Variable ScopeĀ¶


  • ā€œ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.ā€ keypoints:

  • ā€œThe scope of a variable is the part of a program that can ā€˜seeā€™ that variable.ā€


The scope of a variable is the part of a program that can ā€˜seeā€™ that variable.Ā¶

  • There are only so many sensible names for variables.

  • People using functions shouldnā€™t have to worry about what variable names the author of the function used.

  • People writing functions shouldnā€™t have to worry about what variable names the functionā€™s caller uses.

  • The part of a program in which a variable is visible is called its scope.

pressure = 103.9

def adjust(t):
    temperature = t * 1.43 / pressure
    return temperature
  • pressure is a global variable.

    • Defined outside any particular function.

    • Visible everywhere.

  • t and temperature are local variables in adjust.

    • Defined in the function.

    • Not visible in the main program.

    • Remember: a function parameter is a variable that is automatically assigned a value when the function is called.

print('adjusted:', adjust(0.9))
print('temperature after call:', temperature)
adjusted: 0.01238691049085659
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-e73c01f89950> in <module>
      1 print('adjusted:', adjust(0.9))
----> 2 print('temperature after call:', temperature)

NameError: name 'temperature' is not defined