0
0
Pythonprogramming~5 mins

For–else execution behavior in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AOnly if the loop contains a break
BAfter every iteration of the loop
CAfter the loop finishes all iterations without a break
DBefore the loop starts
What happens if a break is executed inside a for loop with an else?
AAn error occurs
BThe <code>else</code> block is skipped
CThe loop restarts
DThe <code>else</code> block runs immediately
Which of these is a correct use of for–else?
ARunning code after every loop iteration
BSkipping loop iterations
CReplacing <code>if</code> statements
DSearching for an item and doing something if not found
What will this code print?
for i in range(3):
    if i == 1:
        break
else:
    print('Done')
ANothing
BDone
C0 1 2
DError
Can for–else be used without a break statement?
AYes, but else always runs then
BNo, break is required
CYes, else never runs
DNo, syntax error
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.