Understanding Python For Loops
A for loop in Python is a powerful tool used to iterate over a sequence, such as a list, tuple, dictionary, set, or even a string. Unlike the traditional for keyword found in other programming languages, Python’s for loop acts more like an iterator method in object-oriented programming languages.
Executing Statements for Each Item
The for loop allows you to execute a block of code once for each item in a sequence. For example, consider a list of books:
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for book in books:
print(book)
In this example, the loop iterates over each book in the list, printing the title of each one. Notably, the for loop in Python does not require an indexing variable to be set beforehand.
Iterating Over Strings
Strings in Python are also iterable, meaning you can loop through each character individually. Here’s an example:
for letter in "Library":
print(letter)
This loop will print each letter of the word “Library” on a new line.
The Break Statement
Using the break statement, you can exit a loop prematurely, even if there are remaining items to iterate over. Consider the following example:
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for book in books:
print(book)
if book == "1984":
break
Here, the loop stops as soon as it encounters “1984”. If you place the break statement before the print function, “1984” won’t be printed at all:
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for book in books:
if book == "1984":
break
print(book)
The Continue Statement
The continue statement allows you to skip the current iteration and proceed with the next one. For example, if you want to skip printing a specific book:
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for book in books:
if book == "1984":
continue
print(book)
In this case, “1984” is skipped, and only the other books are printed.
The range() Function
Python’s range() function is incredibly useful when you want to loop a specific number of times. It generates a sequence of numbers, starting from 0 by default, and increments by 1 until it reaches a specified number:
for x in range(6):
print(x)
This code will print numbers from 0 to 5. You can also customize the starting point:
for x in range(2, 6):
print(x)
Here, the loop prints numbers from 2 to 5. Additionally, you can specify the increment value by adding a third parameter:
for x in range(2, 30, 3):
print(x)
This example prints numbers from 2 to 29, incrementing by 3 each time.
Using Else with For Loops
The else keyword can be used in conjunction with a for loop to execute a block of code once the loop has finished iterating over the sequence:
for x in range(6):
print(x)
else:
print("Loop completed!")
It’s important to note that the else block won’t be executed if the loop is terminated early with a break statement:
for x in range(6):
if x == 3: break
print(x)
else:
print("Loop completed!")
Nested Loops
Python also supports nested loops, where you have a loop inside another loop. The inner loop will execute entirely for each iteration of the outer loop. For instance:
genres = ["Fantasy", "Dystopian", "Classic"]
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for genre in genres:
for book in books:
print(genre, book)
In this case, the loop will print every combination of genre and book title.
The Pass Statement
There may be situations where you want to write a for loop but leave it empty temporarily. Python doesn’t allow empty code blocks, so you can use the pass statement to avoid errors:
for x in [0, 1, 2]:
pass
This loop does nothing, but it is syntactically valid.
Test Your Knowledge with Exercises
Exercise: Try looping through the items in a book list:
books = ["The Hobbit", "1984", "To Kill a Mockingbird"]
for book in books:
print(book)