Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Puffy wuff
Puffy wuff
9,573 Points

Python scope question

Why does this work:

def outer():
    x = 100
    def inner():
        print(x)
    inner()

outer()

But not this:

def outer():
    x = 100
    def inner():
        x += 10
        print(x)
    inner()

outer()

I don't understand why I can print x from the outer scope but not update it.

1 Answer

Steven Parker
Steven Parker
229,732 Points

The "print" is simply accessing the variable from the outer scope.

But when you make an assignment, Python takes that to mean that a new variable should be created in the current scope. But "+=" is a special kind of assignment that also accesses the current value, so it doesn't work with variables being created in the same statement.