Python for loop
For Loops in Python
In Python, for loops are fundamental constructs used for iterating over sequences, including lists, tuples, dictionaries, sets, and strings. They enable you to execute a block of code multiple times, making them essential for data manipulation and automation tasks. This lesson will delve into how for loops work in Python, including key features, examples, and common use cases.
1. Basics of For Loops
A for loop allows you to traverse through a collection of items, executing the same operation for each item. This feature makes for loops powerful tools for working with data structures.
Example: Loop Through a List
python
1# Define a list of vegetables
2vegetables = ["carrot", "potato", "tomato"]
3
4# Iterate through the list and print each vegetable
5for vegetable in vegetables:
6 print(vegetable)
In this example, the loop goes through each vegetable in the list and prints its name.
2. Iterating Through Strings
Strings in Python are also iterable, which means you can use a for loop to traverse through each character.
Example: Loop Through Characters in a String
python
1# Define a string
2word = "hello"
3
4# Iterate through each character in the string
5for letter in word:
6 print(letter)
This example prints each character of the string "hello" one by one.
3. Using Break to Exit a Loop Early
You can use the break
statement within a for loop to terminate the loop prematurely when a certain condition is met.
Example: Exit the Loop Based on a Condition
python
1# Define a list of fruits
2fruits = ["apple", "banana", "cherry"]
3
4# Iterate through the list and exit when encountering "banana"
5for fruit in fruits:
6 if fruit == "banana":
7 break
8 print(fruit)
In this scenario, the loop stops when it reaches "banana," so only "apple" is printed.
4. Skipping Items with Continue
The continue
statement allows you to skip the current iteration and move to the next one in the loop.
Example: Skip an Item
python
1# Define a list of numbers
2numbers = [1, 2, 3, 4, 5]
3
4# Print only the even numbers
5for number in numbers:
6 if number % 2 != 0:
7 continue
8 print(number)
In this example, the loop skips odd numbers and only prints even ones.
5. Utilizing the range() Function
The range()
function is commonly used with for loops to iterate over a sequence of numbers. It generates a series of integers based on specified parameters.
Example: Use range() in a For Loop
python
1# Iterate from 0 to 4
2for i in range(5):
3 print(i)
This example prints the numbers 0 through 4. You can also customize the starting point, end point, and step size.
Example: Customizing the Range
python
1# Iterate from 2 to 10, stepping by 2
2for i in range(2, 11, 2):
3 print(i)
Here, the loop prints every second number between 2 and 10.
6. Else Clause with For Loops
Python allows the use of an else
clause with for loops, which executes a block of code after the loop finishes iterating. This block will not run if the loop is terminated with a break
statement.
Example: Using Else with a For Loop
python
1# Iterate through a range
2for i in range(3):
3 print(i)
4else:
5 print("Loop completed successfully.")
In this example, "Loop completed successfully." is printed after the loop ends.
7. Nested For Loops
You can place a for loop inside another for loop, known as a nested for loop. This is useful for working with multi-dimensional data structures.
Example: Nested Loop
python
1# Define a list of colors and shapes
2colors = ["red", "blue", "green"]
3shapes = ["circle", "square"]
4
5# Print every combination of colors and shapes
6for color in colors:
7 for shape in shapes:
8 print(f"{color} {shape}")
This example generates combinations of colors and shapes.
8. The pass Statement
In Python, if you need a for loop that doesn’t perform any operation, you can use the pass
statement. This is often used as a placeholder.
Example: Using Pass in a For Loop
python
1# Define a list
2numbers = [1, 2, 3]
3
4# Placeholder for future implementation
5for number in numbers:
6 pass
7
The loop does nothing here but remains syntactically correct.