
Python Program to Find the Factorial of a Number
If you’re new to Python or if you’re new to the programming world, then you must face this question.
It’s a very common question and as a beginner, you just need to know how to solve this question. In this article, I will show you that, how to find the factorial of a number in Python. It’s really easy to do.
Python Program to Find the Factorial of a Number
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) num = int(input("Enter a number: ")) print("The factorial of", num, "is", factorial(num))
In this program, the function factorial(n)
uses recursion to calculate the factorial of the input number n
. The base case for the recursion is when n
is equal to 0, in which case the function returns 1. Otherwise, the function returns n
multiplied by the factorial of n-1
.
The user input is taken with the input()
function, which returns a string. So we need to convert it to an integer using int()
a function.
The program then calls the factorial(num)
function and prints the result.
Input:
Enter a number: 3
Output:
The factorial of 3 is 6
Hi techview71.com owner, Your posts are always well-written and easy to understand.
Hi techview71.com owner, Your posts are always a great read.