Python local variable referenced before assignment

Recently, while doing some Python programming, I got the error as “Python local variable referenced before assignment“. I will show you here when I receive the error and how to fix this.

Local variable referenced before assignment in Python

I was working on a simple function in Python to count the number of times a specific word appears in a list of words. Here’s the initial code I wrote:

def count_word_occurrences(word_list, target_word):
    count += 1
    for word in word_list:
        if word == target_word:
            count += 1
    return count

words = ["apple", "banana", "apple", "orange", "banana", "apple"]
print(count_word_occurrences(words, "apple"))

When I ran this code, I encountered the following error:

UnboundLocalError: local variable 'count' referenced before assignment

You can even see the exact error message in the screenshot below:

unboundlocalerror in python

The error message indicates that I tried to use the local variable count before it was assigned a value. In Python, any variable assigned a value inside a function is considered local to that function. Since count was not initialized before being incremented, Python raised an UnboundLocalError.

Solution

Here is the solution for the above error.

To fix this error, I needed to initialize the count variable before using it. Here’s the corrected version of the function:

def count_word_occurrences(word_list, target_word):
    count = 0  # Initialize the local variable
    for word in word_list:
        if word == target_word:
            count += 1
    return count

words = ["apple", "banana", "apple", "orange", "banana", "apple"]
print(count_word_occurrences(words, "apple"))

With this change, the count variable is initialized to 0 before the loop starts. This ensures that count has a value when it is incremented.

You can also see the output in the screenshot below; there is no error now.

unboundlocalerror local variable referenced before assignment python

Conclusion

The “local variable referenced before assignment” error is very common in Python due to its scoping rules. You need to ensure that variables are properly initialized before they are used; you can avoid this error. In this example, initializing the count variable solved the problem and allowed the function to execute correctly. In this tutorial, I have explained how to fix the error: “unboundlocalerror: local variable referenced before assignment in Python“.

You may also like the following tutorials:

Leave a Comment