5813
5813

Reputation: 1093

Python: While Loop Check Throughout Loop if True

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.

Upvotes: 3

Views: 10627

Answers (3)

Vidya
Vidya

Reputation: 30310

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.

Upvotes: 1

samrap
samrap

Reputation: 5673

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.

Upvotes: 2

inspectorG4dget
inspectorG4dget

Reputation: 113955

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

Upvotes: 0

Related Questions