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
18,939 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, 2020 in Python by Ibrahim Nezar
• 140 points
1,940 views
0 votes
3 answers
0 votes
2 answers
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,423 views
0 votes
1 answer
+5 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,790 points
4,043 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,720 points
1,906 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,460 points
1,157 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP