L0L59
L0L59

Reputation: 25

How to add integers to a variable outside of the function?

I am currently making a small game, and in this game, I have implemented a point system. This following line of code is mentioned at the beginning of the code:

points = 0

This represents that the player has no points at the moment, but later, these points will keep adding up and the value won't be 0. The first time the player encounters an increase in his points is in this function:

def if_castle_right():
    choice = "\nYou found a silver coin that's worth 5 points!"
    coin = 5
    points += coin
    choice += "\nWhat will to do?"
    choice += "\n[a] Go back \n[b] See points \n[c] Quit \n>"
    inp = input(choice)
    if inp == 'a':
        if_castle()
    elif inp == 'b':
        point_total()
        return if_castle_right()
    elif inp == 'c':
        return
    else:
        char_input_fail()
        return if_castle_right()

The problem is, when I execute the code, this is what is outputted:

File "C:\Users\gabyp\Documents\python_work\game\choose_your_adventure_game.py", line 179, in if_castle_right
    points += coin
UnboundLocalError: local variable 'points' referenced before assignment

I don't know what else to do, because if I invert the points += coin into coin += points, it outputs normally, except that the 5 points that the coin is worth isn't added to the total, it just says 0.

Upvotes: 0

Views: 505

Answers (2)

Roshin Raphel
Roshin Raphel

Reputation: 2689

You can either declare it as a global variable, by calling global points inside the function, before it is accessed, or passing it as an argument and returning it along with if_castle_right() as a tuple like :

def if_castle_right(points):
.
.
.
return (points,if_castle_right())

and calling the function as

points,your_variable = if_castle_right(points)

Upvotes: 0

Julio Suriano
Julio Suriano

Reputation: 151

Add global points inside the function before points += coins.

points = 0

def if_castle_right():
    choice = "\nYou found a silver coin that's worth 5 points!"
    coin = 5
    global points
    points += coin
    choice += "\nWhat will to do?"
    choice += "\n[a] Go back \n[b] See points \n[c] Quit \n>"
    inp = input(choice)
    if inp == 'a':
        if_castle()
    elif inp == 'b':
        point_total()
        return if_castle_right()
    elif inp == 'c':
        return
    else:
        char_input_fail()
        return if_castle_right()

Upvotes: 1

Related Questions