Scope

Global Variables and Function Definitions

In the following program, will something be printed out, nothing, or an error… and why?

s = "hello"

def greet():
	print(s)

greet()

s is a global variable. It is accessible everywhere, including the function body.

Variables Declared Inside a Function

In the following program, will something be printed out, nothing, or an error… and why?

def greet():
	s = "hello"
	print(s)

print(s)

An error occurs because s is inaccessible outside of the function definition. s is local to the function that it was defined in.

Parameters

In the following program, will something be printed out, nothing, or an error… and why?

def greet(s):
	s = s + "!"
	print(s)

greet("foo")
print(s)

An error occurs. You can't access the parameters (by their name) that you passed in to the function from outside of the function. Parameters are local to their function.

Precedence

In the following program, will something be printed out, nothing, or an error… and why?

s = "hello"

def greet():
	s = "something else"
	print(s)


greet()
print(s)

Variables created within a function are local to that function. A function will use a local variable before global. In this case, it will use the local variable, s, instead of the global variable, s.

A Quick Explanation

Scope

A scope:

Global Scope

a, b = 25, "something"

def foo():
	print(a)
	print(b)

foo()

Local Scope

Variables that are defined in your function (one indentation level in), however, are only available within your function. They are local to that function. The example below won't work.

def foo():
	c = "bar"
	return c

print(c)

Local Scope Continued

Variables that are declared (created) within a function that have the same name as a global variable are totally different variables/values! They don't overwrite the outer, global variable (there's a way to do this, though). What will this print?

c = "on toast"
def foo():
	c = "grape jelly"
	print(c)

foo()
print(c)
grape jelly
on toast

Obligatory Python tutor version

A Little More Detail on That Last Point

What's (not) in a Name?

What is the exact error that you get if you try to use a variable, function or module that you haven't created yet?

NameError (Let's try it →)

Creating Names

Finding Names

If you use a variable name in a function, it will try to find that name in the following places in order:

And So?

What does the following code print out?

color = "blue"

def my_test_function():

	color = "orange"
	print(color)

my_test_function()
print(color)
orange
blue

Scope Summary