Undestanding Variable Scope In Python

x = 10 def add(): 
x += 1 print(x)
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo UnboundLocalError: local variable 'x' referenced before assignment
x = 10 
def add():
print(x)
x = 10 
def increment():
global x
x += 1
print(x)
x = 10 
def increment():
nonlocal x
x += 1
print(x)

--

--

--

Coding, Reading,Python

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Afsalms

Afsalms

Coding, Reading,Python

More from Medium

Classes in Python

Python — Working with Datetime

Python — How To Read One File Line by Line

Why Python?