Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com

Python Program to Find the Factorial of a Number What is factorial?

1 min read

 

Python Program to Find the Factorial of a Number

What is factorial?

Factorial is a non-negative integer. It is the product of all positive integers less than or equal to that number you ask for factorial. It is denoted by an exclamation sign (!).

Example:

  1. n! = n* (n-1) * (n-2) *........1  
  2. 4! = 4x3x2x1 = 24    

The factorial value of 4 is 24

Example -

  1. num = int(input("Enter a number: "))    
  2. factorial = 1    
  3. if num < 0:    
  4.    print(" Factorial does not exist for negative numbers")    
  5. elif num == 0:    
  6.    print("The factorial of 0 is 1")    
  7. else:    
  8.    for i in range(1,num + 1):    
  9.        factorial = factorial*i    
  10.    print("The factorial of",num,"is",factorial)    

Output:

Enter a number: 10
The factorial of 10 is 3628800

Explanation -

In the above example, we have declared a num variable that takes an integer as an input from the user. We declared a variable factorial and assigned 1. Then, we checked if the user enters the number less than one, then it returns the factorial does not exist for a negative number. If it returns false, then we check num is equal to zero, it returns false the control transfers to the else statement and prints the factorial of a given number.

Using Recursion

Python recursion is a method which calls itself. Let's understand the following example.

Example -

  1. # Python 3 program to find  
  2. # factorial of given number  
  3. def fact(n):  
  4.     return 1 if (n==1 or n==0else n * fact(n - 1);  
  5.   
  6. num = 5  
  7. print("Factorial of",num,"is",)  
  8. fact(num))  

Output:

Factorial of 5 is 120

Explanation -

In the above code, we have used the recursion to find the factorial of a given number. We have defined the fact(num) function, which returns one if the entered value is 1 or 0 otherwise until we get the factorial of a given number.

Using built-in function

We will use the math module, which provides the built-in factorial() method. Let's understand the following example.

Example -

  1. # Python  program to find  
  2. # factorial of given number  
  3. import math  
  4. def fact(n):  
  5.     return(math.factorial(n))  
  6.   
  7. num = int(input("Enter the number:"))  
  8. f = fact(num)  
  9. print("Factorial of", num, "is", f)  

Output:

Enter the number: 6
Factorial of 6 is 720

We have imported the math module that has factorial() function. It takes an integer number to calculate the factorial. We don't need to use logic.

Post a Comment

© 2025Python . The Best Codder All rights reserved. Distributed by