Python Program to Find Factorial of a Number

In this tutorial, we will discuss python program to find factorial of a number.

Before going to the program first, let us understand what is a Factorial Number.

Factorial Number:

  • The factorial of a non-negative integer nn is the product of all positive integers less than or equal to nn.
  • For example, the factorial of 5 (denoted as 5!) is 120.

Related:  Python Program to Find Perfect Number

Program code for finding factorial of a number in Python

# Factorial Program in Python
def factorial(num):
    if num == 0 or num == 1:
        return 1
    else:
        return num * factorial(num - 1)

number = int(input("Enter a number: "))
print(f"The factorial of {number} is {factorial(number)}.")

Explanation

  1. Function Definition: The factorial function takes an integer num as input and returns the factorial of the number.
  2. Base Case: If the number is 0 or 1, the function returns 1.
  3. Recursive Case: For any other number, the function recursively calls itself with the number decremented by 1.
  4. Main Program: The program prompts the user to enter a number and then calculates the factorial using the factorial function.

Output

Python Program to Find Factorial of a Number

  • When you run the above program, it will prompt you to enter a number.
  • After entering the number, it will calculate the factorial of the number and print the result.

Conclusion

  • In this tutorial, we learned how to calculate the factorial of a given number using a Python program.
  • Understanding this concept is essential for solving various mathematical problems and competitive programming challenges.
  • Practice this example to enhance your programming skills and understanding of factorials.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *