我的 If 语句只选择第一个选项
My If statements only choosing first option
这是我的代码
while True:
username = raw_input("Username:")
time.sleep(1)
print username
qwerty = raw_input("Is this right?")
if qwerty == 'yes' or "Yes" or "Yeah" or "yeah" or "yup" or "Yup":
print "OK."
break
elif qwerty == 'no' or 'No' or 'nope' or 'Nope' or 'nah' or 'Nah':
print "Please type your Username again"
continue
else:
print "Please Try a more common answer"
continue`
我不知道出了什么问题,因为我输入的内容只会出现在第一个选项中。有人知道为什么吗?
您需要将 if
中的条件更新为:
if qwerty in ['yes', "Yes", "Yeah", "yeah", "yup", "Yup"]
解释:
or
in Python 执行逻辑 OR
运算。如果值为True
,则条件满足,否则进入or
中的下一个条件。为了让你更清楚。例如:
>>> 'Hello' or 'Man'
'Hello'
>>> '' or 'Man'
'Man'
另外,请注意 python 将非零和非空字符串值视为 True
。
您的案例示例:
>>> querty = 'Yes'
>>> querty == 'yes' # This returns False
False
>>> querty == 'yes' or 'Yes' # Goes to next condition since 1st is False
'Yes' # Since it is non-empty string, retuns that value
# and 'if' treats that as True
这是我的代码
while True:
username = raw_input("Username:")
time.sleep(1)
print username
qwerty = raw_input("Is this right?")
if qwerty == 'yes' or "Yes" or "Yeah" or "yeah" or "yup" or "Yup":
print "OK."
break
elif qwerty == 'no' or 'No' or 'nope' or 'Nope' or 'nah' or 'Nah':
print "Please type your Username again"
continue
else:
print "Please Try a more common answer"
continue`
我不知道出了什么问题,因为我输入的内容只会出现在第一个选项中。有人知道为什么吗?
您需要将 if
中的条件更新为:
if qwerty in ['yes', "Yes", "Yeah", "yeah", "yup", "Yup"]
解释:
or
in Python 执行逻辑 OR
运算。如果值为True
,则条件满足,否则进入or
中的下一个条件。为了让你更清楚。例如:
>>> 'Hello' or 'Man'
'Hello'
>>> '' or 'Man'
'Man'
另外,请注意 python 将非零和非空字符串值视为 True
。
您的案例示例:
>>> querty = 'Yes'
>>> querty == 'yes' # This returns False
False
>>> querty == 'yes' or 'Yes' # Goes to next condition since 1st is False
'Yes' # Since it is non-empty string, retuns that value
# and 'if' treats that as True