In this tutorial, we will learn about how to create a factorial program in python.
Explanation ✏
- First, we take input from the user.
- Then, create a variable and assign 1 to it.
- 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.
- 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