Calculate Factorial in Python Using For Loop W3Schools Tutorial

Logan Jul 13, 2026

Factorials, the product of all positive integers up to some number, are fascinating in mathematics and form the foundation of several other concepts. When dealing with factorials in Python, many programmers turn to the built-in `math` library, but what if you want to write a simple function from scratch? The W3Schools website provides a useful guide, and today we'll explore how to calculate factorials using a for loop, just like the one you might find on W3Schools.

How to use while loops in Python
How to use while loops in Python

Before diving into the code, let's understand the concept of factorials better. If you have a function `f(n) = n!`, it means that `f(n)` is the product of all positive integers up to `n`. For instance, `5! = 5 * 4 * 3 * 2 * 1 = 120`.

For Loop vs While Loop in Python — Explained Simply 🐍
For Loop vs While Loop in Python — Explained Simply 🐍

The Basic Idea of Factorials with a For Loop

The `for` loop in Python is a versatile tool we can use to calculate factorials. The main idea is to start with the number you want the factorial of and multiply it by all the positive integers less than it until you reach 1.

Python while Loop: Python Tutorial on while Loop with Examples
Python while Loop: Python Tutorial on while Loop with Examples

Let's look at this conceptually first. If we want to find `5!`, we'd multiply `5` by `4`, then by `3`, then by `2`, and finally by `1`. This is akin to having a `for` loop count down from `5` to `1` and performing the multiplication at each step.

Manuel Factorial Calculation

Python For Loop Explained 🐍 | Complete Beginner Cheat Sheet
Python For Loop Explained 🐍 | Complete Beginner Cheat Sheet

If you calculate factorials with pencil and paper, it might look something like this:

  1. Start with `5`.
  2. Multiply it by `4`, giving us `20`.
  3. Multiply that result by `3`, giving us `60`.
  4. Multiply that by `2`, giving us `120`.
  5. Finally, multiply it by `1`, which leaves us with `120` as our final answer.

Each of these steps is essentially one iteration of a `for` loop.

18 Python while Loop Examples and Exercises
18 Python while Loop Examples and Exercises

Initializing the Factorial Variable

In Python, you'd start by initializing a variable to hold the factorial result. For `5!`, you'd initialize it to `5`. Then, as you iterate through the numbers, you'd simply multiply the current result by the next number in the sequence. Here's an example:

result = 5

  • Multiply `result` by `4`, giving us `20`.
  • Multiply `result` by `3`, giving us `60`.
  • Multiply `result` by `2`, giving us `120`.
  • Finally, multiply it by `1`, which leaves us with `120` as our final answer.

Power Function in Python Using a Loop
Power Function in Python Using a Loop

Writing the Factorial Function in Python

Now that we understand the logic behind the `for` loop, let's write a simple Python function that calculates factorials. The function takes one argument, `n`, and returns its factorial.

Python Loops Explained (For Loop & While Loop Guide)
Python Loops Explained (For Loop & While Loop Guide)
While loop in Python Easy to learn 🤩
While loop in Python Easy to learn 🤩
For Loop in Python (Complete Guide)
For Loop in Python (Complete Guide)
the instructions for how to use python loops
the instructions for how to use python loops
python Loops for loop and while loop
python Loops for loop and while loop
Python Loops Explained for Beginners (Easy Guide)
Python Loops Explained for Beginners (Easy Guide)
Loops in Python | For, While, Do While Loops | Python Course | Using Different Types of Python Loops
Loops in Python | For, While, Do While Loops | Python Course | Using Different Types of Python Loops
Python Exit For Loop with Example Programs
Python Exit For Loop with Example Programs
Python While Loop | How to Use While Loops?| Continue | Break ⋆ IpCisco
Python While Loop | How to Use While Loops?| Continue | Break ⋆ IpCisco
Python Loops Cheat Sheet
Python Loops Cheat Sheet
Coding For Beginners Python - Learn the Basics - Loops
Coding For Beginners Python - Learn the Basics - Loops
For Loop vs While Loop in Python | Key Differences Explained
For Loop vs While Loop in Python | Key Differences Explained
Python for loop
Python for loop
Loops in Python 💻
Loops in Python 💻
Looping Lines Can Make Great Patterns in Python Turtle
Looping Lines Can Make Great Patterns in Python Turtle
Python Loops (Beginner Friendly)
Python Loops (Beginner Friendly)
While Loop in Python | Syntax, Example
While Loop in Python | Syntax, Example
Python For Loop | How To Use Python For Loops? | For Loops ⋆
Python For Loop | How To Use Python For Loops? | For Loops ⋆
Python Control Flow for Beginners – If Else, For Loop, While Loop Explained
Python Control Flow for Beginners – If Else, For Loop, While Loop Explained

Function Anatomy

The structure of our function will look something like this:

```python def factorial(n): # Initialize result result = n # Use a for loop to iterate through the numbers down to 1 for i in range(n - 1, 0, -1): # Multiply the result by the current number result *= i return result ```

Here, the `for` loop starts at `n - 1` and counts down to `0` (Python's range function goes up to the stop value minus one. By starting at `n - 1` and decrementing, we stop at `1`). At each iteration, we multiply the current result by the loop variable, `i`.

Testing the Function

You can test the function by calling it with different inputs:

```python print(factorial(5)) # Output: 120 print(factorial(10)) # Output: 3628800 ```

These outputs match our manually calculated factorials, indicating that our function is working correctly.

Error Handling

To make our function more robust, we should add error handling to manage invalid inputs:

```python def factorial(n): # Check if n is a non-negative integer if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer") # Initialize result and use the for loop result = n for i in range(n - 1, 0, -1): result *= i return result ```

This version of the function raises a `ValueError` if the input is invalid.

Performance Considerations

While our simple factorial function works well for small numbers, it's not the most efficient for large factorials. Specifically, it has a time complexity of O(n), which means it scales linearly with the input size. This can cause performance issues for large inputs, as the number of multiplications grows with each additional factor.

Thankfully, there are more efficient methods to calculate factorials, including recursion and dynamic programming. However, these optimizations are beyond the scope of this discussion and are left as an exercise for the curious reader.

In conclusion, calculating factorials in Python using a `for` loop is a straightforward affair. By understanding the underlying math and writing thoughtful, efficient code, we can create functions that not only perform their intended task but also evolve in the broader scope of programming expertise. So, keep practicing, keep learning, and above all, keep your curiosity about numbers burning bright.