Python For Loops & Range
In Python, a for loop is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). Unlike traditional for loops in languages like C or Java, Python’s for loop acts more like an iterator traversal, working through each element in a collection directly.
1. Iterating Over Sequences
The most common use of a for loop is to visit every item in a collection.
# Iterating through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating through the characters of a string
for char in "Python":
print(char)
Advertisement
2. The range() Function
When you want to repeat a block of code a specific number of times, you use the built-in range() function. It generates a sequence of numbers.
Syntax: range(start, stop, step)
start(optional): The starting number (inclusive, default is0).stop(required): The ending number (exclusive—the loop stops before reaching this number).step(optional): The difference between each number (default is1).
Examples of range()
# 1. range(stop) - counts from 0 up to 4
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
# 2. range(start, stop) - counts from 2 up to 5
for i in range(2, 6):
print(i) # Output: 2, 3, 4, 5
# 3. range(start, stop, step) - counts from 1 to 10 with a step of 2
for i in range(1, 10, 2):
print(i) # Output: 1, 3, 5, 7, 9
# 4. Counting backwards using a negative step
for i in range(5, 0, -1):
print(i) # Output: 5, 4, 3, 2, 1
Advertisement
3. Loop Control Statements
You can alter the flow of your for loops using control keywords:
break: Exits the loop entirely.continue: Skips the current iteration and moves to the next one.else: Executes a block of code only if the loop finishes normally (i.e., without hitting abreak).
# Using break and continue
for num in range(1, 6):
if num == 3:
continue # Skips printing 3
if num == 5:
break # Stops the loop entirely when reaching 5
print(num) # Output: 1, 2, 4