#'Local variable gold referenced before assignment'

31 messages · Page 1 of 1 (latest)

keen swift
#

basically for homework i've had to make this text based adventure game and for some reason it comes up with the error in the image and i barely code so idk what to do. if you need me to put anymore of the code just say

dusk sinew
#

Did you initialize the variable gold 🤔

keen swift
#

i have no clue what that means sorry

#

i'll send a screenshot of the relevant bit

dusk sinew
#

Like set it to a value?

keen swift
#

yeah

#

here

median lichen
#

You redefined gold inside the function. If you want to assign to a global variable from within a function you've gotta add global gold inside your function.

keen swift
#

ohh thanks for the help big man 🙏

#

would i add that to the first or second gold?

median lichen
#

That's a line all to itself. Typical to put the global variable lines at the beginning of the function

#
def my_function():
    global some_variable
    some_variable = "some value"
keen swift
#

aight okay thanks, i'll do that now

#

def gold():
global gold
gold = int(10)

#

would that be okay?

#

or does the function thing need to be something different>

dusk sinew
#

I think name of function should be different

#

But i think they meant to add global gold to your existing function

keen swift
#

oh okay i'll plug that in

#

wait and every time i use gold do i use the function name or the variable name?

median lichen
#

Gold is a variable. If you want the value of the variable use the variable name. If you want to use the function use the function name.

keen swift
#

ok, thanks big dog

#

so for the line that's breaking everything i'd use global gold, right?

median lichen
#

Try it and see

keen swift
#

it says invalid syntax

median lichen
#

Please show the code that gives the error

keen swift
median lichen
#

The line with the global keyword needs to be exactly how I showed. You do not use the global keyword any other way.

#

It happens once in the function to tell the Python interpreter that your function will need to use that global variable at some point.

keen swift
#

ohhh sorry yeah i get what you mean now