4. Looping over dictionaries
person = {"Name": "Alice", "Age": "13", "City": "New York"}
#Keys only (default)
for key in person:
print(key)
#Keys explicitly
for key in person.keys():
print(key)
#Values
for value in person.values():
print(value)
#Key + Value (most useful)
for key, value in person.items():
print(key, "->", value)
5. Looping over multiple sequences -> 'zip()'
names = ["Alice", "Bob", "Charlie"]
ages =[13, 30, 35]
for name, age in zip(names, ages):
print (f"{name} is {age} years old")
6. Nested 'for' loops
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Useful for matrices, combinations, paterns, ect.
7.'break', 'continue', and 'else'
#break -> exit the loop immediately
for i in range(10):
if i ==5:
break
print(i)
#continue -> skip the rest of the current interation
for i in range(10):
if i % 2 == 0:
continue
print(i) #only odd numbers
#else clause -> runs only if the loop finished normally (no break)
for i in range(5):
print(i)
else:
print("Loop finished successfully")
8. Practical examples
Sum of numbers:
total = 0
for num in [3, 7, 2, 9]:
total += num
print(total)
Finding something:
numbers = [4, 8, 15, 16, 23, 42]
found = False
for num in numbers:
if num == 23:
found = True
break
if found:
print("Found 23")
Building a new list:
squares = [ ]
for x in range(1, 6):
squares.append(x ** 2)
print(squares)
9. List/Dict Comprehensions
Instead of a normal for loop + append, you can write:
squares = [x ** 2 for x in range(1, 6)]
even = [x for x in range(10) if x % 2 == 0]
person_upper = {k: v.upper() for k, v in person.items() if isinstance(v, str)}
These are usually faster and more readable for simple transformations.