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