Factorial program in python

Last updated 1 week, 5 days ago | 35 views 75     5

Tags:- Python

Python | Program to find factorial of a number

This is an example of how to find the factorial of a number in python.

The factorial of a number is a product of all the positive integers less than or equal to that number.
For example, the factorial of 5 is  5x4x3x2x1 = 120

Factorial is not defined for negative integers, and the factorial of zero is one, 0! = 1.

Check here for factorial recursive way

n = int(input('Enter no.:'))
fact = 1
for i in range(1,n+1):
    fact *= i
print(fact)
 

Output for the above code

>>> 
====================== RESTART: E:\py\factorial.py ======================
Enter no.:5
120

let's modify the code to handle number less than or equal to zero

n = int(input('Enter no.:'))
fact = 1

if n < 0:
   print(f"Sorry, factorial does not exist for {n}, negative number")
elif n == 0:
   print("The factorial of 0 is 1")
else:
    for i in range(1,n+1):
        fact *= i

    print(fact)

Output for the above code

>>> 
====================== RESTART: E:\py\factorial.py ======================
Enter no.:5
120
>>> 
====================== RESTART: E:\py\factorial.py ======================
Enter no.:0
The factorial of 0 is 1
>>> 
====================== RESTART: E:\py\factorial.py ======================
Enter no.:-5
Sorry, factorial does not exist for -5, negative number