Coding in Python 12 - Local vs Global Variables

From LearnLinux.tv Wiki
Jump to navigationJump to search

Overview

In video number 12 of the Coding in Python series, we explore the difference between local and global variables.

Relevant Links
Original Video


Commands Used in this Video

An example of what not to do (this will fail!)

#!/usr/bin/env python3


def my_function():
    """ This is just a sample function.
    We're going to declare a variable in this function.
    """"
    message = "Hello everyone!"
    print(message)

my_function()

print(message)

Global variable example (fixes the problem from the previous code, notice the "global" line)

#!/usr/bin/env python3


def my_function():
    """ This is just a sample function.
    We're going to declare a variable in this function.
    """"
    global message
    message = "Hello everyone!"
    print(message)

my_function()

print(message)

Function (with a doc string)

#!/usr/bin/env python3

def my_function():
    """This is a doc string.
    This can be useful.
    It's pretty cool, isn't it?
    """
    mynum1 = 10
    mynum2 = 30
    print(mynum1 + mynum2)

my_function()
my_function()