6 of 6
print()If you forget the print() after the inner loop, everything stays on one line:
# β Wrong β no newline for r in range(3): for c in range(4): print("*", end=" ") # Output: * * * * * * * * * * * * (all on one line!) # β Correct β add print() after inner loop for r in range(3): for c in range(4): print("*", end=" ") print() # β this moves to the next line
Using the same variable for both loops causes bugs:
# β Wrong β both loops use 'i' for i in range(3): for i in range(4): # This overwrites the outer 'i'! print(i, end=" ") print() # β Correct β use different names for i in range(3): for j in range(4): print(j, end=" ") print()
Remember: range(n) goes from 0 to n-1, and range(a, b) goes from a to b-1.
# Want to print 1 to 5? range(5) # gives 0, 1, 2, 3, 4 β starts at 0! range(1, 5) # gives 1, 2, 3, 4 β misses 5! range(1, 6) # gives 1, 2, 3, 4, 5 β correct!
break Only Breaks the Inner Loopfor i in range(5): for j in range(5): if j == 2: break # Only exits the inner loop! # Outer loop keeps going...
If you need to break both loops, use a flag:
done = False for i in range(5): for j in range(5): if some_condition: done = True break if done: break
When your nested loop isn't working, add prints to see what's happening:
for i in range(3): print(f"--- Outer loop: i = {i} ---") for j in range(3): print(f" Inner loop: j = {j}")
This shows you exactly how the loops are running.
| Pattern | Outer | Inner | Total |
|---|---|---|---|
| 3Γ4 grid | range(3) | range(4) | 12 runs |
| Triangle | range(1, n+1) | range(i) | varies |
| All pairs | range(len(list)) | range(i+1, len(list)) | nΓ(n-1)/2 |
| Times table | range(1, 13) | (just multiply) | 12 runs |
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit