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
2 answers

Python UnboundLocalError error while executing script

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

answered 6 days ago in Python by Ibrahim Nezar
• 140 points
0 votes
1 answer

Command "python 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
• 21,860 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
+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 933 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,760 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