Recall & Review
beginner
What does the
else block do in a for–else statement?The
else block runs only if the for loop completes all iterations without hitting a break statement.Click to reveal answer
beginner
When is the
else block skipped in a for–else loop?The
else block is skipped if the for loop is exited early using a break statement.Click to reveal answer
beginner
True or False: The
else block in a for–else loop runs after every iteration.False. The
else block runs only once after the loop finishes all iterations without a break.Click to reveal answer
beginner
What is a real-life analogy for a
for–else loop?Imagine checking every item in a box for a defect. If you find a defect, you stop (break). If you check all items and find none defective, you celebrate (else).
Click to reveal answer
beginner
Write a simple Python
for–else example that prints 'Found it!' if a number 5 is in a list, otherwise prints 'Not found!'.numbers = [1, 2, 3, 4, 6]
for num in numbers:
if num == 5:
print('Found it!')
break
else:
print('Not found!')
Click to reveal answer
When does the
else block run in a for–else loop?✗ Incorrect
The
else block runs only if the loop completes all iterations without encountering a break.What happens if a
break is executed inside a for loop with an else?✗ Incorrect
If
break is executed, the loop exits early and the else block does not run.Which of these is a correct use of
for–else?✗ Incorrect
for–else is useful to run code if the loop did not find what it was searching for.What will this code print?
for i in range(3):
if i == 1:
break
else:
print('Done')✗ Incorrect
The loop breaks when i == 1, so the else block does not run and nothing is printed.
Can
for–else be used without a break statement?✗ Incorrect
If no
break is used, the else block runs after the loop finishes.Explain how the
else block works in a for–else loop and when it runs.Think about what happens if the loop never breaks.
You got /3 concepts.
Describe a real-life situation where a
for–else loop would be useful.Imagine checking items one by one for a problem.
You got /3 concepts.