Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

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

1 Answer

0 votes
by (25.1k points)

You are getting this error because of scoping issue. Basically you have defined variable in the local outer scope and are referencing it in method named foo. Do it like this. It will work fine:

x = 10

    def bar():

        print(x)

If you want to get a deeper understanding of python you can watch this youtube video: 

Browse Categories

...