python if子句中的奇怪行为 [英] weird behaviour in python if clause

查看:45
本文介绍了python if子句中的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用python写了一个简单的小石头,剪刀布游戏,并且在if子句上遇到了一些困难,这是相关代码:

I wrote a simple little rock, paper, scissors game in python and had some difficulties with an if clause, here's the relevant code:

def play():
    user = str(input("rock, paper or scissors? Choose one: "))
    print("You chose", user)

    if user == "paper" or "Paper":
        paper()

    elif user == "rock" or "Rock":
        rock()

    elif user == "scissors" or "Scissors":
        scissors()

    else:
        print("Sorry, your choice was not valid, try again please.")
        play()

现在,无论我选择石头,纸张还是剪刀,它总是会触发第一个条件,从而使我进入纸张功能.我实际上已经解决了它,这是我在if子句中输入的第二个条件,即"Paper","Rock"和"Scissors",这些是我在大写中用大写第一个字母表示的.我的问题是,为什么第二个条件触发了第一个if子句?当我移走所有第二根弦时,它工作得非常好,岩石触发了第二个条件,剪刀一个触发了第三个条件,依此类推.我希望这不要太令人困惑.谢谢.

Now, no matter whether I chose rock, paper or scissors, it would always trigger the first condition, leading me to the paper function. I actually already solved it, it was the second condition I put in the if clauses, the "Paper", "Rock" and "Scissors", which I put there for the case people uppercase the first letter. My question is, why did the second condition trigger the first if clause? When I removed all the second strings, it worked perfectly fine, the rock triggered the second condition, the scissors one triggered the third and so on. I hope this is not too confusing. Thanks.

推荐答案

user == "paper" or "Paper"

始终为真.或运算符在其本身的任一侧测试表达式,并且如果任一表达式为true,则或的结果也为true.上面的测试检查(最多)两件事:

is always true. The or operator tests the expressions on either side of itself, and if either is true, the result of the or is also true. Your test above checks (up to) two things:

  • 表达式 user =="paper" 是真的吗?如果是这样,则整个表达式为true,所以不要检查第二部分,因为 True或x 始终为true,而与 x 的值无关.
  • 表达式"Paper" 是否正确?而且由于非零长度的字符串在Python中是正确的,所以这部分始终是正确的.
  • Is the expression user == "paper" true? If so, the whole expression is true, so don't check the second part, because True or x is always true regardless of the value of x.
  • Is the expression "Paper" true? And because non-zero-length strings are true in Python, this part is always true.

因此,即使第一部分为假,第二部分也始终为真,因此整个表达式始终为真.

So even if the first part is false, the second part is always true, so the expression as a whole is always true.

您想要这样的东西:

user == "paper" or user == "Paper"

或者更好的是:

user in ("paper", "Paper")

或者,最好的是:

user.lower() == "paper"

这篇关于python if子句中的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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