Python basics
  • Introduction
  • Print function, strings, variables and development environment
  • Data types and operators in Python
  • Assignment 1
  • Getting user input and commenting
  • If/Elif/Else Conditions
  • Assignment 2
  • Data Structures
  • Loops
  • Assignment 3
  • Functions
  • Errors and Exceptions
  • Assignment 4
  • Object Oriented Programming
  • Manipulating files
  • Assignment 5
  • Modules
  • Installing packages
  • Scope
  • String formatting and List slicing
  • Ternary operators , *args and **kwargs
  • Guidelines for writing Pythonic Code
  • The End
Powered by GitBook
On this page
  • What's scope?
  • Local and Global

Was this helpful?

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.

In case you're wondering, yes, you can define functions inside a function definition too. Go try it out.

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.

PreviousInstalling packagesNextString formatting and List slicing

Last updated 6 years ago

Was this helpful?