For loops are used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code multiple times, once for each item in the sequence. Here's how they work:
Basic Structure
In Python, a for loop has the following structure:
for variable in sequence:
# code to execute for each item
How It Works
- Initialization: The loop starts by taking the first item from the sequence and assigning it to the variable.
- Execution: The code block inside the loop is executed using the current value of the variable.
- Iteration: The loop then moves to the next item in the sequence and repeats steps 2 and 3 until all items have been processed.
Example
Here's a simple example that prints each number in a list:
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Output:
1
2
3
4
5
Using range()
You can also use for loops with the range() function to iterate over a sequence of numbers:
for i in range(5): # Iterates from 0 to 4
print(i)
Output:
0
1
2
3
4
Summary
For loops are powerful for automating repetitive tasks and processing items in a collection. If you have more questions or need further examples, feel free to ask!
