1

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?

shad0w_wa1k3r
  • 12,955
  • 8
  • 67
  • 90
Julliard
  • 523
  • 1
  • 6
  • 23
  • 1
    https://stackoverflow.com/a/20449433/4909087 – cs95 May 10 '18 at 09:42
  • @cᴏʟᴅsᴘᴇᴇᴅ: I don't think using `input` is the real problem in this question. In Python 2, `input` will return a number and the `getStatus` function should more or less work (it will either return `False` or `None`, which isn't a very good way to distinguish success from failure). Though `print` isn't a function in Python 2, so who knows what version is really being used. Anyway, I'm going to reopen. – Blckknght May 10 '18 at 10:11
  • @Blckknght On closer inspection... yes, I think it is a problem of `getStatus`' return value not being tested in the `while` loop. – cs95 May 10 '18 at 10:13

4 Answers4

4

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
Blckknght
  • 100,903
  • 11
  • 120
  • 169
1

you can add if statement before get_status() that will check if it's true and break and in the get_status function you will have to return true to break

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


while True:
  if getStatus():
     print('Ended')
     break
-1
def selectedCountry():
    while True:
        country = input("Enter country of which you want to check pictures HR, RS, RO:  ").upper()
        if country == str("HR") or country == str("RO") or country == str("RS"):
            break
        else:
            print("Please enter HR or RO or RS: " + "you wrote: " + country)

Why while True is working outside of a function and inside the same problem with asking again

Enter country of which you want to check pictures HR, RS, RO:  >? hr
Enter country of which you want to check pictures HR, RS, RO:  
JoeBlast
  • 1
  • 2
  • 1
    Hello @user2498462, to make your answer more understandable you should use the same code that was used in the question. – OuuGiii Apr 23 '20 at 08:14
  • Not only is this code quite problematic in terms of logic structure it is also very miss leading during the fact that its ignoring the main problem completly – Phillip Apr 23 '20 at 08:48
-2

You may change it to -

while True:
  if(getStatus()==False):
      print('Ended')
      break

By this you can use returned value to break out of infinite loop.

Rohan Rawat
  • 31
  • 1
  • 4
  • Welcome to Stack Overflow! You can format your code by indenting it by four extra spaces (in addition to whatever indentation you want it to have internally). An easy way to get that is by selecting it in the editor, and clicking the `{}` button. If you have multiple lines selected, it will indent them all for you. If you have a single line (or only part of one), it will use backticks \`\` instead (which are useful for putting code snippets like variable names in your text). – Blckknght May 10 '18 at 10:29
  • hi Rohan! may i know which part of my code do i change to yours? – Julliard May 10 '18 at 10:34
  • Sorry @Julliard, I missed the comments. Its too late but still I edited my answer. – Rohan Rawat Nov 01 '21 at 16:33