Why does a `while` loop never stop after I change the wrong variable?
Quick answer
A while loop continues as long as its condition is true. If the condition checks count, changing a different variable such as step does not make the loop stop; count stays the same, so the test stays true. Update count inside the loop, or otherwise arrange for its condition to become false. [S1]
The question, the details, the next step.
A practical checklist
Copy the exact
whilecondition.Identify each variable or value used by that condition.
Find the statement that changes those values before the next test.
Check every path through the loop for a route that skips the update.
Trace sample values until the condition becomes false, or find where it stays true.
A few more useful answers
Does changing any variable inside the loop make it stop?
No. The change must affect the value or values used by the loop condition, so that the condition can become false.
What if the condition is still true after one update?
That can be normal: the loop checks again and continues while the condition is true. Trace later updates to see whether a value eventually makes the test false.
Can a loop stop if I never change the condition variable?
If the values used by the condition never change, the condition remains the same. Trace the actual condition and the paths through the loop to identify a change that can make it false.
Sources
References used for this guide.
- [S1] Python Language Reference: while statements docs.python.org · Checked
