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 in Python by Ashish
1,522 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 by Greg

Related Questions In Python

0 votes
1 answer

Python UnboundLocalError error while executing script

The reason for this error is that ...READ MORE

answered Jan 22 in Python by Omkar
• 68,480 points
87 views
+2 votes
2 answers

Error while printing hello world in python.

You must be trying this command in ...READ MORE

answered Mar 31, 2018 in Python by GandalfDwhite
• 1,320 points
146 views
0 votes
2 answers

Indentation Error in Python

Use tabs instead of spaces. This is ...READ MORE

answered Feb 14 in Python by Shashank
• 1,350 points
122 views
0 votes
1 answer

How to use string.replace() in python 3.x

replace() is a method of <class 'str'> ...READ MORE

answered Aug 3, 2018 in Python by Priyaj
• 57,300 points
110 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 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 417 views
+4 votes
6 answers
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,720 points
224 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 ariaholic
• 7,340 points
61 views