Python 我的if-else语句不';我不能工作,不能指挥一切
如果我输入,让我们说“好”,它会输出以下内容: 不能那样做! 伟大的 好吧,那么Python 我的if-else语句不';我不能工作,不能指挥一切,python,python-3.x,Python,Python 3.x,如果我输入,让我们说“好”,它会输出以下内容: 不能那样做! 伟大的 好吧,那么 而不是“不能那样做”。我不知道出了什么问题,也找不到这样的问题。改为做一些更像蟒蛇的事情: ans = input("Enter yes or no: ") if ans != "Yes" or "yes" or "no" or "No": print("Can't do that"
而不是“不能那样做”。我不知道出了什么问题,也找不到这样的问题。改为做一些更像蟒蛇的事情:
ans = input("Enter yes or no: ")
if ans != "Yes" or "yes" or "no" or "No":
print("Can't do that")
if ans == "yes" or "Yes":
print("Great!")
if ans == "no" or "No":
print("Okay, then")
使用elif
而不是执行另一个if验证。在中使用:
if ans.lower() in ['no', 'yes']:
这不是在编程语言中使用逻辑运算符的方式,它应该是:
ans = input("Enter yes or no: ")
if ans in ["Yes", "yes"]:
print("Great!")
elif ans in ["No", "no"]:
print("Okay, then")
else:
print("Can't do that")
如您所见,您应该始终重复变量。测试答案是在列表中还是在集合中(使用下面示例中的集合)。否则,第一个条件的计算结果为True
。这是因为运算符的优先级,Python认为它等同于(ans!=“Yes”)或(“Yes”)或(“no”)或(“no”)
。而“yes”
是True
,因为它不是空字符串(),这使得整个表达式的计算结果也是True
if (ans != "Yes") or (ans != "yes") or (ans != "no") or (ans != "No")
更好的是,将其缩短,如下所示:
ans = input("Enter yes or no: ")
if ans not in {"Yes", "yes", "no", "No"}:
print("Can't do that")
if ans in {"yes", "Yes"}:
print("Great!")
if ans in {"no" or "No"}:
print("Okay, then")
or运算符分配不正确。请尝试此操作
ans=输入(“输入是或否:”)
如果是ans!=“是”或“是”或“否”或“否”:
打印(“不能那样做”)
如果ans==“是”或“是”:
打印(“太好了!”)
如果ans==“否”或“否”:
打印(“好吧,那么”)
你可以写
如果在('stringone','stringtwo')中有ans:
dosomething()
或者您可以编写单独的相等性测试
ans = input('Enter yes or no: ').lower()
if ans == 'yes':
print('Great!')
elif ans == 'no':
print('Okay, then')
else:
print("Can't do that")
这回答了你的问题吗?你真的有必要要求对你所有的答案投赞成票吗?当然没有。
if var == 'stringone' or var == 'stringtwo':
dosomething()