Open main menu

CDOT Wiki β

Changes

OPS435 Python Lab 7

1,464 bytes added, 11:22, 3 December 2017
INVESTIGATION 2: Scope
= INVESTIGATION 2: Scope =
 
Scope means where in the code a variable is accessible from, and how long that variable exists.
 
In this lab we will look at the types of scope you're most likely to run into and which are most likely to cause trouble for you. We will not be explicitly looking at class scope, nested functions, built-in variables, constants, and mutability.
 
== Local Scope ==
 
In Python any variable that is created inside a function has local scope. That means that it is accessible by any code inside that function, and is not accessible by any code outside the function. In other languages this concept is related to '''block''' scope but that does not exist in python. Every block inside a function has the same scope.
 
Try the following code. Have each in a separate Python file, iPython would cause way too many complications for this lab.
 
'''lab7b.py''' - local scope:
<source lang="python">
#!/usr/bin/env python3
 
def function1():
# This variable 'a' is completely unrelated to the variable 'a' in function2():
a = 'Andrew 1'
print(a)
 
def function2():
# This variable 'a' is completely unrelated to the variable 'a' in function1():
a = 'Andrew 2'
print(a)
 
# Note that you cannot make any of the following print() functions work because neither of
# the variables '''a''' exist in this scope (outside the function where they were defined):
print(a)
function1()
print(a)
function2()
print(a)
</source>
 
== Global Scope ==
 
 
== Object Scope ==
= LAB 7 SIGN-OFF (SHOW INSTRUCTOR) =