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.
The reason 7 test
s 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 test
s 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