0
0
Pythonprogramming~20 mins

For–else execution behavior in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
For–else Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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')
A
0
1
2
Done
B
0
1
2
CDone
D
0
1
Done
Attempts:
2 left
💡 Hint
The else block runs after the for loop completes normally without break.
Predict Output
intermediate
2: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')
A
0
1
Finished
B
0
1
2
Finished
C
0
1
D
0
1
2
Attempts:
2 left
💡 Hint
The else block does not run if the loop is exited by break.
🧠 Conceptual
advanced
2: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.
AThe else block runs only if the for loop has zero iterations.
BThe else block runs only if the for loop contains a break statement.
CThe else block runs after every iteration of the for loop.
DThe else block runs only if the for loop completes all iterations without a break.
Attempts:
2 left
💡 Hint
Think about what happens when break is used inside the loop.
Predict Output
advanced
2: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')
A
0,0
Inner else
1,0
Inner else
Outer else
B
0,0
1,0
Outer else
C
0,0
1,0
Inner else
Outer else
D
0,0
1,0
Attempts:
2 left
💡 Hint
Remember the else after inner loop runs only if inner loop completes without break.
Predict Output
expert
2: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))
A3
B4
C5
D1
Attempts:
2 left
💡 Hint
Check if the else block runs when break is used.