Scope in Python

There are two scopes: local and global.

Global Scope

A global scope allows you to use the variable anywhere in your program.

If your variable is outside a function, it has a global scope by default.

name = "Bob"

def printName():
  print("My name is " + name)

printName()
#My name is Bob

Notice the function could use the variable name and print My name is Bob.

Local Scope

When you declare a variable inside a function, it only exists inside that function and can’t be accessed from the outside.

def printName():
    name = "Bob"
    print("My name is " + name)

printName()
#My name is Bob

The variable name was declared inside the function, the output is the same as before.

But this will throw an error:

def printName():
    name = "Bob"
    print("My name is " + name)

print(name)

The output of the code above is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined

I tried to print the variable name from outside the function, but the scope of the variable was local and could not be found in a global scope.

Mixing Scopes

If you use the same name for variables inside and outside a function, the function will use the one inside its scope.

So when you call printName(), the name="Bob" is used to print the phrase.

On the other hand, when calling print() outside the function scope, name="Sarah" is used because of its global scope.

name = "Sarah"

def printName():
    name = "Bob"
    print("My name is " + name)

printName()
#My name is Bob
print(name)
#Sarah

Global Keyword

You can also use the global keyword.

It tells the Python interpreter that you want to use a global variable inside the scope of your function.

In this case, the phrase will use the value "Sarah" to print and when you change the variable name to "Bob", it will affect the global value and replace "Sarah", instead of creating a locally scoped variable.

name = "Sarah"

def printName():
    global name
    print("My name is " + name)
    name = "Bob"

printName()
#My name is Sarah
print(name)
#Bob