UnboundLocalError: local variable referenced before assignment in Python

Dung Do Tien Sep 01 2021 168

Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small assignment. I want to append an item to a list and print it out. Like this:

countries = ["Vietnam", "Laos", "USA"]

# Defined function help insert & print list countries
def buildCountries(s):
    if s.strip():
        countries = countries.append(s)
        
    for i in range(0,len(countries)):
        print(countries[i])

# Call function
buildCountries("UK")

But I get an exception UnboundLocalError: local variable 'countries' referenced before assignment when I run code above.

Traceback (most recent call last):
  File "main.py", line 10, in <module>
    buildCountries("Color")
  File "main.py", line 7, in buildCountries
    for i in range(0,len(countries)):
UnboundLocalError: local variable 'countries' referenced before assignment

And I am using Python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • A

    An Pham Truong Sep 01 2021

    Please change countries = countries.append(s) to countries.append(s) :

    countries = ["Vietnam", "Laos", "USA"]
    
    # Defined function help insert & print list countries
    def buildCountries(s):
        if s.strip():
            countries.append(s)
            
        for i in range(0,len(countries)):
            print(countries[i])
    
    # Call function
    buildCountries("UK")

    #Output

    Vietnam
    Laos
    USA
    UK
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close