简体   繁体   中英

I can't break this while loop

I have an assignment where I need to complete an action until the input is 'quit', 'Quit', 'q', or 'Q'. I've been trying this:

while variable != 'quit' or 'Quit' or 'q' or 'Q':
    # do stuff

however when any of those strings are inputted the while loop still executes. I've tried other ways like if statements but it just times out? How can I break the loop correctly?

The way to go is probably something like this:

while str(variable).upper() not in ['QUIT', 'Q']:

This way, you can list all the values which allow the user to quit in one place and the case (upper or lower) is ignored.

If I'm understanding this correctly, you have something like the following:

while variable != 'quit' or 'Quit' or 'q' or 'Q':
    # do stuff
    variable = input("")

(By the way - welcome to Stack Overflow; As another user has mentioned in a comment - please provide a code example. it will help potential answerers actually know what's going wrong and what you're trying to do.)

The reason why it never breaks is because what the Python interpreter actually sees is:

while (variable != 'quit') or ('Quit') or ('q') or ('Q'):
    # do stuff
    variable = input("")

In Python, non-empty strings will evaluate to true - if you try bool('q') in the Python interpreter, you will get True . This means that the interpreter is running:

while (variable != 'quit') or True or True or True:
    # do stuff
    variable = input("")

which obviously never breaks. What you need to do is check all options; Kind Stranger has one solution but more explicitly, you could try

while variable not in ('quit', 'Quit', 'q', 'Q'):

Try this:

 while (variable != "quit" and variable != "q"  and variable != "Q" and variable != "Quit"):

You cannot do variable.= "q" or "Q" etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM