Variables – local, global, and parameter

Local

A local variable is only available to the module (or block of code) it is within.  That is its “scope”.

FUNCTION addThis(a, b)
total ← a + b
OUTPUT (total)
End addThis

FUNCTION Main
firstNum ← 5
secondNum ← 6
Call addThis(firstNum, secondNum)
End Main

The variable total is local to the module addThis, and cannot be seen by the Main module.

What would happen if you tried to use the total variable in the Main function?

Global

total ← 0

FUNCTION addThis(a, b)
total ← a + b
End addThis

FUNCTION Main
firstNum ← 5
secondNum ← 6
Call addThis(firstNum, secondNum)
OUTPUT total
End Main

Because the variable total has been created outside the Main and addThis function, it is now known as a global variable and is available to all modules. In Python, you must use the global keyword before modifying a global variable; otherwise, it treats it as a new local variable.

Python example:

global total = a + b

Parameter

When passing variables between functions, we use the term passing parameters. Parameters are placeholders for values. The value we pass is known as the argument.

FUNCTION addThis(a, b)
  total ← a + b
  OUTPUT (total)
End addThis

FUNCTION Main
  Call addThis(5, 6)
End Main

In the above example a and b are parameters, and 5, 6 are arguments.

Passing by reference or value

There are two ways to pass parameters, by value and by reference. In many programming languages, you can specify how; in Python, it’s predetermined. In Python, immutable objects (int, float, str) are passed by value and mutable objects (list, dict) by reference. Passing by value means making a copy in a new memory location for the receiving function.  Passing a parameter by reference is passing the memory location (the address) of the original variable.  What this means is if the variable passed by reference is changed the data in the original variable will change.

Pass by value

def try_to_change(number): 
    number = number + 100 
    print(f"Inside function: {number}") 

my_num = 5 
try_to_change(my_num) 
print(f"Outside function: {my_num}")

Output:
Inside function: 100
Outside function: 5

Pass by reference

def change_value(some_list): 
    some_list[0] = 100 
    print(f"Inside function: {some_list}") 

my_list = [5] 
change_value(my_list) 
print(f"After call: {my_list}")

Output:
Inside function: 100
After call: 100

Lifetime of variables

The term “lifetime” relates to how long and where a variable remains in existence.  For example once a global variable is created it remains available (whether it has anything in it or not) for the life of the program.

Scope of variables

The term “scope” refers to where variables are available to pieces of code.  The scope of a global variable in the whole program.  The scope of a local variable is within the block of code.