2

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 5

2

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')
Sign up to request clarification or add additional context in comments.

Comments

2
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.

Comments

1

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.

Comments

0

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

1 Comment

Thank you this explanation was very clear and I can understand it a lot better now! really appreciate it :)
0

Try

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.