mannayz mannayz - 5 months ago 9
Python Question

Python - Compare string to random item from list

Looking through a lot of existing questions and not seeing quite the same scenario. I'm working through the basics of Python and trying to create the ubiquitous Rock, Paper, Scissors game. However, I've got a variable equal to the user's guess which I can't get to compare successfully against a randomly selected item that represents the computer's guess. Everything evaluates to "You win! :)", even when it shouldn't which suggests the two variables are never equal to each other. I've tried using str(computer_choice) without any luck.

Here's the entirety of the code:

import time
import random

rps = ['Rock', 'Paper', 'Scissors']

computer_choice = random.sample(rps, 1)

print("Let's play some Rock, Paper, Scissors")
print("Hit enter when ready:")
input("")

print("Rock...")
time.sleep(1)
print("Paper...")
time.sleep(1)
print("Scissors...")
time.sleep(.75)
print("SHOOT!")

print("Which is it?")
user_choice = input(">>>")



while True:
valid_check = user_choice in rps
if valid_check == True:
break
else:
print('Bad input, try again:')
user_choice = input(">>>")

print("The computer picked: %s" % computer_choice)

if user_choice == computer_choice:
print("It's a draw!")

elif user_choice == 'Rock':
if computer_choice == 'Paper':
print("You lose :(")

else:
print("You win! :)")

elif user_choice == 'Paper':
if computer_choice == 'Scissors':
print("You lose :(")

else:
print("You win! :)")

elif user_choice == 'Scissors':
if computer_choice == 'Rock':
print("You lose :(")

else:
print("You win! :)")

Answer

You need to use random.choice(rps) which returns an element of the original list rather than random.sample(rps,1) which returns a list of size 1 from the original list.