UnboundLocalError Problem - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: UnboundLocalError Problem (/thread-17064.html) |
UnboundLocalError Problem - DrChicken24 - Mar-27-2019 So I am making my first game in python. It is a text RPG. Obviously I can't post the entire code on here, but I think this will be enough to hopefully get this solved. So right now I am creating achievements. For example, I have one where defeating 10 enemies gives you an achievement titled "soldier". My problem is with this. I set my enemies defeated to 9 and then went into combat and defeated one more to see if the achievement would work. I got this error: This is the code that it is referencing:soldier_achievement = False hunter_achievement = False slayer_achievement = False executioner_achievement = False john_achievement = False shopper_achievement = False merchant_achievement = False cheater_achievement = False dedication_achievement = False frich_achievement = False frrich_achievement = False fstich_achievement = False explorer_achievement = False def earn_achievement(): if player.enemies_killed >= 10 and soldier_achievement == False: print("#######################") print("# Achievement Earned! #") print("# 'Soldier' #") print("#######################") player.achievements.append('Soldier') soldier_achievement = True player.gold += 10 prompt()I've been looking at this for an hour and trying different things to get it to work, but nothing has changed. Anyone have any ideas? If you need more information I will gladly give some. RE: UnboundLocalError Problem - ichabod801 - Mar-27-2019 By assigning to soldier_achievement inside earn_achievement, Python thinks the variable is local to the function (at the time the function is defined). Therefore, it can't see the assignment to the global soldier_achievement on line 1. But then when it gets to line 15 at run time, the local version hasn't been assigned yet, and gives you the error. You would need to pass the global variable to the function as a parameter, and get a new value out as a return value. It would probably be better to have a dictionary with all of those global variables as key/value pairs. However, you should learn more about functions before moving forward. I would suggest the function text_adventure tutorials linked to in my signature, below. |