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)}.")
Code Explanation:
1. Factorial Function Definition:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
The function factorial(n) calculates the factorial of a number n recursively.
The base case for the recursion is when n is 0 or 1:
factorial(0) = 1
factorial(1) = 1
This is because the factorial of both 0 and 1 is defined as 1.
For any other value of n greater than 1, the function returns n * factorial(n - 1). This is the recursive call that keeps reducing n by 1 until it reaches 1.
For example:
factorial(5) will calculate 5 * factorial(4)
factorial(4) will calculate 4 * factorial(3)
factorial(3) will calculate 3 * factorial(2)
factorial(2) will calculate 2 * factorial(1)
Once factorial(1) is reached, it returns 1, and all the previous recursive calls return their results back, giving us the final answer.
2. Taking User Input:
num = int(input("Enter a number: "))
This line takes an integer input from the user and stores it in the variable num.
input() reads input as a string, so int() is used to convert it into an integer.
3. Checking for Negative Input:
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
print(f"The factorial of {num} is {factorial(num)}.")
This block checks if the input number is negative.
If the number is negative, it prints: "Factorial is not defined for negative numbers." because the factorial is only defined for non-negative integers (0, 1, 2, 3, ...).
If the number is not negative, it calls the factorial() function and prints the result using print().
Example Execution:
Input:
Enter a number: 5
Step-by-Step Explanation:
The user inputs 5 which is stored in num.
The if condition checks if the number is negative (num < 0). Since 5 is not negative, it proceeds to the else block.
The factorial(5) function is called:
factorial(5) → 5 * factorial(4)
factorial(4) → 4 * factorial(3)
factorial(3) → 3 * factorial(2)
factorial(2) → 2 * factorial(1)
factorial(1) returns 1
Now, all the recursive calls return their results:
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
The final result 120 is printed: "The factorial of 5 is 120."
#source code --> clcoding.com
0 Comments:
Post a Comment