This Python Scope lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A name assigned inside a function is local. It hides a global name with the same spelling and disappears when the function returns.
A function can read a global name. It should assign to that global only with the global statement, and only when shared state is the real goal.
Example 1: Start here
The outer batch stays Python. The assignment inside rename created a separate local name.
batch = "Python" # text
def rename(): # define the function; it runs when you call it
batch = "SQL" # text
return batch # send this value back to the caller
print(rename())
print(batch)
Example 2: A local name
city exists only while show is running.
def show(): # define the function; it runs when you call it
city = "Chennai" # text
print(city)
show() # call the function
Example 3: Read an outer name
A function may read a name from outside when it does not assign to it.
city = "Chennai" # text
def show(): # define the function; it runs when you call it
print(city)
show() # call the function
Example 4: Shadow the outer name
The assignment inside the function creates a local name. The outer city stays Chennai.
city = "Chennai" # text
def show(): # define the function; it runs when you call it
city = "Pune" # text
print(city)
show() # call the function
print(city)
