Imagine you need to write the word “Hello!” 20 times. You could sit there copying print("Hello!") twenty times. But programmers are lazy — in a good way. They invented something called a loop to make the computer handle repetitive work.
One of the most common tools for this is the for loop.
🎠 Meet the for Loop
If we want to repeat an action many times, we write:
for i in range(5):
print("Hello!")
This tiny piece of code prints “Hello!” exactly 5 times. But how does it work? Let’s break it down piece by piece!
for— tells Python “Start the loop!”i— the counter variable (a notepad where the loop tracks progress: “one lap done, two, three…”). We can name it anything, but conventionally it’si(from index).in range(5)—rangemeans range or sequence. We’re literally saying “In the range up to five” — do 5 steps.- The colon
:at the end — signals that the block of commands to repeat is about to follow. - Indentation (4 spaces) — THE MOST IMPORTANT THING in Python! Everything indented to the right (with the Tab key) is
insidethe loop and will be repeated. Anything without indentation runs only once after the loop finishes.
The Difference Indentation Makes
Look at this example to understand the magic of spaces:
for i in range(3):
print("Mining ore...") # Inside the loop (indented)
print("Found gold!") # Inside the loop (indented)
print("I'm tired, going home.") # Outside the loop (no indentation!)
The computer will do this:
- Mining ore…
- Found gold!
- Mining ore…
- Found gold!
- Mining ore…
- Found gold!
- I’m tired, going home.
🔢 The Magic of the Variable i
What is that variable i and why do we need it? At each pass (or iteration), Python doesn’t just “spin the wheel” — it also writes the current step number into i. It counts from zero!
for i in range(3):
print(f"Current step: {i}")
Output:
Current step: 0
Current step: 1
Current step: 2
Notice? There were three steps (0, 1, and 2), but it never reaches the number 3 itself. This is a small quirk of programming — computers love to start counting at 0, not 1!
If at some point you need the count to go from 1 to 5 (inclusive), you can just add one to i (or display i + 1). Or pass two numbers to range(...) — a start and an end! But for simple repetition, the for i in range(N): pattern is usually enough.
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!