For Loops
The for loop is the most common loop in Python. It iterates over a sequence — like a list, string, or range of numbers — executing code once for each item. Think of it as saying: "For each item in this collection, do something."
Looping Over a List
The basic syntax is straightforward:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello,", name)
Output:
Hello, Alice
Hello, Bob
Hello, Charlie
The variable name takes on each value in the list, one at a time. First it's "Alice", then "Bob", then "Charlie". The indented code runs once for each value.
Counting with Range
Often you need to repeat something a specific number of times. The range() function generates a sequence of numbers:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Notice that range(5) produces 0 through 4 — five numbers total, but starting from 0. This zero-based counting is standard in programming.
Customizing Range
You can control where the range starts and stops:
# Count 1 to 5
for i in range(1, 6):
print(i)
# Count by twos
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
The pattern is range(start, stop, step). The stop value is exclusive — range(1, 6) includes 1, 2, 3, 4, 5 but not 6.
Practical Examples
For loops shine when processing collections:
# Calculate total price
prices = [10.99, 24.50, 8.75]
total = 0
for price in prices:
total = total + price
print("Total:", total)
# Find the longest word
words = ["apple", "banana", "cherry"]
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
print("Longest:", longest)
The Loop Variable
The variable you create (name, i, price, word) exists only within the loop's scope. Choose descriptive names — for item in items is clearer than for x in items.