Global and Local Variables Python Tutorial




Welcome to another python 3 basics tutorial, in this tutorial we're going to now discuss the concept of global and local variables.

When users begin using functions, they can quickly become confused when it comes to global and local variables... getting a the dreaded variable is not defined even when they clearly see that it is... or so they think.

These terms of global and local correspond to a variable's reach within a script or program. A global variable is one that can be accessed anywhere. A local variable is the opposite, it can only be accessed within its frame. The difference is that global variables can be accessed locally, but not modified locally inherently.

A local variable cannot be accessed globally, inherently. Now, dont worry about committing that to memory right now, I think it makes a lot more sense when you just see and do it, so let's do that.

# this variable has no parent function, but is actually NOT a global variable.
# it just so happens that it is committed to memory before the function is called
# so we are able to iterate, or call it out, but we cannot do much else.

x = 6

def example():
    print(x)
    # z, however, is a local variable.  
    z = 5
    # this works
    print(z)
    
example()
# this does not, which often confuses people, because z has been defined
# and successfully even was called... the problem is that it is a local
# variable only, and you are attempting to access it globally.

print(z)

Here, we can see that we are able to access the x variable. We then defined and print out the z variable. We can then call the function, and all seems well. When we go to reference the z variable however, we have trouble. The z variable is local to the example function.

Let's look at another example:

x = 6

def example2():
    # works
    print(x)
    print(x+5)

    # but then what happens when we go to modify:
    x+=6

    # so there we attempted to take the x var and add 6 to it... but now
    # we are told that we cannot, as we're referencing the variable before
    # its assignment.

Here, again, we are able to reference x, we are even able to print x+6... but we are not allowed to modify x.

What if we'd like to modify x? Well, then we need to use global!

x = 6

def example3():
    # what we do here is defined x as a global variable. 
    global x
    # now we can:
    print(x)
    x+=5
    print(x)

Now we're cooking! The problem here is that some people do not like the idea at all of using global variables. How do we get around using them and referencing them locally?

x = 6

def example4():
    globx = x
    # now we can:
    print(globx)
    globx+=5
    print(globx)

We are able to do the above, by assigning the value that we can reference to a local variable, then doing what we want with it from there.

Another choice you might have, as suggested by one of my viewers is the following:

x = 6
def example(x):
 
    print(x)
    x+=5
    print(x)
    return x
 
x = example(x)
print(x)

In the above example, we have the function modifying x. It may appear somewhat confusing since x is being used in multiple locations, so maybe a more clear example is something like:

x = 6
def example(modify):
 
    print(modify)
    modify+=5
    print(modify)
    return modify
 
x = example(x)
print(x)

So, you can better visualize this function as a "modification" function, where it modifies the variable you pass through. Besides the definition of this function, you only need to reassign the variable you want to change as the function with that variable as the parameter.

The next tutorial:






  • Python Introduction
  • Print Function and Strings
  • Math with Python
  • Variables Python Tutorial
  • While Loop Python Tutorial
  • For Loop Python Tutorial
  • If Statement Python Tutorial
  • If Else Python Tutorial
  • If Elif Else Python Tutorial
  • Functions Python Tutorial
  • Function Parameters Python Tutorial
  • Function Parameter Defaults Python Tutorial
  • Global and Local Variables Python Tutorial
  • Installing Modules Python Tutorial
  • How to download and install Python Packages and Modules with Pip
  • Common Errors Python Tutorial
  • Writing to a File Python Tutorial
  • Appending Files Python Tutorial
  • Reading from Files Python Tutorial
  • Classes Python Tutorial
  • Frequently asked Questions Python Tutorial
  • Getting User Input Python Tutorial
  • Statistics Module Python Tutorial
  • Module import Syntax Python Tutorial
  • Making your own Modules Python Tutorial
  • Python Lists vs Tuples
  • List Manipulation Python Tutorial
  • Multi-dimensional lists Python Tutorial
  • Reading CSV files in Python
  • Try and Except Error handling Python Tutorial
  • Multi-Line printing Python Tutorial
  • Python dictionaries
  • Built in functions Python Tutorial
  • OS Module Python Tutorial
  • SYS module Python Tutorial
  • Python urllib tutorial for Accessing the Internet
  • Regular Expressions with re Python Tutorial
  • How to Parse a Website with regex and urllib Python Tutorial
  • Tkinter intro
  • Tkinter buttons
  • Tkinter event handling
  • Tkinter menu bar
  • Tkinter images, text, and conclusion
  • Threading module
  • CX_Freeze Python Tutorial
  • The Subprocess Module Python Tutorial
  • Matplotlib Crash Course Python Tutorial
  • Python ftplib Tutorial
  • Sockets with Python Intro
  • Simple Port Scanner with Sockets
  • Threaded Port Scanner
  • Binding and Listening with Sockets
  • Client Server System with Sockets
  • Python 2to3 for Converting Python 2 scripts to Python 3
  • Python Pickle Module for saving Objects by serialization
  • Eval Module with Python Tutorial
  • Exec with Python Tutorial