Int*_*upt 7 python conditional-operator conditional-statements
我正在学习Python,而且我遇到了一些问题.在我正在考虑的课程中看到类似的东西后,想出了这个简短的剧本.我之前用过"或"用"if"成功(这里没有显示太多).出于某种原因,我似乎无法让这个工作:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey" or "monkeys":
print "You're right, they are awesome!!"
elif x != "monkey" or "monkeys":
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
Run Code Online (Sandbox Code Playgroud)
但是效果很好:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x == "monkey":
print "You're right, they are awesome!!"
elif x != "monkey":
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
Run Code Online (Sandbox Code Playgroud)
可能这个或有条件的不适合这里.但是我已经尝试了等等,我想要一种让这种接受猴子或猴子的方法,其他一切都会触发你的爱人.
Bar*_*mar 22
大多数编程语言中的布尔表达式都不遵循与英语相同的语法规则.您必须对每个字符串进行单独的比较,并将它们与or以下内容连接:
if x == "monkey" or x == "monkeys":
print "You're right, they are awesome!!"
else:
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right animal."
Run Code Online (Sandbox Code Playgroud)
您不需要对不正确的情况进行测试,只需使用即可else.但如果你这样做,那就是:
elif x != "monkey" and x != "monkeys"
Run Code Online (Sandbox Code Playgroud)
你还记得在逻辑课上学习deMorgan的定律吗?他们解释了如何反转连接或析取.
gkayling 是正确的。您的第一个 if 语句在以下情况下返回 true:
x ==“猴子”
或者
"monkeys" 的计算结果为 true(它确实如此,因为它不是空字符串)。
当您想测试 x 是否是多个值之一时,使用“in”运算符很方便:
test = raw_input("It's the flying circus! Cool animals but which is the best?")
x = test.lower()
if x in ["monkey","monkeys"]:
print "You're right, they are awesome!!"
else:
print "I'm sorry, you're incorrect.", x[0].upper() + x[1:], "is not the right
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
52725 次 |
| 最近记录: |