Variable Visibility and Scope in Python Functions, Study notes of Computer Science

Lecture notes from cpsc 121 (fall 2012) discussing the concept of variable visibility and scope in python functions. It explains how variables defined inside a function are local and only exist within the function, and how function parameters are treated as local variables. It also covers the concept of global variables and the implications of reassigning global variables within a function.

Typology: Study notes

2012/2013

Uploaded on 09/28/2013

noob
noob 🇮🇳

4.4

(25)

105 documents

1 / 5

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Lecture Notes CPSC 121 (Fall 2012)
Today ...
Functions (cont.)
Homework
HW 2 due
HW 3 out
S. Bowers 1 of 5
pf3
pf4
pf5

Partial preview of the text

Download Variable Visibility and Scope in Python Functions and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Functions (cont.)

Homework

  • HW 2 due
  • HW 3 out

Function Variable Visibility

Variables defined inside a function are local to the function

  • i.e., they only exist inside the function

For example

def add_and_print(x, y): sum = x + y print(sum)

Q: What does this function do?

arg1 = 3 arg2 = 4 add_and_print(arg1, arg2) 7

When a function terminates, local variables are destroyed

  • If we try to print them, we’ll get an error ...

print(sum) NameError: name ’sum’ is not defined

The same is true for function parameters!

  • e.g., trying to print x gives the same error

What about now?

sum = 10 x = 5 y = 4 z = 1 def add_and_print(x, y): sum = x + y + z print(sum) add_and_print(3, 4) print(sum, x, y, z, sep=", ")

Q: What is printed by the add and print function call?

8

Q: What is printed by the last statement?

10, 5, 4, 1

Equivalent to:

sum = 10 x = 5 y = 4 z = 1 def add_and_print(x0, y0): sum = x0 + y0 + z print(sum) add_and_print(3, 4) print(sum, x, y, z, sep=", ")

  • here z is a “global variable” ... it is defined outside of the function
  • sum, x, and y are also global variables

What about this one?

sum = 10 x = 5 y = 4 z = 1 def add_and_print(x, y): sum = x + y + z print(sum) z = 2 add_and_print(3, 4) print(sum, x, y, z, sep=", ")

  • This confuses Python!

UnboundLocalError: local variable ’z’ referenced before assignment

  • Python thinks z is local (because of the assignment) ...
  • But then is used before it is assigned a value