Ad

While Loop Doesn't Stop With Multiple Conditions

- 1 answer

I am new to coding and i wanted to make a code that could register people and log them back in. while working on my code i wanted to check if the user wanted to login or register so i made this code in python.

login_or_register = None
while login_or_register != 'login' or login_or_register != 'register':

 login_register = input('Would you like to login or register?')
 login_or_register = login_register.lower()
 login_or_register = login_register

While loop doesn't stop even if variable meets the conditions. I tried to remove the second condition and it started to work for some reason. This is probably a dumb question but please be patient I'm a high school student.

Would you like to login or register?login
Would you like to login or register?register
Would you like to login or register?keeps going :(
Would you like to login or register?

It is suppose to stop the loop when input is login or register. Output is suppose to be changing variable login_or_register = None to the answer.

Ad

Answer

The condition of your loop cannot possibly become true.

or returns True if one or both of the two conditions becomes True. If your input is 'login', the first condition is False and the second is True.

For 'register' the first condition becomes True and the second 'False'.

In all other cases both conditions are True. Therefore you have created an infinite loop.

A solution would be connecting the two conditions with an and or even better create a list with all allowed inputs and use an in to check if the user input is in that list. That will be more clear if you have more different options the user is allowed to enter.

For example:

login_or_register = None
while login_or_register not in ['login', 'register']:
    login_register = input('Would you like to login or register?')
    login_or_register = login_register.lower()

You may also want to take a look at the python docs for or and and

Ad
source: stackoverflow.com
Ad