3

I have a very simple problem: I have made a while loop, and in the middle of it, set the initial condition to false. This, however, does not stop the loop and runs entirely through, (somewhat obviously,) until it attempts to unsuccessfully go through again. Here is a simplified construction of what I have.

while(a):
    print("hi")
    a = False
    print("bye")

This returns:

hi
bye

Again I would like to only return hi; I want the loop to continually check if its satisfied.

Any help greatly appreciated.

2
  • Why don't you use break? Commented Oct 23, 2013 at 2:37
  • If you want a checked in more places, you're going to have to insert code to explicitly check it in those places. Commented Oct 23, 2013 at 2:39

3 Answers 3

2

Use:

return, or break

while a:
    print('hi')

    a = False
    if not a:
        break

    print('bye')

In a function or loop, when something is returned, the function or loop terminates. You could also return True, or break which is a specific way to 'break' out of a loop.

Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps I should have been more clear. Rather than fill this page with a huge amount of code, I simplified, but, evidently, excessively so. Anyway, I have a function, within the while loop, and that is where the initial condition is changed. So its similar to the original with the only caveat that everything after the while(a), is inside a function, so a break isn't an option, and I need both the function and the original loop to stop.
if i understand correctly then, use return inside your function. Whenever you return inside a function, the function is terminated, then, directly outside of your function, break out of the while loop, or return something from the while loop
1

Since the condition is true to start with (by design), the body of the loop will execute at least once. The fact you do something in the body of the loop to make the loop condition false doesn't stop the current iteration. It just means there won't be a next iteration after this one is done.

So if you want to get out in the middle of the current iteration, then you need to use break, return, or something more sophisticated like @inspectorG4dget's suggestion.

Comments

0
while(a):
    print("hi")
    a = False
    if a:
        print("bye")

OR

while(a):
    for s in ["hi", "bye"]:
    if a:
        print(s)
    if someCondition:
        a = False

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.