“或”有条件的Python麻烦 [英] "or" conditional in Python troubles

查看:53
本文介绍了“或”有条件的Python麻烦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Python,但遇到了一些问题。在我正在学习的课程中看到类似内容后,想出了这个简短的脚本。在成功使用之前,我将或与 if一起使用(此处显示不多)。由于某些原因,我似乎无法正常工作:

  test = raw_input(这是马戏团!酷动物!哪一个是最好的?)
x = test.lower()

如果x == monkey或 monkeys:
打印你是对的,它们是太棒了!
elif x!= monkey或 monkeys:
打印对不起,您输入的错误。,x [0] .upper()+ x [1:],不是正确的动物。

但这很好用:

  test = raw_input(这是飞行的马戏团!很酷的动物,但这是最好的?)
x = test.lower()

如果x == 猴子:
打印你是对的,他们很棒!
elif x!=猴子:
打印对不起,您输入的错误。,x [0] .upper()+ x [1:],不正确动物。

可能的or条件不适合此处。但是我已经尝试过,等等。我希望有一种方法可以使它接受一个或多个猴子,而其他所有东西都会触发精灵。

解决方案

布尔表达式不遵循与英语相同的语法规则。您必须对每个字符串分别进行比较,然后将它们与连接:

 如果x == monkeys或x == monkeys:
print您说得对,它们很棒!
else:
打印对不起,您错了。,x [0] .upper()+ x [1:],不是正确的动物。

您不需要为不正确的情况进行测试,只需使用 else 。但是,如果这样做,它将是:

  elif x!=猴子和x!=猴子 

您还记得关于德摩根定律在逻辑课上吗?他们解释了如何反转合取或析取。


I'm learning Python and I'm having a little bit of a problem. Came up with this short script after seeing something similar in a course I'm taking. I've used "or" with "if" before with success (it doesn't show much here). For some reason I can't seem to get this working:

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."

But this works great:

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."

Probably the or conditional does not fit here. But I've tried and, etc. I'd love a way to make this accept monkey or monkeys and everything else triggers the elif.

解决方案

Boolean expressions in most programming languages don't follow the same grammar rules as English. You have to do separate comparisons with each string, and connect them with 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."

You don't need to do the test for the incorrect case, just use else. But if you did, it would be:

elif x != "monkey" and x != "monkeys"

Do you remember learning about deMorgan's Laws in logic class? They explain how to invert a conjunction or disjunction.

这篇关于“或”有条件的Python麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆