sudo
sudo

Reputation: 11

python while - unexpected result

if __name__ == '__main__':

    val='n'
    while val != 'y' or val != 'Y':
        val = input("are we done ? [Y/n]: ")

    exit()

and got quite perplexed as the result is

are we done ? [Y/n]: y  
are we done ? [Y/n]: y  
are we done ? [Y/n]: Y  
are we done ? [Y/n]: Y  
are we done ? [Y/n]: yes  
are we done ? [Y/n]:  

I though perhaps related question will help but still not happy about it. anybody knows why my first trial fails as it does?

Upvotes: 1

Views: 76

Answers (4)

Bartosz Karwacki
Bartosz Karwacki

Reputation: 331

if __name__ == '__main__':

    while (val:=input("are we done ? [Y/n]: ").lower()) != 'y':
        pass

    exit()

Upvotes: 0

Adit Magotra
Adit Magotra

Reputation: 39

You need to replace or with and.

This is because you want the loop to stop running only if both the conditions are true.

Final code :-

if __name__ == '__main__':
    
        val='n'
        while val != 'y' and val != 'Y':
            val = input("are we done ? [Y/n]: ")

        exit()

Upvotes: 0

PCM
PCM

Reputation: 3011

Better use .lower() method -

if __name__ == '__main__':

    val='n'
    while val.lower() != 'y': # This will work for 'y' and 'Y'
        val = input("are we done ? [Y/n]: ")

    exit()

You could make it better -

if __name__ == '__main__':

    while True:
        val = input("are we done ? [Y/n]: ")

        if val.lower() == 'y':
            exit()

Upvotes: 0

Leonard
Leonard

Reputation: 833

It's your condition while val != 'y' or val != 'Y'. This will always be true, even if val is y because then it is not Y.

Try

while val != 'y' and val != 'Y':

This is only true if it is neither, y nor Y.

Upvotes: 3

Related Questions