# Scope of variables # The "scope" of a variable means: # "where is this variable and its value accessible" # Variables are used to store data throughout a program. # Creating a variable is commonly done like this: # # A string literal: # my_string = "This Is Text" # A scalar value: # my_number = 47 # A data structure (i.e. list, dict, tuple, set, etc.): # my_list = ["a", "j", "p", "y"] # An object/class instantiation: # my_object = Button("label", color=(25, 128, 199)) # # Each of the examples above are "variable assignments". # An assignment names a variable (such as 'my_number' above) # and sets a specific value to that named variable. # Variables assigned at the "top logical level" of the program # are in what we call the "global scope" or called "global variables". # This means that those variables and their values are available # within the main body of the program, from within functions, # and from within classes. # # More informationL https://www.w3schools.com/python/python_variables_global.asp # Better/More Complex: https://realpython.com/python-use-global-variable-in-function/ name = "Donkey" age = 44 streets = ["Brown Bark", "Pine Knot", "Thomas Jefferson"] def alter(): print(name) age = 3 streets[1] = "George Wythe" alter() print(name) print(age) print(streets) # This shows us several things: # 1) The variable "name" is available inside the alter() function # 2) The streets[] list is available # 3) and its elements can be changed within the alter() function # 4) The "age" variable assigned in the alter() function does not # effect the globally scoped variable "age" # # One of the key topics here is "mutability". This topic is quite # complex and involved. Here's a link where you can read more: # https://realpython.com/python-mutable-vs-immutable-types/ # # The TLDR of that page is: # 1) It's poor practice to try to change any global scope variables inside a function # 2) Variable types that are "mutable" (link above) can be altered in subroutines/functions # 3) Variable types that are "immutable" (link above) CANNOT be altered in subs/functions