Factorial program in Python using 4 different ways
Here you will know that how to make factorial program in python programming using four different ways.
What is factorial in python
Factorial is calculated by multiplying the number from all numbers below that number.
For example, the factorial of 5 is equal to
5 × 4 × 3 × 2 × 1 = 120.
Factorial program in Python using For Loop
1 2 3 4 5 6 7 8 9 | num = int(input("Enter a number: ")) if num < 0: print("Factorial not defined for negative number.") else: result = 1 for i in range(1, num + 1): result *= i print(f"The factorial of {num} is: {result}") |
Output
Enter a number: 5
The factorial of 5 is 120
Factorial program in Python using While Loop
1 2 3 4 5 6 7 8 9 | num = int(input("Enter a number: ")) factorial = 1 while num > 0: factorial *= num num -= 1 print("The factorial is:", factorial) |
Output 1
Enter a number: 7
The factorial is: 5040
Output 2
Enter a number: 4
The factorial is: 24
Factorial program in Python using Recursion
1 2 3 4 5 6 7 8 9 10 11 12 | def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) num = int(input("Enter a number: ")) if num < 0: print("Factorial not define for negative number.") else: result = factorial(num) print("The factorial of {num} is: {result}") |
Output
Enter a number: 5
The factorial of 5 is 120
Factorial program in Python using Function
1 2 3 4 5 6 7 8 9 | def factorial(num): factorial = 1 for i in range(1, num+1): factorial *= i return factorial num = int(input("Enter a number: ")) print("The factorial of", num, "is", factorial(num)) |
Output
Enter a number: 5
The factorial of 5 is 120
Check out our other Python examples