Challenge - 5 Problems
Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Think about how the inner loop runs completely for each iteration of the outer loop.
✗ Incorrect
The outer loop runs for i=1 and i=2. For each i, the inner loop runs j=1 to 3, appending strings like 'i-j'. So the list has 6 elements in order.
❓ Predict Output
intermediate1: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)
Attempts:
2 left
💡 Hint
Multiply the number of outer loop runs by inner loop runs.
✗ Incorrect
The outer loop runs 3 times (x=0,1,2). The inner loop runs 2 times each outer iteration. So total count increments: 3*2=6.
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
The inner loop breaks when i equals j, so some pairs are skipped.
✗ Incorrect
For i=1, j=1 triggers break immediately, so no pairs added. For i=2, j=1 added, j=2 breaks. For i=3, j=1 and j=2 added, j=3 breaks. So result is [(2,1),(3,1),(3,2)].
❓ Predict Output
advanced2: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)
Attempts:
2 left
💡 Hint
Remember that continue skips the rest of the current inner loop iteration.
✗ Incorrect
The outer loop runs 3 times (x=0,1,2). For each, inner loop:
- y=0<3: y=1, !=2, total+=1
- y=1<3: y=2, ==2 continue (skip +=2)
- y=2<3: y=3, !=2, total+=3
Per outer: +4. Total: 12.
🧠 Conceptual
expert2: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)
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each x, then sum.
✗ Incorrect
x=1: y=1>0 count+=1 y=-1 stop (+1)
x=2: y=2>0 count+=1 y=0 stop (+1)
x=3: y=3>0 count+=1 y=1>0 count+=1 y=-1 (+2)
x=4: y=4>0 count+=1 y=2>0 count+=1 y=0 (+2)
Total: 6.