While Loop Counter Confusion

Viewed 482

I'm working with while loops and I'm just a bit confused on how to break out of it in the way that I want. So I've nested a for loop within a while loop:

x = True
y = 0
while x:
  if y >= 5:
    x = False
    print('break')
  else:
      for x in range(7):
        y += 1 
        print('test')

The output that I'm looking for is 5 tests printed out and one break. However, every time I run the program it prints out 7 tests before it goes to the break. I'm not exactly sure, but I think I'm just confused about something within while loops! If someone could explain this to me please let me know :) I have found ways around this, but I'd like to get an understanding of why it doesn't work.

5 Answers

This is because it's performing the entire for loop within the while loop therefore y will become 7 before it checks again. Removing the for loop will resolve this.

x = True
y = 0
while x:
  if y >= 5:
    x = False
    print('break')
  else:
    y += 1 
    print('test')
y = 0
while y < 5:
  print("test")
  y += 1
print("break")

Would work.

There is no point in having another variable like "x" for the while loop when it allows for you to set the condition directly.

Because inner loop will complete before the next iteration of the outer loop. I.e. once the inner loop starts it does all 7 iterations before starting the next iteration of the while loop.

You can do this by just using one loop. Print out “test” increase counter and put in an if condition to break when counter is 5.

Try

i = 0
while True:
    if i == 5:
        break
    print('test')
    i = i + 1

The reason 7 tests print rather than 5 is that your entire for loop is executed before you go back to the beginning of your while statement. I think your understanding is that, after one iteration of a for loop, you go back to the beginning of the while loop, but this is incorrect: your for loop is executed completely before going back to the beginning of the while loop.

After you step into the for loop, you increment y 7 times and print test 7 times. y is now >= 5, and you go back into your if statement. The if statement turns x false, thereby "turning off" the while loop, and a break statement is printed. If you just want to print out 5 tests and one break, it would be much easier to simplify your code as such:

y = 0
while True:
    if y < 5:
        print('test')
        y += 1
    else:
        print('break')
        break
Related