Variable Scope
Introduction
A variable's scope is the part of a program where the variable may be accessed. A variable is only visible (can be used and recognized) by statements within the variable's scope.
Local Variables
One of the very IMPORTANT things about using functions is to understand two terms - Local Variables and Global Variables. With local variables - these are created inside a function and CANNOT be accessed by statements that are outside of the function. Different functions CAN have the same variable names because functions cannot see each other's local variables.
Anytime you assign a value to a variable inside of a function you have created the local variable.
Global Variables
Global variables are accessible to ALL the function listed in a program. When you begin a program - BEFORE defining the main() program, you can create and assign your Global variables. These are ALWAYS done before the definition of any of your programs or functions. Then EACH part of the program - main and functions can use the Global variable as defined.
HOWEVER - these Global variables can be dangerous to use. It is recommended wherever possible to only use local variables. However - you can create a Global constant variable whose value doesn't change through the program and functions. This will avoid any other other problems with global variables.
Exercises
The examples below are written in "script" mode.
Example: variable_scope_1.py
def print_num():
print("Yeehaw! num is visible in this scope, its value is: " + str(num))
num = 25
print_num()
- Variables defined before function call are visible within the function scope too
Results:
Yeehaw! num is visible in this scope, its value is: 25
What happens when a variable declared within a block is used outside of it?
Example: variable_scope_2.py
def square_of_num(num):
sqr_num = num * num
square_of_num(5)
print("5 * 5 = {}".format(sqr_num))
- Here, sqr_num is declared inside square_of_num function and not accessible outside the block
Results:
Traceback (most recent call last):
File "./variable_scope_2.py", line 7, in
print("5 * 5 = {}".format(sqr_num))
NameError: name 'sqr_num' is not defined
One way to overcome this is to use the global keyword to create a global variable.
Example: variable_scope_3.py
def square_of_num(num):
global sqr_num
sqr_num = num * num
square_of_num(5)
print("5 * 5 = {}".format(sqr_num))
- Now, we can access sqr_num even outside the function definition.
Results:
5 * 5 = 25
If a variable name is same outside and within function definition, the one inside the function will stay local to the block and not affect the one outside of it.
Example: variable_scope_4.py
sqr_num = 4
def square_of_num(num):
sqr_num = num * num
print("5 * 5 = {}".format(sqr_num))
square_of_num(5)
print("Whoops! sqr_num is still {}!".format(sqr_num))
- Note that using global sqr_num will affect the sqr_num variable outside the function
Results:
5 * 5 = 25
Whoops! sqr_num is still 4!