Python error "UnboundLocalError: local variable 'x' referenced before assignment"

0 votes

I have the following code:

x = 10

def foo():
print(x)
x += 1

It gives me the following error:

UnboundLocalError: local variable 'x' referenced before assignment
Jul 24, 2019 in Python by Ashish
11,459 views

1 answer to this question.

0 votes

You get this error because when you make an assignment in scope, that variable becomes local to that scope and shadows any other variable with a similar name in the outer scope. 

x = 10
    def bar():
        print(x)

This should work fine

answered Jul 24, 2019 by Greg

Related Questions In Python

0 votes
2 answers

Python UnboundLocalError error while executing script

Inside your function when you say word=word+1, ...READ MORE

answered May 22 in Python by Ibrahim Nezar
• 140 points
401 views
0 votes
1 answer

Command "python setup.py egg_info" failed with error code 1 in C:\Users\Nadeem\AppData\Local\Temp\

Hi@akhtar, I think you are using previous version ...READ MORE

answered May 4 in Python by MD
• 66,500 points
13,417 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 1,465 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,095 views
0 votes
1 answer

When I create and remove files rapidly on windows using python I get WindowsError (Error 5)

Here's the short answer: disable any antivirus or ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,780 points
664 views
0 votes
1 answer

How does Python know whether a variable in the class is a method or a variable?

In python objects/variables are wrapped into methods ...READ MORE

answered Sep 18, 2018 in Python by aryya
• 7,380 points
135 views