Finding Factorial in Python

Python: Find the Factorial of a Number

In this blog, Let us see how to write a Python program to find the factorial of a number

using the recursion function.


Code:

n= int(input("Enter a number:"))
def factorial(n):
    fact=1
    if n == 1 or n == 0:
        return 1
    else:

        return n*factorial(n-1)

print(factorial(n))

Output:

Enter a number:5
120

Explanation:

  1. The first line prompts the user to enter a number by using input() function, the entered value is converted into an integer using int() function then the value is assigned to the variable n.
  2. Next we are defining a function called factorial with an parameter n with in it, entered argument(value) will be passed to the parameter n.
  3. Then we initializes the variable fact with a value 1, which helps to store the factorial of n.
  4. The conditional statement if is used to check the value of n is equals to 0 or 1, if it is true then it returns 1.
  5. Otherwise, the else part will be executed that is the function calls itself recursively with an input argument n-1 and the result is multiplied by n.
  6. The result is returned and the factorial of the number is printed.

Post a Comment

Previous Post Next Post