0

I am wondering why in python, when trying:

count = 0

while count < 3:
    for i in range(40):
        count += 1

does not actually check the while loop condition. Whereas in

count = 0

for i in range(40):
    while count < 3:
        count += 1

does. At first I assumed that maybe the while loop has to be ignored until the iterations are complete. But if I run 2 different for loops

count = 0

while count < 3:
    for i in range(40):
        count += 1

    for i in range(40):
        count += 1

The same things happens! count will become 80. I have been using while loops frequently and am surprised I have never encountered this. Does the while loop only get checked at the end of its contents?. If so, how could I write a variation of the first body of code

bsafaria
  • 17
  • 5
  • 1
    " If so, how could I write a variation of the first body of code" I assume you mean that you want to structure the code the same way, but leave the outer loop immediately any time the condition becomes satisfied. Is there a *specific problem you are trying to solve* by doing this? – Karl Knechtel Apr 20 '20 at 17:46
  • There is a problem that I was trying to do. But there is no necessary format that I am supposed to do it in. I just encountered this and got confused. – bsafaria Apr 20 '20 at 17:51

2 Answers2

3

A while loop's condition is checked before its body begins, and whenever its body finishes. If you put further loops into the body, they all have to finish before the while loop enters its next iteration.

If you want to explicitly terminate the loop before its body is finished, you will need to use break - but if you are inside a nested loop, then break will only terminate the innermost loop!

If for some reason you really need to end an outer loop from inside an inner loop, then the cleanest way would be to place the whole thing into a function and use return. See also: How to break out of multiple loops?

Christoph Burschka
  • 4,467
  • 3
  • 16
  • 31
2

The condition of the while loop is checked each time execution hits that line. I guess you want something like this:

count = 0

for i in range(40):
    if count < 3:
        count += 1
    else:
        break
Keri
  • 356
  • 1
  • 10