Ad

Break Out Of While True Loop With Function

- 1 answer

So I have a while true loop -

while True:
  getStatus()
  print('Ended')

I hope to be able to break out of it if answer is 999. this is what I tried:

def getStatus():
  answer = input('What is the box ID? ')
  if answer == 999:
    return False 
  elif type(answer) == int:
    boxId = answer + 1
    print(boxId)

However even when the input is '999' it loops back and asks 'What is the box ID? ' again.

How do I get out of the while true loop?

Ad

Answer

Your while loop keeps looping because that's exactly what you've told it to do. After the function you call from its body returns, you ignore the return value, unconditionally print "Ended" and then do it all again, since the condition on the loop is obviously still truthy.

If you want the function to control if the loop keeps going, you should use its return value as the condition in the loop, with something like this:

running = True
while running:
    running = getStatus()
print("Ended") # move this outside the loop!

This requires that getStatus returns a truthy value when you want to keep looping and a falsey value when you want to stop. Your current implementation of that function doesn't do that. It returns False when 999 is entered, but doesn't explicitly return anything if you give other input (which in Python is equivalent to returning None). Since both False and None are falsey, the code above won't actually work (you could patch it with something like running = getStatus() is None, but that would be horrible). You should change the function to have an explicit return statement in all of its branches (including the case for non-integer inputs, where it doesn't go into either your if or elif blocks).

If the loop and the function's logic are tightly intertwined, it might make sense to move the loop into the function itself, rather than having it be separate and needing to use a return value to signal when to stop. In a single function, you can use break to exit a loop directly:

def getStatus():
    while True:
        answer = input('What is the box ID? ')
        if answer == 999:
            break
        elif isinstance(answer, int): # isinsance() is better than type(...) == ...
            boxId = answer + 1
            print(boxId)
        else:
            print("I'm sorry, I didn't understand that.") # still good to handle this case
Ad
source: stackoverflow.com
Ad