Python local variable referenced before assignment Solution

Posted in /  

Python local variable referenced before assignment Solution
vinaykhatri

Vinay Khatri
Last updated on May 30, 2024

    The most common error you may encounter while working with Python and user-defined functions is UnboundLocalError: local variable 'name' referenced before assignment . The reason for this error occurrence is we try to access a variable before it has been assigned in the local scope or context of the function.

    In this Python guide, we will walk through this Python error and discuss why this error occurs and how to solve it. We will also look at some examples so that you can get a better idea about this Python error.

    The error: UnboundLocalError: local variable referenced before assignment?

    The error statement UnboundLocalError: local variable referenced before assignment is divided into two statements

    1. UnboundLocalError: It is a Python error type that occurs when we mishandle the Python local variables.
    2. the local variable referenced before assignment : This is the error message that tells that we are trying to access or assign a new value to a Python local variable before its initialization.

    Error Reasons

    There are two main reasons why your Python program is showing this error.

    1. You are trying to create a new local variable with the same name as the global variable and using the value of the global variable.
    2. Or, have created a local variable inside a function using the if..else statement, and it never gets assigned, and you are accessing it.

    Reason 1

    This is the major scenario where the Python learner commits a mistake. When they try to create a new local variable with the same name as the global variable after accessing the global variable into the function.

    Once you have accessed the global variables into a Python function, you can not create a local variable with the same name. If you do, you will receive the UnboundLocalError: local variable referenced before assignment error.

    Example

    # function
    def add_last_name(lname):
        #creating new variable name and accessing the global variable name
        name = name + lname
        print(name)
    
    # global variable name
    name = "Rahul"
    
    # call function
    add_last_name("Singh")

    Output

    File "main.py", line 13, in <module>
    add_last_name("Singh")
    File "main.py", line 4, in add_last_name
    name = name + lname
    UnboundLocalError: local variable 'name' referenced before assignment

    Break the code

    In the above example, we are getting the error because we are trying to create a new local variable name and accessing the global variable name value using the statement name = name + lname at line 4.

    When Python executes that statement, it gets confused between the local and global variables and treats both variables as local variables. By that time, Python does not find the value of the right hand name so it throws the error.

    Solution 1

    The solution for this example is very simple. Although we can access the value of a global variable inside a function, we can not alter it. In case you want to access the global variable and change its value, you can use the Python global keyword.

    Solution

    # function
    def add_last_name(lname):
        # access the global name variable
        global name
        # alter the global name variable
        name = name +" "+ lname
    
    # global variable name
    name = "Rahul"
    
    # call function
    add_last_name("Singh")
    
    print(name)

    Output

    Rahul Singh
    Onces we have accessed the gloable variable inside a function wihtout using global keyword, we can not create a new local variable by the same name.

    Reason 2

    Another common reason why we receive this error is when we create a local variable inside a Python if..else conditional statement, and it never gets initialized because the condition was False.

    Example

    # function
    def is_adult(age):
        if age>=18:
            # define adult that that never execute
            adult= True
    
        print(adult)
    
    # global variable name
    age =12
    
    # call function
    is_adult(age)

    Output

    Traceback (most recent call last):
    File "main.py", line 16, in <module>
     is_adult(age)
    File "main.py", line 7, in is_adult
    print(adult)
    UnboundLocalError: local variable 'adult' referenced before assignment

    Break the code

    The age value is 12 , which means the statement inside the if age>18: condition block did not execute. That leads to no assignment value to the adult variable, but at the backend, when Python executes its program line by line and initializes the variable adult but did not assign any value to it. So when we accessed the variable at line 7, it threw the error.

    Solution 2

    When we access a variable inside a local scope, we need to make sure that we initialize and assign a value to it before accessing it. If we are creating a new variable inside the if statement, we also need to make sure that there must be an else statement that also assigns the value to the variable if the condition is False.

    In our above example, the value of adult only get assigned when the condition is true, so all we need to do is create an else statement that also assigns a value to the variable adult when the condition is False.

    solution

    # function
    def is_adult(age):
        if age>18:
            # if the condition is true
            adult= True
        else:
            # if the condition is false
            adult =False
        print(adult)
    
    # global variable name
    age =12
    
    # call function
    is_adult(age)

    Output

    Flase

    Conclusion

    In this Python tutorial, we discussed one of the most common Python functions error local variable referenced before assignment . The error raises when we try to access a local variable before its assignment inside a function. We often encounter this error when we try to access a global variable with the same name as the local variable or create a local variable inside a function that never gets assigned.

    If you are still getting this error in your Python program, please comment down your code and query in the comment section, and we will try to debug it for you.

    People are also reading:

    Leave a Comment on this Post

    0 Comments