Variable scope in Python

From Computer Science Wiki
This is basic programming knowledge [1]


Recall that a variable is a label for a location in memory. It can be used to hold a value. In statically typed languages, variables have predetermined types, and a variable can only be used to hold values of that type. In Python, we may reuse the same variable to store values of any type.

A variable is similar to the memory functionality found in most calculators, in that it holds one value which can be retrieved many times, and that storing a new value erases the old. A variable differs from a calculator’s memory in that one can have many variables storing different values, and that each variable is referred to by name. [2]

Example of variable scope in Python[edit]

# This is a global variable
a = 0

if a == 0:
    # This is still a global variable
    b = 1

def my_function(c):
    # this is a local variable
    d = 3

# Now we call the function, passing the value 7 as the first and only parameter

# a and b still exist

# c and d don't exist anymore -- these statements will give us name errors!


Remember or recognize from prior learning experiences.

Add labels to a diagram.