← Back to Nested Loops

Coordinate Pairs

4 of 6

Exercise 3: Coordinate Pairs

Print all coordinate pairs for a 3×3 grid:

(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

Starter Code

# Print all (row, col) pairs for a 3x3 grid for row in range(___): for col in range(___): print(f"(___,___)", end=" ") print()

Hints

Hint 1 — What ranges?

Both the outer and inner loops should go from 0 to 2: range(3)

Hint 2 — How to format?

Use an f-string: f"({row},{col})" and print with end=" " to stay on the same line.


Bonus Challenge

Make it work for any size grid! Ask the user for the size:

size = int(input("Grid size: ")) # Print all coordinate pairs for that size

Solution

Show Solution
for row in range(3): for col in range(3): print(f"({row},{col})", end=" ") print()
Show Bonus Solution
size = int(input("Grid size: ")) for row in range(size): for col in range(size): print(f"({row},{col})", end=" ") print()

Try it yourself

Code: Coordinate Pairs

Loading Python runtime…
Python
Loading...
bash
$ Click "Run" to execute your code...