Skip to content
Advertisement

Error: UnboundLocalError: local variable ‘attempts’ referenced before assignment

I am attempting to make a simple guessing game for my class with graphics and I’m trying to make an attempt counter. This is the area where my code is going wrong.

JavaScript

The error I receive is:

JavaScript

It doesn’t seem possible to move attempts into the function as it constantly calls itself, resetting attempts each time.

I am unsure why this is occurring so any help would be greatly appreciated. Thanks!

Advertisement

Answer

The reason you are getting this error is because of something called variable scope. You have defined the variable attempts outside of the function value, so the function will not recognize any local variable by the name attempts unless you explicitly put the statement global attempts at the beginning of your function. This will tell the function that you want to use the variable attempts that you defined in your main program. That should look like this:

JavaScript

Alternatively, you can allow your function value to take an argument, and pass the variable attempts into that. That would look something like this:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement