Hey guys, in this blog we will see a Python Program to Find the Factorial of a Number in two ways.
In the first way, we will simply use for loops to calculate the factorial of the number provided by the user and in the second way, we will use recursion to calculate the factorial of the number input by the user.
Example 1: Factorial of a number using For-Loop
# Python program to find the factorial of a number provided by the user. # To take input from the user num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial)
Output
Enter a number: 5 The factorial of 5 is 120
Enter a number: -1 Sorry, factorial does not exist for negative numbers
Enter a number: 0 The factorial of 0 is 1
Here we have simply used a for-loop to calculate the factorial of a number entered by the user.
For example, the factorial of 5 can be calculated as follow:
5! = 5X4X3X2X1
Example 2: Factorial of a number using Recursion
# Python program to find the factorial of a number provided by the user # using recursion def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: # recursive call to the function return (x * factorial(x-1)) # to take input from the user num = int(input("Enter a number: ")) # call the factorial function result = factorial(num) print("The factorial of", num, "is", result)
Output
Enter a number: 5 The factorial of 5 is 120
Enter a number: -1 Sorry, factorial does not exist for negative numbers
Enter a number: 0 The factorial of 0 is 1
- Here we have used the concept of recursion to calculate the factorial of a number entered by the user.
- For example, the factorial of 5 can be calculated as follow:
5! = 5X4!
4! = 4X3!
3! = 3X2!
2! = 2X1!
Check out our other python programming examples…