Python | Factorial of a number using for loop

Python | Factorial of a number using for loop

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. The factorial of 0 is defined to be 1. The factorial formula can be expressed as:

n! = 1 * 2 * 3 * … * n

Code to calculate factorial of a number using for loop in Python

n = input("Enter number: ")
try:
    n = int(n)
    factorial_result = 1
    if n<0:
        print("Factorial of a negative number is not defined")
    elif n==0:
        print("Factorial of 0 is 1")
    else:
        # factorial of a number using for loop in Python
        for i in range(1, n+1):
            factorial_result = factorial_result * i
        print("Factorial of", n, "is", factorial_result)
except:
    print("Enter positive integer value only")

Output:

output

Also read:

Share:

Author: Yogesh Kumar