0

UnboundLocalError question.

I'm learning to code in python, and to challenge myself and get some good practice i decided to try to make a simple card game. The link to the code is below: https://code.sololearn.com/cL0plOMlcUp3/#py when i run this code, I get an error message: Traceback (most recent call last): File "..\Playground\", line 81, in <module> rollvalue() File "..\Playground\", line 70, in rollvalue if y in hearts: UnboundLocalError: local variable 'hearts' referenced before assignment This doesn't make any sense to me because the dictionaries containing all the cards in each suit are clearly defined/assigned. additionally, they can be called by one of the defined functions (rollsuit())but not the other (rollvalue()). If anyone has more experience than me in stuff like this and some time to sink into my little problem, I'd appreciate some clarity. Thank you.

11th May 2019, 3:57 PM
Erik Bouwhuis
3 ответов
+ 5
Unless a variable is declared global, you can use its value in a function, but you can't change (or delete) it. "hearts" is declared before the function, so it is a valid global variable that can be used (e.g. printed) in the function. Because it is a list, you can also append or delete items. But you can't delete the list/variable as a whole (line 66). To do so, you need a "global hearts" statement in your function. Otherwise python will think that hearts is a local variable and that you try to delete a (local) variable before you even declared it.
11th May 2019, 4:07 PM
Anna
Anna - avatar
+ 2
Works for me. Add "global clubs, diamonds, hearts, spades" after def rollvalue(). You might run into a situation where e.g. diamonds isn't defined anymore (line 66) because you deleted it before in line 38 or 43, but in this case there's something wrong with the logic, not with the usage of local vs. global variables
11th May 2019, 4:27 PM
Anna
Anna - avatar
0
I gave that a quick try, but i run into the same error code.
11th May 2019, 4:21 PM
Erik Bouwhuis