Example of the code
# Python code to calculate the factorial of a number
def calculate_factorial(number):
if number == 0 or number == 1:
return 1
else:
return number * calculate_factorial(number - 1)
# Prompt the user for a number
user_number = int(input("Enter a non-negative integer: "))
# Check if the user entered a non-negative integer
if user_number >= 0:
# Calculate the factorial using the function
result = calculate_factorial(user_number)
# Display the result
print(f"The factorial of {user_number} is: {result}")
else:
# Handle the case where the user didn't enter a non-negative integer
print("Invalid input. Please enter a non-negative integer.")
Explanation:
- Their is a function called calculate_factorial that takes a parameter number. This function will calculate the factorial of the given number using recursion.
- The input function prompts the user to enter a non-negative integer, and int is used to convert the input to an integer.
- The calculate_factorial function is called with user_number as an argument to calculate the factorial.
- The result is then printed using the print function.
- If the user enters a negative number, an error message is displayed.
Output:
The factorial of 5 is: 120