Python Program Find Factorial Of A Number

2 min read

The factorial of a number is the product of all the integers from 1 to that number. Mathematically, the formula for the factorial is as follows. If n is an integer greater than or equal to 1, then factorial of n is,

 (n!) = 1*2*3*4....*n

Also, the factorial value of 0 is equal to 1 and the factorial values for negative integers are not defined.

Problem Definition

Create a Python Program to find the factorial of the user-provided number.

Program

num = int(input("Enter the Number :"))

fact = 1

if num < 0:
    print("Factorial of negative number is not defined")
else:
    for i in range(1,num+1):
        fact *= i
    print("Factorial of {} is {}".format(num, fact))

Output

Enter the Number :7
Factorial of 7 is 5040

In this program first, we are taking input from the keyboard using the input() function then we have a conditional statement for negative inputs since factorial of a negative number doesn't exist.

Then we have a for loop in range 1 to the number itself inside the loop we are simply iterating over loop variable i and multiplying it with the fact variable defined above. In the end, we are simply printing out the result using string formatting.

The same program can be implemented using a while loop as follows,

num = int(input("Enter the Number :"))

fact = 1
i = 1

if num < 0:
    print("Factorial of negative number is not defined")
else:
    while(i<=num):
        fact *= i
        i += 1
    print("Factorial of {} is {}".format(num, fact))

Output

Enter the Number :6
Factorial of 6 is 720

Since Python always has a better way of doing things, it comes with a built-in solution for computing factorial of a number.

from math import factorial

num = int(input("Enter the Number :"))

fact = factorial(num)

if num < 0:
    print("Factorial of negative number is not defined")
else:
    print("Factorial of {} is {}".format(num, fact))

Output

Enter the Number :5
Factorial of 5 is 120

The math library which ships with Python has a factorial() method that returns the factorial of the provided number.


PROGRAMS

Latest Articles

Latest from djangocentral

Capturing Query Parameters of request.get in Django

In Django, the request object contains a variety of information about the current HTTP request, including the query parameters. Query parameters are a way to pass additional information in the URL and are used to filter or sort data. The request object p…
Read more →

2 min read

Understanding related_name in Django Models

In Django, related_name is an attribute that can be used to specify the name of the reverse relation from the related model back to the model that defines the relation. It is used to specify the name of the attribute that will be used to access the relat…
Read more →

2 min read