Python Forum
UnboundLocalError: local variable referenced before assignment
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
UnboundLocalError: local variable referenced before assignment
#1
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...
Reply


Messages In This Thread
UnboundLocalError: local variable referenced before assignment - by svr - Dec-27-2019, 05:23 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,154 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  local varible referenced before assignment SC4R 6 1,517 Jan-10-2023, 10:58 PM
Last Post: snippsat
  How does UnboundLocalError work? deanhystad 3 1,674 Feb-25-2022, 01:21 AM
Last Post: bowlofred
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,906 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  Referenced before assignment finndude 3 3,264 Mar-02-2021, 08:11 PM
Last Post: finndude
  exec + subprocess = UnboundLocalError paul18fr 6 3,492 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  ReferenceError: weakly-referenced object no longer exists MrBitPythoner 17 11,503 Dec-14-2020, 07:34 PM
Last Post: buran
  Assignment of non-existing class variable is accepted - Why? DrZ 6 4,264 Jul-13-2020, 03:53 PM
Last Post: deanhystad
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,265 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  UnBoundLocalError Seaninho 3 2,672 May-31-2020, 07:22 AM
Last Post: azajali43

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020