0
0
Pythonprogramming~20 mins

Nested for loop execution in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Nested Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of nested loops with range
What is the output of this Python code?
Python
result = []
for i in range(2):
    for j in range(3):
        result.append((i, j))
print(result)
A[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
B[(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]
C[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
D[(0, 0), (1, 1), (2, 2), (3, 3)]
Attempts:
2 left
💡 Hint
Think about how the inner loop runs completely for each step of the outer loop.
Predict Output
intermediate
2:00remaining
Sum of products in nested loops
What is the value of variable total after running this code?
Python
total = 0
for x in range(1, 4):
    for y in range(1, 3):
        total += x * y
print(total)
A18
B20
C24
D12
Attempts:
2 left
💡 Hint
Calculate the sum of x*y for x=1 to 3 and y=1 to 2.
🔧 Debug
advanced
2:00remaining
Identify the error in nested loops
What error does this code raise when run?
Python
for i in range(3):
    for j in range(2):
        print(i, j)
ASyntaxError
BTypeError
CIndentationError
DNo error, prints pairs
Attempts:
2 left
💡 Hint
Check the syntax of the for loops carefully.
Predict Output
advanced
2:00remaining
Output of nested loops with break
What is the output of this code?
Python
result = []
for a in range(3):
    for b in range(3):
        if b == 1:
            break
        result.append((a, b))
print(result)
A[(0, 0), (1, 0), (1, 1), (2, 0), (2, 1)]
B[(0, 0), (1, 0), (2, 0)]
C[(0, 0), (0, 1), (1, 0), (2, 0)]
D[(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)]
Attempts:
2 left
💡 Hint
The break stops the inner loop when b equals 1.
🧠 Conceptual
expert
2:00remaining
Number of iterations in nested loops
How many times will the innermost statement print(i, j, k) execute in this code?
Python
for i in range(2):
    for j in range(3):
        for k in range(4):
            print(i, j, k)
A6
B9
C12
D24
Attempts:
2 left
💡 Hint
Multiply the lengths of all ranges to find total iterations.