fbpx

Scope

What is scope?

To best understand the concept of scope as it relates to computer programming, it may be helpful to picture a neighborhood of houses:

If I wanted to share information with houses in this neighborhood, one way that I could so is by distributing flyers to each house. It’s important to note that the people in any given house will only know the information on the one flyer shared with them, not necessarily the information on the flyer given to their neighor.

However, if I wanted to share the same information to all the houses in the neighborhood, there may be an easier way to do so:

In this scenario, we would consider the information on the flyers to be local to any individual house, whereas the billboard would be considered global, as in anyone in the neighborhood has access to its information. This same idea is the foundation of what we refer to as local and global variables within Python.

Global Variables

Global variables in Python are variables that are able to be accessed anywhere within a file of code. It is typically best practice to declare your global variables at the top of a program, so that when you access them later in the code it knows what they refer to. 

Global variables that have been declared at the top of the code can be accessed within blocks of code such as functions, loops, and conditionals, as well as outside of any block. Note how in the code below, the global variable score is declared globally, meaning that the functions addPoint() and subtractPoint() and anywhere else in the code can access the variable.

				
					score = 0

def addPoint():
    score = score + 1

def subtractPoint():
    score = score - 1
    
addPoint()
addPoint()
subtractPoint()
    
print("Your current score is:", score)
				
			

Local Variables

Local variables, on the other hand, are variables that are declared within a block of code such as a function, loop, or conditional, and are thus only able to be accessed from within that block of code. Once the program exits that block of code, the local variable is destroyed. This also means that if you try to access a local variable outside of the block in which it was created, it will throw an error.

Note in the code below that the greeting variable is local to the introduction function. Once we exit that function, we no longer have access to its local data.

				
					my_name = "Jose"

def introduction(name):
    greeting = "Hi, my name is " + name
    return greeting
    
print(introduction(my_name)) # this is ok, because my_name is global

print(greeting) # this will throw an error, because greeting is local to the introduction function
				
			

Replit Practice

Loading...