Scope
Hey guys, welcome back to the Python basics tutorial! Today you'll learn about the scope of variables and functions.
What's scope?
Scope is the area which a variable/function can access. For example, you have probably seen that if you do this:
def myfunc(x, y):
z = x + y
print(z)
It raises a NameError
, saying that z
is not defined. Why? z
IS a regular variable after all!
That's because the variable z
was defined inside myfunc
, and therefore only available within it. Its scope is limited to myfunc
. Same for functions too.
Local and Global
As you just saw above, a variable/function which is limited within a specific range is called a local variable. And variables defined outside of a code block is global, meaning that it can be accessed from any place.
def hello(name):
reply = 'Hello ' + name # Local variable
name = 'John' # Global
You can convert a local variable to a global one too, though you should generally avoid it.
def hello(name):
reply = 'Hello ' + name
hello('John')
print(name) # Raises NameError
# But, this does not:
def hello(name):
global reply
reply = 'Hello ' + name
hello('Mike')
print(reply) # Prints 'Mike'
In most cases you'll want to return from the function, not make the variables global.
Hopefully this will solve some of your issues with scope, and you'll see some more tricks in the next few chapters.
Last updated
Was this helpful?