This Global Variables 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 belongs to that function. The global statement is how that function assigns to a name defined outside.
Reading a global needs no keyword. Writing one does. Returning a new value is usually easier to follow than a global write.
Example 1: Start here
Without global, seats += 1 inside book creates an error, because the name is treated as local before it exists.
seats = 0 # a whole number
def book(): # define the function; it runs when you call it
global seats # assign to the name outside this function
seats += 1 # update the stored value
book() # call the function
print(seats)
Example 2: Read an outer name
The function can read city without a global line.
city = "Chennai" # text
def show(): # define the function; it runs when you call it
print(city)
show() # call the function
Example 3: Assign inside with global
global is required only when the function assigns to the outer name.
count = 0 # a whole number
def add_one(): # define the function; it runs when you call it
global count # assign to the name outside this function
count = count + 1 # add, then store the new number
add_one() # call the function
print(count)
Example 4: Prefer a return value
Returning a new value is usually clearer than changing a global.
def add_one(count): # define the function; it runs when you call it
return count + 1 # send this value back to the caller
print(add_one(0))
