I’m collaborating on a text-based Pokémon game but cant seem to figure out why a variable is giving the error “local variable referenced before assignment” when it is defined as one of the first things. Please help!
Link: https://replit.com/@IronCodem/Pokemon-RPG-Game?v=1
How to recreate: enter your username, choose your Pokémon and type “find”.
It’s because how you are using global
variables.
If a variable is defined outside of any function, it’s a global variable. If it’s defined within a function, it’s a local variable.
In your code, met
is defined as a global variable, but when you try to modify it inside the wild_pokemon()
function with met += 1
, Python treats met
as a local variable. But, since met
hasn’t been defined in the local scope, so you got the error: local variable referenced before assignment
.
So… you need to add the statement global met
at the beginning of the wild_pokemon()
function. This tells Python that in this function, met
refers to the global variable met
, not a new local variable.
Like this:
def wild_pokémon():
global met # Add the variable here
random_pokémon = pokelist[random.randint(0, len(pokelist) - 1)]
random_pokémon_name = random_pokémon.getVar("name")
Great! Thanks for the help!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.