Reputation: 11
I am making a simple rock, paper, scissors game in python - and the counter variable comes up as an error neither me or my computer science can seem to place.
import random
options = ["R", "P", "S"]
userwin = 0
computerwin = 0
counter = 0
def RPS():
counter = counter + 1
computerchoice = random.choice(options)
print ("It's round number", counter, "!")
humanchoice = input ("Do you choose rock [R], paper [P] or scissors[S]?")
if computerchoice == "R":
if humanchoice == "R":
print ("Rock grinds rock - it's a draw!")
if humanchoice == "P":
print ("Paper wraps rock - you win!")
userwin = userwin + 1
if humanchoice == "S":
print ("Rock blunts scissors - you lost!")
computerwin = computerwin + 1
if computerchoice == "S":
if humanchoice == "S":
print ("Scissors strikes scissors - it's a draw!")
if humanchoice == "R":
print ("Rock blunts scissors - you win!")
userwin = userwin + 1
if humanchoice == "P":
print ("Scissors cuts paper - you lost!")
computerwin = computerwin + 1
if computerchoice == "P":
if humanchoice == "P":
print ("Paper folds paper - it's a draw!")
if humanchoice == "S":
print ("Scissors cuts paper - you win!")
userwin = userwin + 1
if humanchoice == "S":
print ("Paper wraps scissors - you lost!")
computerwin = computerwin + 1
while userwin < 10 or computerwin < 10:
RPS()
The error which comes up is
counter = counter + 1
UnboundLocalError: local variable 'counter' referenced before assignment
I haven't come across this error before - and am unsure how to fix it. Any ideas? Thank you!
Upvotes: 0
Views: 66
Reputation: 2358
You can't assign global variables in a function, you need to do it like:
def RPS():
global counter
counter = counter + 1
computerchoice = random.choice(options)
You have to do it for every variable that's defined outside the function.
Upvotes: 1