Saturday, July 2, 2022

Python - Scope

# Variables are scoped
# It is only available from inside region it is created

def myfunc():
  print("Inside function")
  x = 300
  print(x)
  print("Exiting function")

# 300
myfunc()
# Next line fails
#print(x)

print("----")

# This sequence sets and displays a variable
# It then calls a function which *looks* like it messes with same variable
# But it shows that when we exit the function,
# the variable is intact

x = 7
# 7
print(x)

# From inside function, we will see 300
myfunc()

# 7
print(x)

print("=======")

# This shows that outer variables can be accessed from inner regions

# Define a global variable
outer = "my outer variable"

def myfunc():
    inner = "my inner variable"
    # Works as expected - we can see both
    print(outer)
    print(inner)
    
myfunc()

print("<><><><><><><>")

# Use global keyword to declare a variable global from within an inner region

def myfunc():
    global surprise
    surprise = 777

myfunc()
# the surprise variable is now treated as a global
# 777
print(surprise)

print("<><><><><><><>")

# We can change global variables from within an inner region
# by using the global keyword

x = 300

def myfunc():
  global x
  x = 200

myfunc()

# 200
print(x)