Skip to main content

Global Variables

A variable created outside any function is called a global variable. All your code can use it, whether inside a function or not.

A variable created inside a function under that same name is a different thing: it is local and exists only for use within that function. The global one keeps its original value and stays untouched.

Use global variable

Here x is defined outside the function and read inside it:

Prompt
Create a global variable x with value "awesome", then define a function that prints "Python is " + x, and call the function.
Output: complete Python program

Local vs global

Here the function creates its own x, sharing a name with the global one:

Prompt
Create a global variable x = "awesome". Define a function that creates a local x = "fantastic" and prints it. Call the function, then print the global x to show it is unchanged.
Output: complete Python program

The global Keyword

A variable you create in a function is usually local, so nothing outside that function can use it. The global keyword changes that and lets you create a global variable from inside a function. You also need this keyword when a function has to change an existing global variable.

Create global inside function

With the global keyword, x belongs to the global scope:

Prompt
Use the global keyword inside a function to create a global variable x = "fantastic", call the function, then print "Python is " + x outside the function.
Output: complete Python program

Change global inside function

Inside a function, global lets you give an existing global variable a new value:

Prompt
Create a global variable x = "awesome". Use the global keyword inside a function to change x to "fantastic". Call the function, then print "Python is " + x to show it changed.
Output: complete Python program