0
0
Pythonprogramming~20 mins

Nested while loops in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested while loops with counters
What is the output of this Python code using nested while loops?
Python
i = 1
result = []
while i <= 2:
    j = 1
    while j <= 3:
        result.append(f"{i}-{j}")
        j += 1
    i += 1
print(result)
A['1-1', '1-2', '1-3', '2-1', '2-2', '2-3']
B['1-1', '2-1', '3-1', '1-2', '2-2', '3-2']
C['1-1', '1-2', '2-1', '2-2', '3-1', '3-2']
D['1-1', '1-2', '1-3', '2-1', '3-2', '2-3']
Attempts:
2 left
💡 Hint
Think about how the inner loop runs completely for each iteration of the outer loop.
Predict Output
intermediate
1:30remaining
Counting iterations in nested while loops
What is the value of variable count after running this code?
Python
count = 0
x = 0
while x < 3:
    y = 0
    while y < 2:
        count += 1
        y += 1
    x += 1
print(count)
A2
B5
C3
D6
Attempts:
2 left
💡 Hint
Multiply the number of outer loop runs by inner loop runs.
Predict Output
advanced
2:00remaining
Output of nested while loops with break
What is the output of this code snippet?
Python
i = 1
result = []
while i <= 3:
    j = 1
    while j <= 3:
        if i == j:
            break
        result.append((i, j))
        j += 1
    i += 1
print(result)
A[(2, 1), (3, 1), (3, 2)]
B[(1, 1), (1, 2), (2, 1), (2, 2), (3, 1), (3, 2)]
C[(1, 1), (2, 1), (2, 2), (3, 1), (3, 2), (3, 3)]
D[(1, 2), (2, 1), (3, 1), (3, 2)]
Attempts:
2 left
💡 Hint
The inner loop breaks when i equals j, so some pairs are skipped.
Predict Output
advanced
2:00remaining
Final value of variable after nested while loops with continue
What is the final value of total after running this code?
Python
total = 0
x = 0
while x < 3:
    y = 0
    while y < 3:
        y += 1
        if y == 2:
            continue
        total += y
    x += 1
print(total)
A9
B15
C12
D18
Attempts:
2 left
💡 Hint
Remember that continue skips the rest of the current inner loop iteration.
🧠 Conceptual
expert
2:30remaining
Number of iterations in nested while loops with complex conditions
Consider this nested while loop code. How many times does the innermost statement count += 1 execute?
Python
count = 0
x = 1
while x < 5:
    y = x
    while y > 0:
        count += 1
        y -= 2
    x += 1
print(count)
A8
B6
C10
D9
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each x, then sum.