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.

pressure = 103.9

def adjust(t):
    temperature = t * 1.43 / pressure
    return temperature
print('adjusted:', adjust(0.9))
print('temperature after call:', temperature)
adjusted: 0.01238691049085659
Traceback (most recent call last):
  File "/Users/swcarpentry/foo.py", line 8, in <module>
    print('temperature after call:', temperature)
NameError: name 'temperature' is not defined

Local and Global Variable Use

Trace the value of each variable in this program during execution.

limit = 100

def clip(value):
   value = max(0.0, value) 
   value = min(value, limit)
   return value

value = -22.5
clipped = clip(value)

Which of the following is true?

a. limit = 100    value = -22.5  clipped = 0.0
b. limit = 0.0    value = 0.0    clipped = 0.0
c. limit = -22.5  value = -22.5  clipped = 100
d. limit = 100    value = 0.0    clipped = -22.5

Solution

a.

Reading Error Messages

Read the traceback below, and identify the following:

  1. How many ‘levels’ does this traceback have (i.e., how many scopes does it pass through)?
  2. What is the file name where the error occurred?
  3. What is the function name where the error occurred?
  4. On which line number in this function did the error occur?
  5. What is the type of error?
  6. What is the error message?
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-e4c4cbafeeb5> in <module>()
      1 import errors_02
----> 2 errors_02.print_friday_message()

/Users/ghopper/thesis/code/errors_02.py in print_friday_message()
     13
     14 def print_friday_message():
---> 15     print_message("Friday")

/Users/ghopper/thesis/code/errors_02.py in print_message(day)
      9         "sunday": "Aw, the weekend is almost over."
     10     }
---> 11     print(messages[day])
     12
     13

KeyError: 'Friday'

Solution

  1. 3
  2. errors_02.py
  3. print_message()
  4. 11
  5. KeyError
  6. KeyError: ‘Friday’

Key Points