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

0 votes

I have the following code:

x = 10

def foo():
x += 1

It gives me the following error:

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

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():

This should work fine

answered Jul 24, 2019 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, 2019 in Python by Omkar
• 68,940 points
+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
0 votes
2 answers

Indentation Error in Python

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

answered Feb 14, 2019 in Python by Shashank
• 1,370 points
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,530 points
0 votes
1 answer
+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 639 views
0 votes
0 answers
+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,750 points
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,350 points