Break Out Of While True Loop With Function
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?
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
999 is entered, but doesn't explicitly return anything if you give other input (which in Python is equivalent to returning
None). Since both
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 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
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module