I’m a new programmer and am trying to familiarize myself with if else statements by creating a rock paper scissors game. My problem is that the code always lets me win. In addition, my while loop won’t actually loop so any help with this stuff would be greatly appreciated. Thanks! :)
The code:
from random import randint t = ["Rock", "Paper", "Scissors"] computer = t[randint(0, 2)] player = False while player == False: player = input("Rock, Paper, or Scissors: ").lower() if player == computer: print("Computer:" + player.capitalize()) print("Tie!") elif player == "rock": if computer == "Paper": print("Computer: Paper") print("You lose") else: print("Computer: Scissors") print("You Win!") elif player == "paper": if computer == "Scissors": print("Computer: Scissors") print("You Lose!") else: print("Computer: Rock") print("You win") elif player == "scissors": if computer == "Rock": print("Computer: Rock") print("You lose!") else: print("Computer: Paper") print("You Win!") else: print("Invalid input. Try again!") player = False computer = t[randint(0, 2)]
Advertisement
Answer
The game doesn’t repeat because your condition player == False
is never true after the player has made a choice. It always contains the player’s last choice, which isn’t False
.
Instead of using that while
condition, allow the user to enter something like quit
. Then check for that before running the rest of the code, and break out of the loop.
You can use random.choice()
to select an item from a list, instead of randint()
.
The computer’s choice needs to be in the loop. Otherwise, the player can always win because the computer’s choice never changes.
from random import choice t = ["Rock", "Paper", "Scissors"] while True: player = input("Rock, Paper, Scissors, or quit: ").lower() if player == 'quit': break computer = choice(t) if player == computer: print("Computer:" + player.capitalize()) print("Tie!") elif player == "rock": if computer == "Paper": print("Computer: Paper") print("You lose") else: print("Computer: Scissors") print("You Win!") elif player == "paper": if computer == "Scissors": print("Computer: Scissors") print("You Lose!") else: print("Computer: Rock") print("You win") elif player == "scissors": if computer == "Rock": print("Computer: Rock") print("You lose!") else: print("Computer: Paper") print("You Win!") else: print("Invalid input. Try again!")