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

Django 4.1 adds async-compatible interface to QuerySet

The much-awaited pull request for an async-compatible interface to Queryset just got merged into the main branch of Django.Pull Request - https://github.com/django/django/pull/14843 The Django core team has been progressively adding async suppor…
Read more →

3 min read

Making Django Admin Jazzy With django-jazzmin

Django admin is undoubtedly one of the most useful apps of Django. Over the years there has been very little change in the admin app as far as the UX is concerned and it's not a bad thing at all. Django admin was designed to provide a simple and minimali…
Read more →

4 min read