Python Program to Find the Factorial of a Number

Python Program to Find the Factorial of a Number

In this tutorial, we will learn about how to create a factorial program in python.

Explanation ✏

  1. First, we take input from the user.
  2. Then, create a variable and assign 1 to it.
  3. Now, with the help of for loop ranging from 1 till n+1 we will multiply user input (num) with the temporary variable (x) and store it into the num variable.
  4. Finally, print the output.

Code 👩‍💻

def factorial(n):
    num = 1
    for i in range(1,n+1):
        num = num*i
    return num
print(factorial(int(input("Enter a number: "))))

Example: Factorial of 4 is 432*1 = 24

Steps 📑

When num = 1 and i = 1

  • num = 1*1 = 1

When num = 1 and i = 2

  • num = 1*2 = 2

When num = 2 and i = 3

  • num = 2*3 = 6

When num = 6 and i = 4

  • num = 6*4 = 24

image.png