Jed Rembold & Fred Agbo
February 14, 2025
Which of the below images would be produced by the following code?
gw = GWindow(200,200)
for c in range(0,10):
for r in range(0,10):
rect = GRect(20*c,20*r,20,20)
if (r+c) % 2 != 0:
rect.set_filled(True)
gw.add(rect)
A function is just a sequence of statements that have been collected together and given a name
Some reminders about vocabulary:
Syntax:
def function_name( parameter_list ):
function_body
Functions that return a Boolean value are called predicate functions
def is_divisible_by(x, y):
return x % y == 0
Once you have defined a predicate function, you can use it in any conditional expression!
for i in range(1, 100):
if is_divisible_by(i, 7):
print(i)
Don’t complicate your code for no reason!
Work directly with the boolean values when possible
Try not to code patterns like the following:
def is_divisible_by(x, y):
if x % y == 0:
return True
else:
return False
for i in range(1, 100):
if is_divisible_by(i,7) == True:
print(i)
So far we have used a positional way to assign arguments to parameters
>>> def func( first, second, third ):
print( first, second, third )
>>> func(1,2,3)
1 2 3
>>> func(2,6,4)
2 6 4
Arguments may also be specified by a keyword, in which the caller precedes the argument with a parameter name and equals sign
Always stores the argument value in the specified parameter
>>> def func( first, second, third ):
print( first, second, third )
>>> func(third=4, first=2, second=6)
2 6 4
Keyword arguments can appear in any order
All keyword arguments must come after any positional arguments!
def introduction(name='Jed', age=35):
print(f'My name is {name} and I am {age}')
Different cases of calling the introduction function:
>>> introduction()
My name is Jed and I am 35
>>> introduction('Bob', 25)
My name is Bob and I am 25
>>> introduction('Larry')
My name is Larry and I am 35
>>> introduction(age=68)
My name is Jed and I am 68
x
and z
are
printed, what will their value be?def Vegas(x):
y = 2
for i in range(5):
x += y
return x
x = 3
z = Vegas(x)
print('z =', z)
print('x =', x)
def mystery (x):
def enigma (s, t):
t -= 2
return s [::6] + s[t]
y = len(x)
z = x[1 - y]
z += enigma (x, y)
z += enigma (x, y - 2)
print(z)
if __name__ == '__main__':
print(mystery ("abcdefgh"))
def make_filled_circ(x_cent, y_cent, radius, color='black'):
circle = GOval(x_cent-radius, y_cent-radius, 2*radius, 2*radius)
circle.set_color(color)
circle.set_filled(True)
return circle
return
, compute the return value and
substitute that value in place of the function callabs
,
str
, print
,
etc.def func1(x,y):
return z + func2(x,y)
def func2(x,y):
def func3(x):
return (y + x) ** 2
z = x - func3(y)
return z - y
z = 1
print(func1(2,z))
In Python, assigning any value to a variable means that the variable is assumed to be local
Can lead to issues though:
def increment():
x = x + 1
x = 0
increment()
The variable x in the fuction is local within that scope, and another global x with value 0 can cause issues