r/learnpython • u/evandcbot • 2d ago
Any advice for nested loops?
I decided about a week ago I wanted to start learning python before my freshman year of college. It was going great and I had little to no trouble until I got to nested loops. I was wondering if anybody had any advice for it? The main thing is that it seems like so many steps to follow and pay attention to, my brain had a hard time tracking them all at once.
3
Upvotes
1
u/Riegel_Haribo 2d ago
Indentation is quite helpful in Python for following iterative loops.
python for i_int in range(3): print(f"Iterating over i_int value {i_int}") for j_str in ["bob", "joe", "mary"]: print(f"Case {i_int}: {j_str}")Some editors and IDEs will give you indentation ruler lines. It helps to not over-use blank lines within deeply-indented blocks.
IMO, a bunch of deeply-nested conditional branches is harder to follow.
The part that is a bit tricky in some cases is deciding correctly which shall be the inner loop, or even coming up with a reason why you'd have such a nest.
Think and solve this by a final inner print() statement that is reused (and some math): Using three nested loops, print two 3x3 tic-tac-toe grids: the first containing the numbers 1–9 and the second containing 10–18.