Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Examples
  3. Calculate a Factorial

Loops · Python example

Calculate a Factorial

Multiply numbers in a loop to compute n! with a loop.

Open the compilerAll examples
beginnerfor loopaccumulatorfactorial

A factorial multiplies every positive integer up to n. The example uses an accumulator variable that grows on each iteration.

example.py
number = 6
result = 1

for value in range(2, number + 1):
    result *= value

print(f"{number}! = {result}")

How the code works

  • The loop multiplies result by 2, 3, 4, 5, and 6.
  • After the loop, result is 720.
  • The formatted message prints the final value.

Key ideas

  • result starts at 1, the identity value for multiplication.
  • range(2, number + 1) includes the number itself.
  • result *= value is shorthand for result = result * value.

Try changing it

  • Use math.factorial(number) from the standard library.
  • Compute the factorial with a recursive function.
  • Validate that the input is non-negative before looping.

Related examples

beginner

Fibonacci Series

Generate the first n Fibonacci numbers with parallel assignment.

beginner

Multiplication Table

Print a ten-row multiplication table with a for loop and range().

Previous exampleMultiplication TableNext exampleFibonacci Series

Expected output

6! = 720

Output is compared after trimming trailing whitespace on each line. Run the code to see it produced by CPython in your browser.

Practice next

Apply the same idea with automatic tests or browse a guided project.

ExercisesProjects