18
That one afternoon I finally understood loops after 3 failed tutorials
I spent all Tuesday trying to wrap my head around for loops in Python and kept getting infinite loops that crashed my browser. Then a guy on Discord told me to print the loop variable each iteration, and it suddenly clicked why my code was stuck. Has anyone else had a weird simple trick that made a hard concept just fall into place?
3 comments
Log in to join the discussion
Log In3 Comments
aaronsullivan1mo ago
I had a similar moment with while loops in JavaScript back in 2022. I kept getting infinite loops because I forgot to increment my counter variable inside the loop body. A coworker told me to put a console.log right before the closing brace and watch what the counter was doing each pass through. That one line showed me I was updating the wrong variable entirely, and it fixed the problem in about thirty seconds. Sometimes the simplest debug step is just watching the numbers change in real time.
5
wendy8201mo ago
Printing the loop variable is genius, that totally would have saved me hours.
3
shane_park921mo ago
The loop variable trick is decent for sure but it has a flaw. If your code has nested loops, printing the wrong variable will give you garbage data that looks right but isn't. I wasted two days on a sorting algorithm because I was printing i instead of j in a double loop. Double check which loop you're actually debugging before you start.
3