Skip to main content

Repeating Code with for Loops

Before writing complex programs, we need to understand how to make the computer repeat actions automatically.


1. Why Do We Need Loops?

Imagine your program needs to print "Hello Python!" 5 times on the screen.

Without loops, you have to manually copy and paste 5 lines of code. If you needed to print it 1,000 times, you would have to write 1,000 lines!

With a loop, you write the instruction once and tell Python to repeat it automatically:

Comparison: Printing 5 Times

WITHOUT LOOPS (Manual & Repetitive)
print("Hello Python!")
print("Hello Python!")
print("Hello Python!")
print("Hello Python!")
print("Hello Python!")
WITH A FOR LOOP (Clean & Automatic)
for i in range(5):
  print("Hello Python!")

2. What is a Loop?

Definition: A Loop is a programming feature that automatically repeats a block of code multiple times.

What is a "Block of Code"?

A block of code is a group of code lines that belong together. In Python, code blocks are created using Indentation (4 spaces pushing the lines to the right).

Why Python Uses Indentation:

Python uses indentation to clearly understand which lines of code belong inside the loop body and should be repeated, and which lines are outside the loop and should run after the loop completes.

Block of Code and Execution Order Visual Guide
Click to enlarge

Visual Guide: Understanding Python Indentation, Block of Code, and Execution Order.


3. Introduction to for Loop

A for loop is used to process items from a sequence one by one.

Before looking at syntax or numbers, remember this key concept:

A for loop processes items from a sequence.

Real-World Analogy:

  • Fruit Basket: Imagine picking up apples from a basket one by one. You pick up Apple 1, inspect it, pick up Apple 2, inspect it... until the basket is empty.
  • Teacher Taking Attendance: A teacher reads student names from a register one by one: Student 1, Student 2, Student 3... until the list ends.

In both cases, you perform an action on each item, one by one. That is exactly how a for loop works!


4. Understanding the Basic Structure of a for Loop

First, let me look at the generic structure of a for loop:

for item in sequence:
block of code

Let me break down each part separately:

for keyword

  • It is a reserved Python keyword that starts the loop instruction.
  • for controls the iteration process. It repeatedly gets the next value from the sequence, stores it in the loop variable, and executes the block of code.

item / variable

  • It is a normal variable created by the programmer.
  • It stores the current value during each iteration (round).
  • It is not a special keyword. i is commonly used as a short variable name, but any valid variable name can be used (e.g., for number in range(5):).

in keyword

  • in connects the loop variable with the source of values.
  • In simple words: it tells Python where the values should come from.
  • for item in sequence: means: "Take each item from this sequence and store it in the variable item."

sequence

  • A sequence is an ordered collection of items where each item has a position.
  • Examples of sequences include:
    • Numbers
    • Strings (text)
    • Lists
    • range()

block of code

  • The indented lines of code (4 spaces) that execute repeatedly for every item in the sequence.

5. Understanding range()

Now that we understand for, variable, in, and sequence, how do we get a sequence of numbers?

A for loop needs a sequence to go through. When we want a sequence of numbers, we use range().

range() provides a sequence of numbers for the for loop to iterate through.

Example:

range(5) creates the number sequence:

0, 1, 2, 3, 4

Important: range() only provides values. It does not perform the looping itself; the for loop performs the iteration over those values.

For example, you can store the sequence generated by range() in a variable first:

numbers = range(5)

for i in numbers:
print(i)

range() is not directly connected only with for syntax. It creates a sequence of numbers that can be stored in a variable and later used by a for loop.


6. How for i in range() Works Step by Step

Let's trace how Python executes a for loop step by step:

for i in range(3):
print(i)

Step-by-Step Execution:

  • Step 1: range(3) provides the sequence of values: 0, 1, 2.
  • Step 2: for takes the first value 0:
    • i = 0
    • The block executes: print(0)Output: 0
  • Step 3: for takes the next value 1:
    • i = 1
    • The block executes: print(1)Output: 1
  • Step 4: for takes the next value 2:
    • i = 2
    • The block executes: print(2)Output: 2
  • Step 5: No values are left in the sequence, so the loop stops automatically.
0
1
2

Simple Mental Model:

  • range() → Provides values
  • in → Connects the loop variable with the source of values
  • for → Controls iteration, takes values one by one, and repeats the block
  • i → Stores the current value
  • block → Executes the task for each value

7. range() Variations

You can customize range() by providing different arguments:

1. range(stop)

Generates numbers starting from 0 up to (but not including) stop:

for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4

2. range(start, stop)

Generates numbers starting from start up to (but not including) stop:

for i in range(1, 6):
print(i)
# Output: 1, 2, 3, 4, 5

3. range(start, stop, step)

Generates numbers starting from start, stopping before stop, incrementing by step:

for i in range(2, 11, 2):
print(i)
# Output: 2, 4, 6, 8, 10

8. for Loop is Not Limited to range()

Until now, we used range() to provide numbers to a for loop. But remember, a for loop does not care where the values come from. It only processes items one by one from a sequence.

A for loop only needs a sequence that can provide items one by one. range() is only one source of values.

A for loop can work with different sequences like:

  • range() (numbers)
  • Strings (text characters)
  • Lists (collections of items)

Example 1: Using range()

for number in range(5):
print(number)

9. Looping Through Strings

for loops are not just for numbers! Any sequence can be used with a for loop.

A String (text) in Python is an ordered sequence of individual characters.

word = "Python"

for letter in word:
print(letter)

Output:

P
y
t
h
o
n

10. Common Beginner Mistakes

❌ Mistake 1: Thinking i is a Mandatory Keyword

  • Wrong Thought: "I must write i in every for loop."
  • Correction: i is just a normal variable name. You can use for letter in word:, for number in range(5):, or any descriptive name.

❌ Mistake 2: Forgetting Indentation

  • Wrong Code:
    for i in range(3):
    print(i) # SyntaxError!
  • Correction: Always indent the loop body by 4 spaces so Python knows which code belongs inside the loop.

❌ Mistake 3: Confusing range() with the Loop Itself

  • Wrong Thought: "The range() function does the looping."
  • Correction: range() provides values. The for loop performs iteration over those values.

Quick Summary

ConceptMeaning
LoopA feature that automatically repeats a block of code.
forPython keyword that iterates over elements of any iterable sequence.
inConnects the loop variable with the sequence source.
range(start, stop, step)Generates an arithmetic progression of numbers up to (stop - 1).
Loop VariableTemporary variable storing the current element in each iteration.
Indentation4 spaces required to define the loop block.

What's Next?

A for loop repeats code over a fixed sequence. But what if you want to repeat code until a condition changes (like playing a game while you still have lives)? Let's learn about while loops next!