0
0
Pythonprogramming~5 mins

While–else behavior in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the else block do in a while–else statement?
The else block runs only if the while loop finishes normally without encountering a break statement.
Click to reveal answer
beginner
When is the else block skipped in a while–else loop?
The else block is skipped if the while loop exits early due to a break statement.
Click to reveal answer
beginner
Consider this code:<br>
i = 0
while i < 3:
    print(i)
    i += 1
else:
    print('Done')
<br>What will be printed?
The output will be:<br>0<br>1<br>2<br>Done<br>The else runs because the loop finished normally.
Click to reveal answer
beginner
What happens if a break is used inside a while loop with an else?
If break runs, the loop stops immediately and the else block does not run.
Click to reveal answer
intermediate
Why might you use a while–else instead of just a while loop?
You use while–else to run special code only if the loop did not stop early, like confirming a search found nothing.
Click to reveal answer
What triggers the else block in a while–else loop?
AThe loop contains a break
BThe loop runs at least once
CThe loop finishes without a break
DThe loop condition is false initially
If a while loop never runs because the condition is false at start, does the else block run?
AYes, because the loop did not break
BNo, never
CYes, always
DOnly if there is a break
What happens if a break is inside the while loop?
AThe <code>else</code> block runs after break
BThe <code>else</code> block is skipped
CThe loop restarts
DThe program crashes
Which of these is a good use of while–else?
ATo run code only if the loop breaks
BTo run code before the loop starts
CTo run code inside the loop
DTo run code after a loop that found no matching item
What will this code print?<br>
i = 0
while i < 5:
    if i == 3:
        break
    print(i)
    i += 1
else:
    print('Finished')
A0 1 2
B0 1 2 Finished
CFinished
D0 1 2 3 4 Finished
Explain how the else block works with a while loop in Python.
Think about when the loop ends normally versus early.
You got /3 concepts.
    Describe a real-life example where a while–else loop would be helpful.
    Imagine looking for your keys and what you do if you find or don't find them.
    You got /3 concepts.