Wednesday 10/11¶
Scope and Modules¶
Scope¶
What will be printed by the following python script?
name = "Herman"
def print_greeting(alias):
name = alias
print(name)
def print_hello():
print("Hello", name)
print_greeting("Mary")
print_hello()
print(name)
How about this one?
names = ["Herman", "Alice"]
def print_greeting(alias):
names.append(alias)
print(names[0])
def print_hello():
print("Hello", names[-1])
print_greeting("Mary")
print_greeting("Jane")
print_hello()
print(names)
Variables assigned inside function have local scope, variables declared outside of any function have global scope.
Modules¶
Consider the following two python files:
geometry.py
"""Useful geometry functions."""
origin = (0, 0)
def distance(point_a, point_b):
return ( (point_a[0] - point_b[0])**2
+ (point_a[1] - point_b[1])**2)**.5
print("Let's calculate the distance from the origin!")
x = float(input("x: "))
y = float(input("y: "))
print(distance(origin, (x, y)))
finder.py
import geometry
def furthest(start, points):
largest_distance = -1
index_largest = -1
for i, point in enumerate(points):
dist = geometry.distance(start, point)
if dist > largest_distance:
largest_distance = dist
index_largest = i
return index_largest
locations = [(10, 10),
(1, 1),
(100, 100)]
print(furthest(geometry.origin, locations))
What will happen when we run finder.py
?
Quiz Instructions¶
- Log into the desktop as
student
with no password. - Log into Canvas.
- Wait until the instructor says to start before accessing Part 1.
- The quiz can be found in the "Modules" section of Canvas.
- The entire quiz has a 25 minute time limit.
- Part 1 (Conceptual):
- You may not use Thonny (or any other resources) for Part 1.
- Part 2 (Coding):
- You have unlimited submissions.
- You do NOT need to provide docstrings.
- The autograder will NOT check for PEP8 violations (though you should still use good style.)
- You must use Thonny as your editor.
- You may not access any external web pages or other resources.