Challenge - 5 Problems
For–else Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this for–else code?
Consider the following Python code snippet. What will it print when executed?
Python
for i in range(3): print(i) else: print('Done')
Attempts:
2 left
💡 Hint
The else block runs after the for loop completes normally without break.
✗ Incorrect
The else block after a for loop runs only if the loop finishes all iterations without a break.
Here, the loop prints 0, 1, 2 and then the else prints 'Done'.
❓ Predict Output
intermediate2:00remaining
What is the output when break is used inside for loop with else?
What will this code print when run?
Python
for i in range(5): if i == 2: break print(i) else: print('Finished')
Attempts:
2 left
💡 Hint
The else block does not run if the loop is exited by break.
✗ Incorrect
The loop breaks when i == 2, so it prints 0 and 1 only.
The else block is skipped because of the break.
🧠 Conceptual
advanced2:00remaining
When does the else block run in a for–else structure?
Choose the correct statement about the execution of the else block in a for–else loop.
Attempts:
2 left
💡 Hint
Think about what happens when break is used inside the loop.
✗ Incorrect
The else block runs only if the loop finishes normally without encountering a break.
If break is used, else is skipped.
❓ Predict Output
advanced2:00remaining
What is the output of this nested for–else code?
Analyze the code below and select the output it produces.
Python
for x in range(2): for y in range(3): if y == 1: break print(f'{x},{y}') else: print('Inner else') else: print('Outer else')
Attempts:
2 left
💡 Hint
Remember the else after inner loop runs only if inner loop completes without break.
✗ Incorrect
The inner loop breaks when y == 1, so inner else is skipped both times.
The outer loop completes normally, so outer else runs.
❓ Predict Output
expert2:00remaining
How many items are in the dictionary after this for–else code runs?
What is the number of items in the dictionary
d after executing this code?Python
d = {}
for i in range(5):
if i == 3:
break
d[i] = i * 2
else:
d['done'] = True
print(len(d))Attempts:
2 left
💡 Hint
Check if the else block runs when break is used.
✗ Incorrect
The loop breaks when i == 3, so only keys 0,1,2 are added.
The else block is skipped, so 'done' key is not added.
Length is 3.