Lesson 12 +10 XP

Global Variables

A variable created outside any function is global. Global variables can be read by every function in the file.

Global scope


python
x = "awesome"

### global variable

def myfunc():
    print("Python is " + x)

### can read the global

myfunc()

### Python is awesome

Creating a variable inside a function

If you assign a variable inside a function, it is local to that function by default:


python
def myfunc():
    y = "fantastic"

### local
    print(y)

myfunc()

### fantastic
print(y)

### NameError: y is not defined

The global keyword

To change a global variable from inside a function, use global:


python
x = "awesome"

def myfunc():
    global x
    x = "fantastic"

myfunc()
print(x)

### fantastic

Without global, the function would just create a new local x and leave the global alone.

Read but not assign

A function can read a global without any keyword. Only when you want to assign to it do you need global.

TL;DR

  • Global variables live outside functions and are readable everywhere.
  • Local variables live inside a function only.
  • global lets a function modify a global variable.