UnboundLocalError: local variable referenced before assignment - 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: local variable referenced before assignment (/thread-23386.html) |
UnboundLocalError: local variable referenced before assignment - svr - Dec-27-2019 Hi Need some help here Original code def test1(): test_list = [] test_var = 0 test_string1 = "" def test2(): temp =2 if temp > test_var: test_var = temp else: test_string = "fail" return test_string res = test2() print res test1()https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value I used both global , nonlocal but both throws different error def test1(): test_list = [] test_var = 0 test_string1 = "" def test2(): nonlocal test_var temp =2 if temp > test_var: test_var = temp else: test_string = "fail" return test_string res = test2() print res test1()throws this error nonlocal test_var ^ SyntaxError: invalid syntax def test1(): test_list = [] test_var = 0 test_string1 = "" def test2(): global test_var temp =2 if temp > test_var: test_var = temp else: test_string = "fail" return test_string res = test2() print res test1()throws this error ^ NameError: global name 'test_var' is not defined Any suggestions ? I have gone through top 10 search results , all suggest to use nonlocal or global... RE: UnboundLocalError: local variable referenced before assignment - perfringo - Dec-27-2019 This is topic with lot of subtlety. Some of the scenarios are discussed in this thread: Namespace and scope difference I think that this boils down to this: Quote:You should also understand difference between reference and assignment: |