Python For Loops: A Comprehensive Guide
For loops are a fundamental control flow statement in Python, used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in that sequence. They are incredibly powerful for automating repetitive tasks.
1. Basic Syntax
The basic syntax of a for loop in Python is:
for item in sequence:
# Code to be executed for each item
# This block is indented
forkeyword: Starts the loop.item: A variable that takes on the value of each element in thesequenceduring each iteration of the loop. You can choose any valid variable name.inkeyword: Connects theitemvariable to thesequence.sequence: The iterable object (list, tuple, string, range, etc.) that you want to loop through.:(colon): Marks the end of theforstatement and the beginning of the loop's code block.- Indentation: Crucially important in Python! The code block that will be executed for each item must be indented (usually 4 spaces).
2. Looping Through Lists
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the fruit variable takes on the value "apple" in the first iteration, "banana" in the second, and "cherry" in the third. The print(fruit) statement is executed for each of these values.
3. Looping Through Strings
Strings are also iterable, meaning you can loop through their characters:
message = "Hello"
for char in message:
print(char)
Output:
H
e
l
l
o
4. Looping Through Tuples
Tuples work similarly to lists:
coordinates = (10, 20, 30)
for coord in coordinates:
print(coord)
Output:
10
20
30
5. The range() Function
The range() function is often used with for loops to generate a sequence of numbers.
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 (but not including)stop, incrementing bystep.
# Print numbers from 0 to 4
for i in range(5):
print(i)
# Print numbers from 2 to 7
for i in range(2, 8):
print(i)
# Print even numbers from 0 to 10
for i in range(0, 11, 2):
print(i)
Output (first loop):
0
1
2
3
4
Output (second loop):
2
3
4
5
6
7
Output (third loop):
0
2
4
6
8
10
6. break and continue Statements
break: Immediately terminates the loop and transfers control to the statement following the loop.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
break # Exit the loop when num is 3
print(num)
Output:
1
2
continue: Skips the rest of the current iteration and proceeds to the next iteration of the loop.
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 3:
continue # Skip printing 3
print(num)
Output:
1
2
4
5
7. The else Clause with for Loops
A for loop can have an optional else clause. The else block is executed only if the loop completes normally (i.e., it doesn't encounter a break statement).
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 6:
print("Found 6!")
break
else:
print("6 not found in the list.")
Output:
6 not found in the list.
If the list contained a 6, the break statement would have been executed, and the else block would not have been executed.
8. Nested For Loops
You can nest for loops inside each other to iterate over multiple sequences.
colors = ["red", "green", "blue"]
sizes = ["small", "medium", "large"]
for color in colors:
for size in sizes:
print(f"Color: {color}, Size: {size}")
Output:
Color: red, Size: small
Color: red, Size: medium
Color: red, Size: large
Color: green, Size: small
Color: green, Size: medium
Color: green, Size: large
Color: blue, Size: small
Color: blue, Size: medium
Color: blue, Size: large
9. Looping Through Dictionaries
You can loop through dictionaries in several ways:
- Looping through keys:
my_dict = {"name": "Alice", "age": 30, "city": "New York"}
for key in my_dict:
print(key)
- Looping through values:
for value in my_dict.values():
print(value)
- Looping through key-value pairs:
for key, value in my_dict.items():
print(f"Key: {key}, Value: {value}")
Key Takeaways:
- For loops are essential for iterating over sequences.
- Indentation is crucial for defining the loop's code block.
range()is a powerful function for generating sequences of numbers.breakandcontinueprovide control over loop execution.- The
elseclause can be used to execute code after a loop completes normally. - Nested loops allow you to iterate over multiple sequences.
- Dictionaries can be looped through using keys, values, or key-value pairs.