Exercise
Function To Compute Factorial
Objective
Develop a Python program with a recursive function to compute the factorial of a given number. The factorial of a number is defined as:
n! = n × (n-1) × (n-2) × (n-3) × ... × 3 × 2 × 1
For example, 6! = 6 × 5 × 4 × 3 × 2 × 1
Create a function to calculate the factorial of the number specified as a parameter. For instance, if you call factorial(6), it should display 720.
Example Python Exercise
Show Python Code
# Define the recursive factorial function
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n! = n * (n-1)!
return n * factorial(n - 1)
# Main function to test the factorial function
def main():
number = 6
print(factorial(number)) # This should print 720
# Call the main function to execute the program
if __name__ == "__main__":
main()
Output
720
Share this Python Exercise