1

So I'm practising python, and doing simple tasks, so I tried making a Rock Paper Scissors game. It kept screwing up, and I've reduced most of the code to a point where the annoying code remains. When I try executing this, no matter what I input into the p_choice input, it thinks it's rock, paper, or scissors. Whether I write "rock", "a", or "ro", or anything, the code prints X.

def game(): 
      p_choice = input("Rock, Paper, Scissors?: ").lower() 
      if p_choice == "rock" or "paper" or "scissors":
        print("X")
      else:
        print("Y")

It's worth noting the spacing is not causing the issue,Obviously the print command is not intended for the final code, but I'm just using it as a quick way to see whether the intended function is occurring. It's not, and I can't even begin to understand why. Does anyone understand what's going on?

It's probably worth noting I'm using an online exectuter repl.it. Since I've already asked one question, I may as well ask another here: my computer won't execute python script. It just opens the window and immediately closes it, even if there's supposed to be user input before it closes. Hence why I'm using repl.it instead of an offline version. Anyway, any help would be greatly appreciated.

Confused
  • 13
  • 2

1 Answers1

2

The == operator in programming languages usually compares the expression on the left with the expression on the right. Also, or has lower precedence. This means that the expression in your case is evaluated as: (p_choice == "rock") or ("paper") or ("scissors"). "paper" and "scissors" are always evaluated as True, making the whole expression effectively always True.

The correct code would be:

def game(): 
  p_choice = input("Rock, Paper, Scissors?: ").lower() 
  if p_choice in ["rock", "paper", "scissors"]:
    print("X")
  else:
    print("Y")
Forketyfork
  • 7,416
  • 1
  • 26
  • 33