The provided Python program is designed to calculate the factorial of a given number. The program defines a function called factorial, which utilizes recursion to compute the factorial. The base case of the recursion is set for when the input is either 0 or 1, in which case the factorial is 1. The user is then prompted to input a number. The program checks whether the entered number is non-negative. If it is, the program calculates the factorial using the defined function and prints the result. If the input is a negative number, the program informs the user that the factorial is not defined for negative numbers. Additionally, if the input is zero, it informs the user that the factorial of 0 is 1. The program provides a comprehensive solution for calculating factorials, handling various scenarios with informative messages for the user.
Source code
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Get input from the user
num = int(input("Enter a number: "))
# Check if the number is non-negative
if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1")
else:
result = factorial(num)
print(f"The factorial of {num} is {result}")
Description
- Function Definition:
def factorial(n):- The program defines a function named
factorialthat takes a parametern.
- The program defines a function named
- Base Case Check:
if n == 0 or n == 1: return 1- This part of the function checks if the value of
nis either 0 or 1. If true, it returns 1, as the factorial of 0 and 1 is 1.
- This part of the function checks if the value of
- Recursion:
else: return n * factorial(n - 1)- If
nis not 0 or 1, the function recursively calls itself with the argumentn - 1and multiplies the result byn. This recursive step continues until it reaches the base case.
- If
- User Input:
num = int(input("Enter a number: "))- The program prompts the user to input a number, and the input is converted to an integer (
int) for numerical operations.
- The program prompts the user to input a number, and the input is converted to an integer (
- Input Validation:
if num < 0: print("Factorial is not defined for negative numbers.")- The program checks if the entered number is negative. If so, it prints a message indicating that the factorial is not defined for negative numbers.
- Calculate and Display Factorial:
elif num == 0: print("The factorial of 0 is 1") else: result = factorial(num) print(f"The factorial of {num} is {result}")- If the entered number is non-negative and not 0, it calculates the factorial using the
factorialfunction and prints the result. If the input is 0, it prints a message stating that the factorial of 0 is 1.
- If the entered number is non-negative and not 0, it calculates the factorial using the
This code structure ensures proper calculation and handling of factorials for various scenarios, including negative numbers and 0.
Screenshot

