Python has a few loop features that look unusual at first but make your code cleaner. Let's start with the else clause on loops.
The else clause
# Find a name in the list
names = ['Alice', 'Bob', 'Charlie']
for n in names:
if n == 'Bob':
print('Found Bob')
break
else:
# Runs ONLY if we did NOT hit break
print('No match found')
Classic search pattern
The else block runs when the loop finishes without hitting a break. If you do find something and call break, the else is skipped. This turns a common flag variable pattern into clean, readable code.
A while loop can have an else too, with the same rule: it runs when the condition becomes false, and is skipped when you leave with break.
The pass statement
# Python requires an indented block after a colon.
# If you have nothing to do there yet, use pass:
for n in [3, -1, 4]:
if n < 0:
pass # decide what to do with negatives later
else:
print(n)
A placeholder body
pass is a no-op. It satisfies Python's requirement for an indented block when you haven't written the real logic yet.
Nested loops
# A 2x3 grid
for row in range(2):
for col in range(3):
print(f'({row}, {col})')
# Output:
# (0, 0)
# (0, 1)
# (0, 2)
# (1, 0)
# (1, 1)
# (1, 2)
Rows and columns
Your turn
0 of 3 solved
Exercise 1
+30 XP
codes holds the codes that open the vault. Search it twice, each time with a for loop that has an else: first for first_try, then for second_try. The first loop prints f'{first_try} opens the vault' and breaks when it finds first_try; if it runs out of codes, its else prints f'{first_try} does not'. The second loop does the same with second_try. With the starter's values the output is 4417 opens the vault and then 5555 does not.
codes = [1234, 4417, 9001]
first_try = 4417
second_try = 5555
# Search codes for first_try: a for loop with break, and an else
# Then search codes for second_try the same way
Ctrl + Enter to run
Run your code to check it against the tests.
Exercise 2
+30 XP
Add up readings, leaving the negative ones out. Loop over the readings with an if for a negative reading with only pass inside, and an else that adds the reading to total. Print total after the loop.
readings = [4, -1, 7, -3, 2]
total = 0
# Loop over readings: pass for a negative reading, otherwise add it to total
Ctrl + Enter to run
Run your code to check it against the tests.
Exercise 3
+30 XP
shelves is a list of shelves, each a list of titles. Use a loop inside a loop to print every title as f'{shelf_number}: {title}', counting the shelves from 1, and add one to count for each title you print. A shelf is read only up to a title that is 'STOP': break out there without printing it. break only leaves the inner loop, so the next shelf is still read. The first line printed is 1: Dune.
shelves = [
['Dune', 'Emma', 'STOP', 'Ulysses'],
['Beloved', 'Hamlet'],
['STOP', 'Walden'],
['Persuasion'],
]
count = 0
shelf_number = 0
# For each shelf, add 1 to shelf_number, then print its titles up to 'STOP'