Chapter 5 of 12
Python loops are powerful, especially the for loop which iterates over any iterable โ lists, strings, dictionaries, ranges, files, and custom objects.
# Iterate over a list
courses = ["HTML", "CSS", "Python", "Django"]
for course in courses:
print(course)
# range() โ generate a sequence of numbers
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step of 2)
print(i)
# enumerate() โ get index AND value together
for i, course in enumerate(courses):
print(f"{i + 1}. {course}")
# Iterate over a string
for char in "Hello":
print(char) # H, e, l, l, o# while โ runs as long as condition is True
count = 0
while count < 5:
print(count)
count += 1
# break โ exit the loop immediately
for n in range(100):
if n == 5:
break
print(n)
# Prints: 0, 1, 2, 3, 4
# continue โ skip to the next iteration
for n in range(10):
if n % 2 == 0:
continue # skip even numbers
print(n)
# Prints: 1, 3, 5, 7, 9
# else clause on loops โ runs if loop completed without break
for course in courses:
if course == "Rust":
print("Found Rust!")
break
else:
print("Rust not in list") # runs if loop didn't break