Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 471
FearlessENT Avatar asked Aug 03 '26 11:08

FearlessENT


2 Answers

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.

like image 129
Alexis Clarembeau Avatar answered Aug 06 '26 01:08

Alexis Clarembeau


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.

like image 26
Pierre.Sassoulas Avatar answered Aug 06 '26 01:08

Pierre.Sassoulas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!