Back to community
Computer ScienceClass 11 (CBSE) Resolved

Why does my Python while loop run forever and never stop?

I wrote a while loop to print numbers but it just keeps printing and my screen freezes. I have to force-close the program. What am I doing wrong?

TuitionsInIndia Study Desk 50 90d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

1 answer

Accepted answer
8

An infinite loop almost always means the loop condition never becomes False because you forgot to update the variable inside the loop. For example, 'i = 1; while i <= 5: print(i)' runs forever because i stays 1. You must change the control variable each iteration: add 'i = i + 1' (or 'i += 1') as the last line inside the loop. Now i grows to 6, the condition i <= 5 becomes False, and the loop stops. Always check three things: the variable is initialised before the loop, the condition will eventually be False, and the variable is updated inside the loop. If any one is missing, the loop runs forever.

TuitionsInIndia Study DeskEditorial
Reviewed answer · 90d ago

Sign in as a tutor to answer this doubt.