Saturday, 14 December 2024

Day 33 : Python Program to Find the Factorial of a Number using Recursion

 


def factorial(n):

    if n == 0 or n == 1:

        return 1

    else:

    return n * factorial(n - 1)

num = int(input("Enter a number: "))

if num < 0:

    print("Factorial is not defined for negative numbers.")

else:

    print(f"The factorial of {num} is {factorial(num)}.")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition: factorial(n)
This function computes the factorial of a given number 
๐‘›
n using recursion.

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)
Base Case:
if n == 0 or n == 1:
    return 1
If 
๐‘›
n is 0 or 1, the factorial is defined as 1. This serves as the stopping condition for the recursion.
Recursive Case:
return n * factorial(n - 1)
n by the result. This continues until the base case is reached.

How Recursion Works: 

factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1  (Base Case)

Substituting back:

factorial(5) = 5 * 4 * 3 * 2 * 1 = 120

Taking Input from the User
num = int(input("Enter a number: "))
Prompts the user to enter a number.
Converts the user input (a string) into an integer using int().

Handling Negative Input

if num < 0:
    print("Factorial is not defined for negative numbers.")
Factorial is defined only for non-negative integers.
If the input number is negative, the program prints an error message and does not proceed further.

Computing and Printing the Factorial
else:
    print(f"The factorial of {num} is {factorial(num)}.")

If the input is valid (a non-negative number):
The program calls the factorial function with the input num.
The result is printed in a formatted string: f"The factorial of {num} is {factorial(num)}.".



0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (41) AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (225) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (925) Python Coding Challenge (343) Python Quiz (12) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses