简体   繁体   中英

Python while loop not working as expected

When I type "no" into the input I expected it to add 1 to "x", therefore ending the loop, but what happens is that it ignores it and does not add 1 x. Here is the code.

x = 1
password = ""

while x == 1:        
    # imagine there is some code here which works

    ans1 = input("\n\nTest a new password? ")
    ans1 = ans1.upper()

    print(ans1)

    if ans1 == ("Y" or "YES"):
        x = x
    elif ans1 == ("N" or "NO"):
        x = x + 10

    print(x)

It's the bottom if/elif statement that is not working. It should continue to ask for input again until the user says NO but this isn't working.

You should use or that way.

if ans1 == ("Y" or "YES"):

Can be replaced with:

if ans1 == "Y" or ans1 == "YES": 

Or:

if ans1 in ("Y", "YES"): 

The bug comes from the definition of the or operator. When you do "Y" or "YES", it will return "Y" as A or B is defined to return A if A is not false. Here, A is "Y" which is not a False value. So, it will return A="Y". If you do if a == ("Y" or "YES"): , il will be equivalent to if a == "Y": . Ok it's a bit tricky but it's how python works.

Moreover, your code is very strange. It's a very bad habit to exit a loop like that. Generally, we put a boolean value "looping" that is set to false when we want to leave the loop.

Here's how I would do your loop:

looping = True 
password = "" 

while looping: 

    ans1 = input("\n\nTest a new password? ")

    if ans1.upper() in ("NO", "N"): 
        looping = False

You can also use a construction with an infinite loop ( while True: ). Then, you call the instruction break to quit the loop.

You could also use "break" or "exit" to go out of the loop or the program. It's also generally better to use a larger condition that goes well in unexpected case (x<=0 or ans1 isn't YES rather than x==0 or ans1 is YES or ans1 is NO).

while True:
  # Code
  if ans1 not in ["Y", "YES"]:
    break # or exit

Then you would have no undefined behavior, and also fewer condition to take care of : if it isn't "YES" or "Y", the program exit.

Well, there is a problem with this line: ans1 == ("Y" or "YES")

It is not similar to this line:

ans1 == "Y" or ans1 == "YES"

The second one is right, the first one is called null coalescing . That's not what you want. Basically, the idiom x or y returns x if x is not null, otherwise it returns y.

So basically you just check if ans1 is "Y" (not "YES")

You can check if a list of idioms contains yours this way:

if ans1 in ["Y", "YES"]:

And you can continue adding values to that list as many as you want.

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