Loops – for and while in Python
Learn how to repeat tasks using for and while loops, including iteration over lists and ranges.
Welcome to a deep dive into one of the most fundamental and powerful concepts in programming: loops! If you’ve ever found yourself needing to repeat a task, process every item in a list, or continue an action until a certain condition is met, then loops are your best friend. In Python, we primarily use two types of loops: the for loop and the while loop. Understanding them is crucial for writing efficient, automated, and scalable code.
Today, we’re going to explore both for and while loops in detail, looking at their syntax, common use cases, and advanced features. We’ll cover everything from iterating over simple lists and ranges to handling strings, dictionaries, and even files. We’ll also demystify loop control statements like break and continue, and uncover the often-misunderstood else block for loops.
This blog post is a companion to our YouTube video on Python Loops and the full source code on GitHub. We encourage you to watch the video for visual demonstrations and explore the repository for hands-on practice!
Watch the Video Tutorial
1. The for Loop: Iterating Over Sequences
The for loop in Python is incredibly versatile and is primarily used for iterating over sequences, which could be anything from a list of items to the characters in a string, or even the lines in a file. Think of it as telling your program: ‘For each item in this collection, do something.’ It’s perfect when you know exactly how many times you need to repeat an action, or when you want to process every single element in a definite collection.
1.1. Iterating Over Lists
Let’s start with one of the most common applications: iterating over a list. Instead of writing a separate print statement for every single fruit, which would be incredibly inefficient for a large list, a for loop allows you to process each item elegantly.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f" Current fruit: {fruit}")
The loop takes each element from the sequence, assigns it to a temporary variable (which you name, like fruit in our example), and then executes the indented block of code for that element. This makes your code concise, readable, and highly scalable.
1.2. Iterating Over Ranges of Numbers with range()
Beyond lists, the for loop shines when working with sequences of numbers, especially using Python’s built-in range() function. The range() function is a powerful tool for generating sequences of numbers, and it’s particularly efficient because it generates numbers on-the-fly, without creating a full list in memory.
You can use range() in a few different ways:
range(stop): Generates numbers from 0 up to (but not including)stop.range(start, stop): Generates numbers fromstartup to (but not including)stop.range(start, stop, step): Generates numbers fromstartup to (not including)stop, with the givenstep.
# range(5) generates numbers 0, 1, 2, 3, 4
for i in range(5):
print(f" Number: {i}")
# range(2, 8) generates numbers 2, 3, 4, 5, 6, 7
for j in range(2, 8):
print(f" Number (start, stop): {j}")
# range(0, 11, 2) generates even numbers 0, 2, 4, 6, 8, 10
for k in range(0, 11, 2):
print(f" Even number: {k}")
1.3. Iterating Over Strings and Dictionaries
The for loop isn’t just limited to lists and numbers. It’s incredibly versatile and can iterate over various other iterable objects:
Iterating over a String:
You can easily iterate over the characters in a string, processing each letter individually. This is useful for tasks like counting specific characters or performing text analysis.
word = "Python"
for char in word:
print(f" Character: {char}")
Iterating over a Dictionary:
Dictionaries, which store data in key-value pairs, can also be iterated over using a for loop. By default, a for loop on a dictionary will iterate over its keys. However, Python provides convenient methods like .values() to iterate directly over the dictionary’s values, or .items() to iterate over both keys and values simultaneously as tuples.
student = {"name": "Alice", "age": 25, "major": "CS"}
# Iterating over keys (default)
print(" Keys:")
for key in student: # or student.keys()
print(f" Key: {key}")
# Iterating over values
print(" Values:")
for value in student.values():
print(f" Value: {value}")
# Iterating over key-value pairs (items)
print(" Key-Value Pairs:")
for key, value in student.items():
print(f" {key}: {value}")
1.4. Advanced for Loop Techniques: enumerate() and zip()
Python offers even more powerful ways to iterate using enumerate() and zip():
enumerate() for Index and Value:
The enumerate() function is a game-changer when you need both the item and its index during iteration. Instead of manually managing a counter variable, enumerate() gives you back an index and the corresponding value as a tuple for each iteration.
colors = ["red", "green", "blue", "yellow"]
for index, color in enumerate(colors):
print(f" Index {index}: {color}")
zip() for Parallel Iteration:
zip() allows you to iterate over multiple sequences in parallel. Imagine you have a list of names and a separate list of ages, and you want to combine them. zip() takes elements from each iterable and aggregates them into tuples.
names = ["Alice", "Bob", "Charlie"]
ages = [30, 24, 35]
for name, age in zip(names, ages):
print(f" {name} is {age} years old.")
2. The while Loop: Condition-Controlled Iteration
Moving on from for loops, let’s explore while loops. Unlike for loops, which are best for iterating over sequences or a fixed number of times, while loops are condition-controlled. This means they will keep executing a block of code repeatedly as long as a specified condition remains true.
They are perfect for situations where you don’t know beforehand how many times the loop needs to run, such as waiting for user input or processing data until a certain threshold is reached. The most critical aspect of a while loop is ensuring that the condition eventually becomes false; otherwise, you’ll end up with an infamous “infinite loop.”
2.1. Basic while Loop
A common pattern involves initializing a counter or flag variable before the loop and then modifying it inside the loop’s body to eventually satisfy the exit condition. For instance, a simple countdown uses a while loop, decrementing a counter until it reaches zero.
count = 5
while count > 0:
print(f" Countdown: {count}")
count -= 1 # Decrement the counter
print(" Lift-off!")
3. Loop Control Statements: break and continue
To give you even more control over your loops, Python provides two essential statements: break and continue.
3.1. The break Statement
The break statement allows you to immediately exit the innermost loop that it’s contained within. It’s incredibly useful when you’ve found what you’re looking for, or an error condition occurs, and there’s no need to continue processing the rest of the loop.
secret_number = 7
while True: # Infinite loop until 'break' is encountered
try:
guess = int(input(" Guess the secret number (between 1 and 10): "))
if guess == secret_number:
print(" Congratulations! You guessed it!")
break # Exit the loop
elif guess < secret_number:
print(" Too low! Try again.")
else:
print(" Too high! Try again.")
except ValueError:
print(" Invalid input. Please enter a number.")
3.2. The continue Statement
The continue statement, on the other hand, is used to skip the rest of the code in the current iteration of the loop and move directly to the next iteration. This is handy when you want to filter out certain elements or conditions within your loop without stopping the entire process.
num_to_check = 0
while num_to_check < 10:
num_to_check += 1
if num_to_check % 2 == 0: # If number is even
continue # Skip the rest of the current iteration and go to the next loop cycle
print(f" Odd number: {num_to_check}")
4. The else Block with Loops
One of Python's lesser-known but incredibly useful features with loops is the else block. Yes, for and while loops can have an else block, just like if statements!
The else block associated with a loop will execute only if the loop completes normally, meaning it finishes iterating through its sequence (for a for loop) or its condition becomes False (for a while loop), without encountering a break statement. If a break statement is executed within the loop, the else block is completely skipped.
4.1. for Loop with else
# Example 1: Loop completes normally, else block executes
for num in range(3):
print(f" Processing number {num}")
else:
print(" For loop completed successfully (no 'break' encountered).")
# Example 2: Loop with a 'break', else block is skipped
for num in range(5):
if num == 3:
print(f" Breaking loop at {num}")
break # This prevents the 'else' block from executing
print(f" Processing number {num}")
else:
print(" This line will NOT be printed because of 'break'.")
4.2. while Loop with else
# Example 1: Loop completes normally, else block executes
x = 0
while x < 3:
print(f" Current value of x: {x}")
x += 1
else:
print(" While loop finished because condition became false (x is no longer < 3).")
# Example 2: Loop with a 'break', else block is skipped
y = 0
while y < 5:
if y == 2:
print(f" Breaking loop at y = {y}")
break # This prevents the 'else' block from executing
print(f" Current value of y: {y}")
y += 1
else:
print(" This line will NOT be printed because of 'break'.")
This can be very powerful for scenarios where you need to confirm that a search was exhaustive, or that a process finished without interruption. It provides a clean, Pythonic way to handle post-loop logic based on how the loop exited.
5. Practical Application: File Iteration with for Loop
Reading data from files is a common task in software engineering, and Python makes it incredibly straightforward with for loops. When you open a file in Python (especially using the with statement, which ensures the file is properly closed even if errors occur), the file object itself becomes an iterable.
This means you can directly use a for loop to process each line in the file, one by one, without loading the entire file into memory, which is a significant advantage for large files. We can even combine this with enumerate() to get line numbers, and use the .strip() method to clean up any leading or trailing whitespace, including the newline character at the end of each line.
# Ensure you have a 'data' directory with 'numbers.txt' inside it
# data/numbers.txt content:
# 10
# 20
# 30
# 40
# 50
# Hello Python
# Looping is fun!
# End of file
try:
with open("data/numbers.txt", "r") as file:
for line_num, line in enumerate(file, 1): # Start enumeration from 1 for line numbers
print(f" Line {line_num}: {line.strip()}") # .strip() removes whitespace
except FileNotFoundError:
print(" Error: 'data/numbers.txt' not found. Please ensure the file exists in the 'data' directory.")
except Exception as e:
print(f" An error occurred: {e}")
This pattern is robust, efficient, and a cornerstone for any data processing or logging tasks.
How to Run the Code
All the code examples discussed in this blog post are available in our comprehensive GitHub repository. To run them yourself, follow these simple steps:
- Ensure you have Python installed (version 3.6 or higher recommended).
- Clone or download the
python_loop_basicsdirectory from our GitHub repository: https://github.com/aicoresynapseai/code/tree/main/python_loop_basics - Navigate to the
python_loop_basicsdirectory in your terminal or command prompt. - Run the main script:
python main.py
Feel free to experiment with the code, modify it, and see how different changes impact the output!
Leave a Reply