Skip to content
← Back to Community
UnboundLocalError: local variable 'money' referenced before assignment
Profile icon
zachaaa

My code says that I am using a variable before defining it but I define it before I use it.

Thanks for helping!

Voters
Profile icon
LEONELAGUIRRE
Profile icon
goatsgogrr
Profile icon
DSARehan
Profile icon
zachaaa
Comments
hotnewtop
Profile icon
MrEconomical

global variables in python are different, when you access it in a function it thinks you are trying to access a local variable

fix this by at the top of the function add a line: global money

Profile icon
delonbest

All variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.

The unboundlocalerror: local variable referenced before assignment is raised when you try to use a variable before it has been assigned in the local context. Python doesn't have variable declarations , so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local .