Basic for loop
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Loop over strings
text = "Hello"
for char in text:
print(char)
# Output:
# H
# e
# l
# l
# o
Loop with range
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
for i in range(2, 5):
print(i)
# Output: 2, 3, 4
Loop over dictionaries
person = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
# Loop over keys:
for key in person:
print(key)
# Loop over values:
for value in person.values():
print(value)
# Loop over items:
for key, value in person.items():
print(f"{key}: {value}")
break and continue
# break — exit loop early:
for i in range(10):
if i == 5:
break
print(i) # Prints 0-4, then stops
# continue — skip to next iteration:
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints only odd numbers
else clause
else runs if loop completes without break:
for i in range(5):
if i == 10:
break
else:
print("Loop completed normally") # Runs because no break