[英]While loop doesn't stop with multiple conditions
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. 我是编码新手,我想制作一个可以注册人员并重新登录的代码。在编写我的代码时,我想检查用户是否要登录或注册,所以我用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. 即使变量满足条件,while循环也不会停止。 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.
假设输出将答案更改为login_or_register = None。
login_or_register != 'login' or login_or_register != 'register'
will always be True. login_or_register != 'login' or login_or_register != 'register'
始终为True。 You probably want to use a logical and
: 您可能要使用逻辑
and
:
while login_or_register != 'login' and login_or_register != 'register':
# ....
The condition of your loop cannot possibly become true. 循环的条件不可能变为真。
or
returns True
if one or both of the two conditions becomes True
. or
返回True
,如果这两个条件中的一个或两个变成True
。 If your input is 'login'
, the first condition is False
and the second is True
. 如果您输入的是
'login'
,则第一个条件为False
,第二个条件为True
。
For 'register'
the first condition becomes True
and the second 'False'
. 对于
'register'
,第一个条件为True
,第二个为'False'
。
In all other cases both conditions are True
. 在所有其他情况下,两个条件均为
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. 一种解决方案将连接用的两个条件
and
甚至更好地创造了所有允许的输入列表并使用in
检查,如果用户输入是在该列表中。 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
您可能还想看看
or
和and
的python文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.