Jed Rembold & Fred Agbo
February 19, 2024
What would be the printed value of z at the end of the code to the right?
def f(x,y=0):
z = (x + 3) ** 2
return y + z
x = 1
z = x + f(y=x,x=2)
print(z)
()
. Including the parentheses is how you
call the function!import math
def evaluate_numbers(func):
print(func)
print(func(0))
print(func(2))
print(func(10))
A = evaluate_numbers
A(math.sqrt)
A(math.exp)
Consider the code to the right.
a
should
still exist when it is called!f2
must also keep track
of any local variables!b = 1
def f1(a):
print(a)
print(b)
def f2():
c = a + b
return c * 3
return f2
f2 = f1(10)
c = f2()
Consider the simple program below, where we’ve imported the basics and some of our helper functions
def draw_dots():
def click_action(event):
c = create_filled_rect(
event.get_x(), event.get_y(),
10,10, random_color())
gw.add(c)
gw = GWindow(500, 500)
gw.add_event_listener("click", click_action)
The click_action
function specifies
what to do when the mouse is clicked
gw
variable since it is in the enclosing function and thus in the
closure.The last line of our example function:
gw.add_event_listener("click", click_action)
tells the graphics window (gw
) to call
the click_action
function whenever a mouse
“click” occurs within the window.
When the user clicks the mouse, the graphics window, in essense,
calls the client back to let them know that a click has occured. Thus,
functions such as click_action
are known as
callback functions.
The parameter event
given to the
callback function is a special data structure called a mouse
event, which contains details about the specifics of the event that
triggered the action.
Name | Description |
---|---|
"click" |
The user clicks the mouse in the window |
"dblclick" |
The user double-clicks the mouse in the window |
"mousedown" |
The user presses the mouse button down |
"mouseup" |
The user releases the mouse button |
"mousemove" |
The user moves the mouse |
"drag" |
The user moves the mouse with the button down |
draw_dots()
function, you’ll notice that nothing happensgw.add_event_listener("click", click_action)
gw.add_event_listener("dblclick", dblclk_action)