0

Making a RPS game for a school assignment

import random
#player score
p1 = 0
p2 = 0
#add score
def AddScore(a,c):
    print(a + " +1")
    if c == "hum":
        p1+=1
    else:
        p2+=1
    
#gets player choices
while p1 < 3 or p2 < 3:
    print("Rock, Paper, Scissors, Shoot!")
    a = int(input("Rock, Paper or Scissors? (1, 2, 3):"))
    b = random.randint(1,3)
    if a == b:
        print("Draw!")
    elif a > b and a != 1:
        AddScore("Human", "hum")
    elif a == 1 and b == 3:
        AddScore("Human", "hum")
    elif b > a and b != 1:
        AddScore("Computer", "comp")
    elif a == b and a == 3:
        AddScore("Computer", "comp")
    print(p1)
    print(p2)

returns error on lines 9 and 21:

UnboundLocalError: local variable 'p1' referenced before assignment

2 Answers2

0

The reason why you get an error is because p1 and p2 inside AddScore are local variables and are bound to that function. However, p1 and p2 outside the function are global variables but since every variable inside a function is local by default they cannot be accessed inside the function.

You need to explicitly indicate that you want to use p1 and p2 global variables inside the function.

def AddScore(a,c):
    global p1, p2
    print(a + " +1")
    if c == "hum":
        p1+=1
    else:
        p2+=1

You may want to read the following article about function scopes: https://www.w3schools.com/python/python_scope.asp

squancy
  • 565
  • 1
  • 7
  • 25
0

This is a scoping issue. By reassigning the name, the Python interpreter reserves the reassigned name for local usage, thus shadowing the previous value from the outer scopes, which results in the name being unbound if used before the first assignment.

A simple, but highly discouraged, solution is to explicitly set p1 and p2 as globals.

def AddScore(a,c):
    global p1, p2
    print(a + " +1")
    if c == "hum":
        p1+=1
    else:
        p2+=1

A cleaner approach would be to ask and return p1 and p2:

def AddScore(a, c, p1, p2):
    print(a + " +1")
    if c == "hum":
        p1+=1
    else:
        p2+=1
    return p1, p2

to be used as:

p1, p2 = AddScore(..., ..., p1, p2)
norok2
  • 25,683
  • 4
  • 73
  • 99