Welcome back, coding adventurer! In the previous chapters, we learned how to store information in variables, make decisions with if statements, and organize our code. That’s a fantastic start!
But what if you need to do the same thing, or a very similar thing, multiple times? Imagine you have a list of 100 names and you need to print a greeting for each one. Would you write print() 100 times? That sounds incredibly tedious and inefficient, right?
This is where loops come to the rescue! In this chapter, we’re going to unlock the power of repetition. You’ll learn how to tell your Python programs to perform actions over and over again, saving you tons of time and making your code much smarter. We’ll explore two fundamental types of loops: for loops and while loops, and see how they help us automate repetitive tasks with Python 3.14.1, the latest stable release as of December 2nd, 2025.
By the end of this chapter, you’ll be able to:
- Understand what loops are and why they are essential.
- Use
forloops to iterate over sequences like numbers and lists. - Master
whileloops for repeating actions based on a condition. - Control loop behavior with
breakandcontinuestatements. - Apply loops to solve practical problems, making your code dynamic and powerful!
Ready to make your computer do the heavy lifting? Let’s dive in!
The Magic of Repetition: Why Loops Are Your New Best Friend
Think about your daily routine. Maybe you brush your teeth every morning, or perhaps you stir your coffee until the sugar dissolves. These are repetitive actions, and you perform them until a certain condition is met (e.g., teeth are clean, sugar is dissolved).
In programming, we often encounter similar scenarios:
- Processing every item in a shopping cart.
- Counting down from 10 to 0.
- Asking a user for input until they provide a valid response.
- Drawing each pixel on a screen.
Manually writing code for each repetition would be a nightmare. Loops provide a concise and elegant way to tell Python, “Hey, do this thing X times,” or “Keep doing this thing as long as Y is true.” They are fundamental to almost any program you’ll ever write!
Let’s start with a very common type of loop: the for loop.
for Loops: Iterating Over Collections
The for loop is Python’s go-to tool for iterating. “Iterating” just means going through items one by one. If you have a collection of things – like a list of numbers, a string of characters, or a range of values – a for loop lets you process each item in that collection sequentially.
The range() Function: Your Loop’s Best Companion
Before we write our first for loop, we need a way to generate sequences of numbers. That’s where the built-in range() function comes in! range() is incredibly useful for creating sequences that a for loop can then iterate over.
Imagine you want to count from 0 to 4. You could do this manually, but range(5) will generate those numbers for you.
Let’s see how range() works. Open your Python interpreter or a new script file.
Understanding range(stop)
When you give range() one argument, it generates numbers starting from 0 up to (but not including) that number.
# This generates numbers 0, 1, 2, 3, 4
my_range = range(5)
print(list(my_range)) # We use list() to see the numbers it generates
Explanation:
range(5)creates a “range object” that knows how to produce numbers from 0 up to 4. It doesn’t create the entire list in memory immediately, which is efficient for very large ranges.list()is used here just to convert that range object into a visible list of numbers so you can see what it’s generating. You won’t usually needlist()when usingrange()with aforloop.
What to observe: The output is [0, 1, 2, 3, 4]. Notice it stops before 5. This is a common pattern in computer science (zero-based indexing, exclusive end).
Understanding range(start, stop)
You can specify a starting number too! range(start, stop) generates numbers from start (inclusive) up to stop (exclusive).
# This generates numbers 3, 4, 5, 6
my_range_with_start = range(3, 7)
print(list(my_range_with_start))
What to observe: The output is [3, 4, 5, 6]. It starts at 3 and goes up to, but not including, 7.
Understanding range(start, stop, step)
Want to count by twos, or threes, or even backwards? The step argument lets you do that!
# This generates numbers 0, 2, 4, 6, 8 (counting by 2s)
my_range_with_step = range(0, 10, 2)
print(list(my_range_with_step))
# Counting backwards!
my_range_backwards = range(5, 0, -1) # Start 5, stop before 0, step -1
print(list(my_range_backwards))
What to observe:
[0, 2, 4, 6, 8]for the first one.[5, 4, 3, 2, 1]for the second one. Excellent!
Now that we know how range() works, let’s use it with a for loop!
Your First for Loop!
Let’s make our Python program count from 1 to 5.
# Save this as `first_loop.py`
print("Starting the countdown...")
for number in range(1, 6):
print(number)
print("Countdown finished!")
Explanation:
print("Starting the countdown..."): Just a friendly message before the loop begins.for number in range(1, 6):: This is the heart of theforloop.for: The keyword that starts aforloop.number: This is a loop variable. In each iteration of the loop, it will take on the value of the next item generated byrange(1, 6). You can name this variable anything descriptive (i,item,index, etc.).in: This keyword means “in this sequence”.range(1, 6): Our trustyrange()function, which will produce numbers 1, 2, 3, 4, 5.:: Remember this colon fromifstatements? It signifies the start of a new indented block of code.
print(number): This line is indented (usually 4 spaces). This indentation is crucial! It tells Python that this line (and any other similarly indented lines) belongs inside theforloop. It will execute once for eachnumberin therange.print("Countdown finished!"): This line is not indented, so it executes after the loop has completely finished its iterations.
Run this script. You should see:
Starting the countdown...
1
2
3
4
5
Countdown finished!
Interactive Challenge: Counting Even Numbers
Can you modify the for loop above to print only the even numbers from 0 to 10 (inclusive)?
- Hint: Think about the
stepargument inrange(). - What to observe: The output should be
0, 2, 4, 6, 8, 10.
Take a moment to try it out before looking at the solution!
Click for Hint
Remember that `range(start, stop, step)` can help you jump values. What should `start`, `stop`, and `step` be for even numbers?Click for Solution
print("Printing even numbers from 0 to 10:")
for num in range(0, 11, 2): # Start at 0, go up to (but not including) 11, step by 2
print(num)
Looping Through Other Collections
for loops aren’t just for numbers! They are perfect for iterating over any sequence, like strings (collections of characters) or lists (collections of items).
Let’s loop through a list of fruits:
# Add this to your `first_loop.py` or a new file
fruits = ["apple", "banana", "cherry", "date"]
print("\nMy favorite fruits are:")
for fruit in fruits:
print(f"I love {fruit}!") # Using an f-string for clear output
Explanation:
fruits = ["apple", "banana", "cherry", "date"]: We define a list of strings.for fruit in fruits:: This loop will take each item from thefruitslist, one by one, and assign it to thefruitvariable.print(f"I love {fruit}!"): Inside the loop, we use an f-string (a modern Python feature from 3.6+ for easy string formatting) to print a personalized message for eachfruit.
What to observe:
My favorite fruits are:
I love apple!
I love banana!
I love cherry!
I love date!
This is incredibly powerful! Imagine if you had a list of hundreds or thousands of items; the same for loop code would work perfectly without needing any changes.
while Loops: Repeating Until a Condition is Met
Sometimes, you don’t know exactly how many times you need to repeat an action. Instead, you want to keep repeating as long as a certain condition is true. This is precisely what a while loop is for!
Think of a while loop like this: “While this condition is still true, keep doing these things.”
The structure of a while loop is:
# Some initial setup
# ...
while condition_is_true:
# Do something
# Make sure to change something that eventually makes condition_is_true false!
Let’s create a simple countdown using a while loop.
# Save this as `while_loop.py`
countdown = 5
print("Starting while loop countdown...")
while countdown > 0:
print(countdown)
countdown = countdown - 1 # Or countdown -= 1 (shorthand)
print("Blast off!")
Explanation:
countdown = 5: We initialize a variablecountdownto 5. This variable will be used in our condition and will change inside the loop.while countdown > 0:: This is our loop’s condition. As long as the value ofcountdownis greater than 0, the code inside thewhileloop will execute.print(countdown): Prints the current value ofcountdown.countdown = countdown - 1: This is crucial! This line decreases the value ofcountdownby 1 in each iteration. If we didn’t do this,countdownwould always be 5,5 > 0would always be true, and our loop would run forever (an infinite loop!).print("Blast off!"): This line runs once thewhileloop’s condition (countdown > 0) becomes false (i.e., whencountdownbecomes 0).
Run this script. You should see:
Starting while loop countdown...
5
4
3
2
1
Blast off!
Important Note on Infinite Loops:
An infinite loop is a common pitfall with while loops. If the condition you’re checking never becomes false, the loop will run forever, potentially freezing your program. Always ensure that something inside your while loop changes the condition, so it eventually evaluates to False. If you accidentally get stuck in an infinite loop, you can usually stop your program by pressing Ctrl+C in your terminal.
Interactive Challenge: Guess the Number
Let’s create a simple “guess the number” game using a while loop. The program should keep asking the user for a guess until they guess the correct number (let’s say 7).
- Hint: You’ll need
input()to get user input andint()to convert it to a number. - What to observe: The loop should only stop when the user types ‘7’.
# Start with this code
secret_number = 7
guess = 0 # Initialize guess to something not equal to secret_number
print("\nGuess the secret number (between 1 and 10)!")
# Your while loop goes here!
# It should keep asking for input until guess == secret_number
# Inside the loop, get user input and convert it to an integer
# Example: guess = int(input("What's your guess? "))
print("Congratulations! You guessed it!")
Click for Hint
Your `while` condition should check if `guess` is *not equal* to `secret_number`. Remember the `!=` operator?Click for Solution
secret_number = 7
guess = 0 # Initialize guess to something not equal to secret_number
print("\nGuess the secret number (between 1 and 10)!")
while guess != secret_number:
try: # We'll learn about try-except later, but it helps handle invalid input now!
guess_str = input("What's your guess? ")
guess = int(guess_str)
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
except ValueError:
print("That's not a valid number. Please enter an integer.")
print("Congratulations! You guessed it!")
Loop Control Statements: break and continue
Sometimes, you might want to alter the normal flow of a loop. Python provides two special keywords for this: break and continue.
break: Exiting a Loop Early
The break statement immediately terminates the current loop (either for or while) and transfers control to the statement immediately following the loop.
Imagine you’re searching a list for a specific item. Once you find it, there’s no need to keep searching the rest of the list. break is perfect for this!
# Add to `while_loop.py` or a new file
items = ["apple", "banana", "grape", "orange", "kiwi"]
search_item = "grape"
print(f"\nSearching for '{search_item}' in the list...")
for item in items:
if item == search_item:
print(f"Found '{search_item}'! Stopping search.")
break # Exit the loop immediately
print(f"Checking {item}...")
print("Search complete.")
Explanation:
- The loop iterates through
items. - When
itembecomes"grape", theifcondition is true. print("Found 'grape'! Stopping search.")is executed.breakis encountered, and theforloop stops entirely. Theprint(f"Checking {item}...")for “orange” and “kiwi” will not be executed.print("Search complete.")is then executed, as it’s outside the loop.
What to observe:
Searching for 'grape' in the list...
Checking apple...
Checking banana...
Found 'grape'! Stopping search.
Search complete.
Notice that “Checking orange…” and “Checking kiwi…” are skipped.
continue: Skipping the Current Iteration
The continue statement skips the rest of the code inside the current loop iteration and moves to the next iteration. The loop doesn’t stop; it just skips a particular pass.
Let’s say you want to process numbers from 1 to 5, but you want to skip number 3.
# Add to your script
print("\nCounting, but skipping 3:")
for i in range(1, 6):
if i == 3:
print("Skipping 3!")
continue # Skip the rest of this iteration, go to the next 'i'
print(i) # This line won't run when i is 3
Explanation:
- When
iis 1, it prints 1. - When
iis 2, it prints 2. - When
iis 3, theif i == 3:condition is true. print("Skipping 3!")is executed.continueis encountered. Theprint(i)statement belowcontinueis skipped for this iteration. The loop immediately jumps to the next value ofi(which is 4).- When
iis 4, it prints 4. - When
iis 5, it prints 5.
What to observe:
Counting, but skipping 3:
1
2
Skipping 3!
4
5
Notice that the print(i) for i=3 was skipped.
Mini-Challenge: Filtering with Loops and continue
Imagine you have a list of temperatures, and some of them are invalid (e.g., None or very low numbers). You want to print only the valid temperatures (let’s say, anything 0 or above).
Challenge:
Write a for loop that iterates through the temperatures list. If a temperature is None or less than 0, use continue to skip it. Otherwise, print the valid temperature.
temperatures = [22, 25, -5, 18, None, 30, -1, 28]
print("\n--- Valid Temperatures ---")
# Your loop here!
- Hint: You’ll need an
ifstatement to check for invalid temperatures. Rememberis Nonefor checkingNonevalues. - What to observe: Only
22, 25, 18, 30, 28should be printed.
Click for Solution
temperatures = [22, 25, -5, 18, None, 30, -1, 28]
print("\n--- Valid Temperatures ---")
for temp in temperatures:
if temp is None or temp < 0:
continue # Skip this iteration if temp is invalid
print(f"{temp}°C") # Print valid temperatures
Common Pitfalls & Troubleshooting
Infinite
whileLoops: This is the most common mistake withwhileloops.- Problem: The condition of your
whileloop never becomesFalse. - Example:
count = 0 while count < 5: print(count) # Forgot to increment count! - Fix: Always ensure there’s a line of code inside your
whileloop that will eventually make the conditionFalse. Forgettingcount += 1or similar updates is the usual culprit. - How to debug: If your program seems stuck, press
Ctrl+Cin your terminal to interrupt it. Then, examine yourwhileloop’s condition and the code inside to see why the condition isn’t changing.
- Problem: The condition of your
Off-by-One Errors with
range():- Problem: Your
forloop usingrange()starts or ends one number too early or too late. - Example:
range(0, 5)gives0, 1, 2, 3, 4(5 numbers). If you wanted 1 to 5, you’d get it wrong. - Fix: Remember
range(start, stop)goes fromstartup to but not includingstop. If you want to includestop, you need to add 1 to it (e.g.,range(1, 6)for numbers 1 through 5). If you wantNiterations starting from 0, userange(N). - How to debug: Mentally trace the first and last few values that
range()will produce, or temporarily useprint(list(range(...)))to see the exact sequence.
- Problem: Your
Incorrect Indentation:
- Problem: Python relies heavily on indentation to define code blocks (what belongs inside the loop). If your indentation is wrong, Python will raise an
IndentationErroror your code won’t behave as expected. - Example:
for i in range(3): print(i) # This will cause an IndentationError - Fix: Always use 4 spaces for indentation. Most code editors (like VS Code) will handle this automatically when you press
Enterafter a colon (:). - How to debug: Python will usually tell you with an
IndentationError. Pay close attention to where your code blocks start and end.
- Problem: Python relies heavily on indentation to define code blocks (what belongs inside the loop). If your indentation is wrong, Python will raise an
Summary
Phew! You’ve just mastered one of the most powerful concepts in programming: loops! Let’s quickly recap what we covered:
- Loops allow your programs to repeat actions efficiently, preventing you from writing repetitive code.
- The
forloop is used for iterating over sequences, processing each item one by one. It’s great when you know how many times you need to repeat or when you’re going through a collection. - The
range()function is a perfect partner forforloops, generating sequences of numbers. Rememberrange(stop),range(start, stop), andrange(start, stop, step). - The
whileloop keeps repeating a block of code as long as a specified condition remains true. It’s ideal when the number of repetitions is unknown beforehand. - Crucial for
whileloops: Always ensure the condition will eventually becomeFalseto avoid infinite loops. breaklets you exit a loop immediately, even if its normal termination condition hasn’t been met.continueskips the rest of the current iteration and moves to the next one in the loop.- We’re rocking Python 3.14.1 – the latest stable release as of December 2025!
You’ve added a fantastic tool to your Python toolbox! Loops are truly fundamental, and you’ll find yourself using them in almost every program you write.
What’s next? Now that you can make your programs repeat actions, it’s time to learn how to organize those actions into reusable blocks of code. In Chapter 5, we’ll dive into Functions, which will allow you to write modular, clean, and even more powerful Python programs! Get ready to define your own commands!