Wednesday, June 22, 2022

Python - Global variables

x = "awesome"

def myfunc():
    x = "cool"
    print("Python is " + x) # Output: Python is cool

myfunc()

print("Python is " + x) # Output: Python is awesome

def myfunc2():
    # Notice here we turn what would normally have been a local variable 'y' into a global variable
    # This means it is accessible outside this function
    global y
    y = "fantastic"
    print ("Python is " + y)    # Output: Python is fantastic

myfunc2()

print ("Python is " + y)    # Output: Python is fantastic