Zed-King Institute

    Python Program to Find Factorial of a Number

    mediumFunctionsPython

    Factorial (n!) is n × (n − 1) × … × 1. Writing it as a function is one of the most common PR-3 questions.

    The question

    Write a function factorial(n) that returns n! using a loop. Read n and print its factorial by calling your function.

    The code

    program.py

    def factorial(n):
        result = 1
        for i in range(2, n + 1):
            result *= i
        return result
    
    n = int(input())
    print("Factorial of", n, "is", factorial(n))

    Input

    10

    Output

    Factorial of 10 is 3628800

    How it works

    1. 1def factorial(n): creates a reusable function.
    2. 2result starts at 1 (starting at 0 would make every product 0).
    3. 3The loop multiplies result by every number from 2 to n.
    4. 4return sends the answer back to the line that called the function.

    Common mistakes

    • Starting result at 0 — the answer is always 0.
    • Printing inside the function instead of returning — the question asks for a function that returns n!.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Functions