Variable Scope

Overview

Teaching: 10 min
Exercises: 10 min
Questions
  • How do function calls actually work?

  • How can I determine where errors occurred?

Objectives
  • Identify local and global variables.

  • Identify parameters as local variables.

  • Read a traceback and determine the file, function, and line number on which the error occurred, the type of error, and the error message.

The scope of a variable is the part of a program that can ‘see’ that variable.

access_url = 'http://memegenerator.net/'

def extract_domain(uri):
    domain = uri[7:-1]
    return domain
print('domain is:', extract_domain('http://metafilter.com/'))
print('url after call:', domain)
domain is: metafilter.com
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-9860e4547781> in <module>()
      1 print('domain is:', extract_domain('http://metafilter.com/'))
----> 2 print('url after call:', domain)
      3 

NameError: name 'domain' is not defined

Key Points

  • The scope of a variable is the part of a program that can ‘see’ that variable.