[英]gender input loop keeps repeating even if I enter “m” or “f”
If it's not m or f, repeat prompt until it's either or. 如果不是m或f,则重复提示直到它为or。 I typed m or f, but the loop keeps repeating.
我输入了m或f,但是循环不断重复。 Why?
为什么?
gender = input('m/f? ')
while gender != 'm' or gender != 'f':
print("Type 'm' or 'f'")
gender = input('m/f? ')
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender = 'her'
print("It read {}".format(gender))
Just say gender
is m
. 只是说
gender
是m
。 Look at this statement: 查看以下语句:
while gender != 'm' or gender != 'f':
Is gender!='m'
? 是
gender!='m'
吗? No. Or
... Is gender!='f'
? 不。
Or
……是gender!='f'
吗? Yes! 是! OK, keep
while
ing! OK,保持
while
荷兰国际集团!
You don't want or
, you want and
您不想要
or
,您想要and
Because of this line : while gender != 'm' or gender != 'f':
由于这一行:
while gender != 'm' or gender != 'f':
Use instead : while gender != 'm' and gender != 'f':
改为使用:
while gender != 'm' and gender != 'f':
gender
cannot simultaneously contain 'm' and 'f' gender
不能同时包含“ m”和“ f”
The basic fundamental 基本面
True or True : True 正确或正确:正确
True or False : True 是非题:是
False or True : True 错误或正确:正确
False or False : False 错误或错误:错误
You have to continue asking for input as long as both the conditions are not satisfied. 只要两个条件都不满足,就必须继续请求输入。
Or has to be replaced by 'and'. 或必须替换为“和”。
Try: 尝试:
gender = raw_input('m/f?')
while True:
print("Type 'm' or 'f'")
gender = raw_input('m/f? ')
if gender=='m' or gender=='f':
break
if gender == 'm':
gender = 'him'
elif gender == 'f':
gender = 'her'
print("It read {}".format(gender)) print(“读取为{}”。format(gender))
There's a number of answers already, but I think the most Pythonic way, which also eliminates the AND/OR confusion is, and is easily extendable if you want to add, say, o
for other
已经有很多答案了,但是我认为,最Python化的方式也消除了AND / OR混淆,并且如果您想为
other
添加o
,则很容易扩展。
while gender not in 'mf':
That is, while gender
is not present in the list of genders. 也就是说,
gender
列表中不存在性别。
In your while, you are checking to see if either the string gender does not equal 'm' OR 'f', which will always be the case because it cannot be both. 在您检查的同时,您要检查字符串的性别是否不等于'm'或'f',这将一直存在,因为不能同时为两者。
Change or to and to fix this. 更改为或修复此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.