- We will see how to use stack diagrams to trace through a program. First,
open oops_squareFunc.py. Read the program and run it. Why did
the program not work?
A useful website for visualizing code is Python Tutor. Use this tool to see how we represent the execution of a program
as a stack diagram. Use this link to load oops_squareFunc.py into the python tutor. Step through the function.
- Let us do a trace of a program using stack diagrams. Work through
this program on pen and paper and attempt to maintain a stack diagram.
The dir() function returns a list of variables in scope
1 def main():
2 a = 10
3 b = 55
4 print("in function...dir() = "+str(dir()))
5 result = absval(a,b)
6 print("The absolute value of %d - %d is %d" % (a,b, result) )
7
8 def absval(x,y):
9 print("in function... dir() = "+str(dir()))
10 if x > y:
11 z = x - y
12 else:
13 z = y - x
14 #
15 #Pause program and show full stack diagram
16 #
17 return z
18
19 main()
What is the final output?
- Run squareList.py through Python Tutor. Why do we get
different behavior with this program than with oops_squareFunc.py?
- Draw a stack diagram in the following program. Note that there may
be an error that prevents this program from running. Can you find it?:
def main():
list_x = [7, 10]
size = len(list_x)
print(list_x[0])
size = some_function2(list_x)
print(size)
print(list_x[0])
def some_function2(list_nums)
list_nums.append(15)
list_nums[0] = 23
print(list_x)
print(size)
#Draw stack
return len(list_nums)
main()
- There were a few examples from last week that we did not get to cover. However,
they each demonstrate different ways to use functions. First, open w05-graphics/animate.py to see how we can create animated objects. We will learn about the sleep(x)
function, which causes the program to pause for x seconds.
- Next trace through w05-graphics/duplicate.py from last week. Why
does this program not do what we desire? How can we fix it?
- Open w05-graphics/biggest_circle_soln.py and read through the solution.
We will trace through this program to see how a stack diagram helps illustrate understand
our solution.
- In w05-graphics/lights.py, we will see another use of functions with graphics.
We will also seen an example of the None value and the use of checkKey() to
detect user feedback
- Lastly, in w06-functions/guess.py, we will practice more defense programming
against incorrect user input. In particular, we will learn about about exception handling.