How Do You Troubleshoot an Error Such as “UnboundLocalError: local variable ‘foobar’ referenced before assignment”?

Problem scenario
You run a Python program. You receive this message: "UnboundLocalError: local variable 'foobar' referenced before assignment"

What should you do?

Initialize the variable (e.g., foobar = 0). If you do so inside a function wherein foobar, that may work. If you want it to be available globally throughout your program, you will initialize it outside of a function. To gain access to the variable inside a function, use this syntax: global foobar

Leave a comment

Your email address will not be published. Required fields are marked *