pythonif-statementclause

weird behaviour in python if clause


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()

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.


Solution

  • user == "paper" or "Paper"
    

    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:

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

    You wanted something like this:

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

    or, better yet:

    user in ("paper", "Paper")
    

    or, best of all:

    user.lower() == "paper"