My while loop runs once and exits even though the condition is still true Help
I am walking through a list of numbers and stopping when I hit a negative one. The loop body definitely runs, I can see the print, but it exits after the first pass. The loop is while i < len(values): and inside I check the value, print it, and return if it is negative. It is all inside a function. I have checked the indentation about eight times.
@goroutine_gil · 4mo ago · 3 replies
Paste the real code if you can, but from that description your
returnis almost certainly at the wrong indent level, so it runs on every pass rather than only when the value is negative. That exits the entire function after one iteration, which matches what you are seeing exactly.Two other things while you are in there. Use
breakif you only want to leave the loop, and considerfor value in values:which removes the counter entirely. The fact that you are not stuck in an infinite loop means youri += 1is fine.Reply
Report
@goroutine_gil · 4mo ago
Nobody sees their own indentation. It is the most common thing in this room by a distance.
Reply
Report
@airgap_amir · 4mo ago
It was the return. Lined up with the print, not inside the if. Eight readings and I did not see it.
Reply
Report