RPS: NameError: name "computer_choice" is not defined


#1

Hello,
I'm stuck with Rock, Paper, Scissors exercise, where I get the following error:

$ python RPS.py
Computer selecting...
Traceback (most recent call last):
File "RPS.py", line 14, in
print "Computer selected: %s" % (computer_choice)
NameError: name 'computer_choice' is not defined

I have looked for spelling errors and couldn't find any typos. I don't understand where this error comes from, as I defined computer_choice on the 3rd line from the bottom and it matched the answer in the hints.
What am I missing here anybody?

from random import randint
from time import sleep

options = ["R", "P", "S"]
LOSS_MESSAGE = "You lost!"
WIN_MESSAGE = "You won!"

def decide_winner(user_choice, computer_choice):
    print "You selected: %s" % user_choice
print "Computer selecting..."
sleep(1)
print  "Computer selected: %s" % computer_choice
user_choice_index = options.index(user_choice)
computer_choice_index = options.index(computer_choice)
if user_choice_index == computer_choice_index:
  print "It's a tie!"
elif user_choice_index == 0 and computer_choice_index == 2:
  print WIN_MESSAGE
elif user_choice_index == 1 and computer_choice_index == 0:
  print WIN_MESSAGE
elif user_choice_index == 2 and computer_choice_index == 1:
  print WIN_MESSAGE
elif user_choice_index > 2:
  print "Invalid option"
else:
  print LOSS_MESSAGE
    
def play_RPS():
  print "Rock, Paper of Scissors?"
  user_choice = raw_input("Select R for Rock, P for Paper or S for Scissors: ")
  user_choice = user_choice.upper()
  computer_choice = options[randint(0, len(options)-1)]
  decide_winner(user_choice, computer_choice)
play_RPS()

#2

You have indeed defined computer_choice, but only within the scope of the decide_winner() function.

My suspicion is that the line print "Computer selecting..." and henceforth is also supposed to be part of the decide_winner() function, in which case you need to fix your indentation.

Don't forget that anything that's part of a function must be properly indented to indicate so, as Python is very strict when it comes to whitespace.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.