Python Tutorials

Python Programs

Python Factorial


Python Factorial

In this tutorial, we will learn how to write a program to calculate the factorial of a number in Python. We will cover the basics of using a loop to compute the factorial.


What is a Factorial

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and is calculated as n! = n × (n-1) × (n-2) × ... × 1. The factorial of 0 is 1.


Syntax

The syntax to calculate the factorial in Python is:

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result


Youtube Learning Video



Calculating the factorial of a number

We can use a loop to calculate the factorial of a number.

For example,

  1. Define a function named factorial that takes one parameter n.
  2. Initialize a variable result to 1.
  3. Use a for loop to iterate from 1 to n (inclusive).
  4. Multiply result by the current number in the loop.
  5. Return the result after the loop ends.
  6. Call the factorial function with the desired number and print the result.

Python Program

def factorial(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# Calculate the factorial of 5
print(factorial(5))

Output

120