Python Tutorials

Overview

Python Global variables can be used both inside and outside of functions. While a variable created inside a function can only be used inside the function that created it.

Global Variable

Variables created outside a function are global. They can be used outside functions, and within a function.

x = "Hello World" #global variable
print(x)
x = " World" #global variable

def myfunc():
    print("Hello " + x)

myfunc()

Global vs. Local

If you create a variable inside a function, this variable will be local, and can only be used inside the function. The global variable will still be used outside the function.

x = " World" #global variable

def myfunc():
    x = " Universe" #local variable
    print("Hello " + x)

myfunc() #will use the local variable to print Hello Universe

print(x) #will use the global variable to print Hello World

Note

Even if the local variable has the same name as a global variable, the global variable will retain its original value when used outside the function using the local version.

The Global Keyword

To create a global variable inside a function, the global keyword is used.

x = " World" #global variable

def myfunc():
    global x
    x = " Universe" #global variable

myfunc()

print("Hello " + x) #will print Hello Universe

Note

Since the variable inside the function is global it can now be used, as changed, inside or outside the scope of the function.

The “x” variable has now been changed by the global keyword from ” World” to ” Universe” and the updated variable will be used globally (inside and outside functions) going forward unless changed again at a later point.


Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.