Python factorial program

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

num = int(input("Enter a number: "))
print("Factorial of", num, "is", factorial(num))

Here’s how this program works:

  • It defines a function called factorial that takes one argument, n.
  • If n is 0, the function returns 1 (since 0! = 1).
  • Otherwise, it recursively calculates the factorial of n-1, multiplies it by n, and returns the result.
  • The program then prompts the user to enter a number, calculates the factorial of that number using the factorial function, and prints the result.

Output

Enter a number: 5
Factorial of 5 is 120

Leave a comment