Exercises for Lesson 5

Back to Lesson 5

Exercise 1: Refactoring code to use functions

The following code is…a bit repetitive. Find repeated chunks and rewrite them to use functions instead. The output when you run the program should still be the same, and it may not even be shorter, but it should be simpler to read. Don’t forget to add a main function, too!

x = 10
y = 12
print(x + y)
x = 15
y = 30
print(x + y)
x = 83
y = 11
print(x + y)
a = 4
print("The remainder when dividing", a, "by 2 is", a % 2)
a = 7
print("The remainder when dividing", a, "by 2 is", a % 2)
a = 15
print("The remainder when dividing", a, "by 2 is", a % 2)

Exercise 2: Drawing a shape

Adapt our simple code snippet to draw a triangle into a function that takes in a list of Point objects, a color name, and a GraphWin object and draws a triangle in the window. The function signature and main are given for you. Also, the docstring (the stuff in triple quotes) helps users of your function learn about what it does and how to use it.

from graphics import *

def drawTriangle(pointList, colorName, win):
    """
    Draws a triangle in the given window.

    pointList: the Point objects that give triangle bounds (a list)
    colorName: the color (a string)
    win: the window in which to draw (a GraphWin)
    """
    # TODO

def main():
    win = GraphWin("Triangle!")

    p1 = win.getMouse()
    p1.draw(win)
    p2 = win.getMouse()
    p2.draw(win)
    p3 = win.getMouse()
    p3.draw(win)

    points = [p1, p2, p3] # the square brackets mean it's a list
    drawTriangle(points, "thistle", win)

    win.getMouse()

main()

Back to Lesson 5

Exercise 3: Creating and drawing shapes

Modify your function from above to not only draw the triangle, but also return it. The updated signature, docstring, and main are given to you.

from graphics import *

def drawTriangle(pointList, colorName, win):
    """
    Draws a triangle in the given window.

    pointList: the Point objects that give triangle bounds (a list)
    colorName: the color (a string)
    win: the window in which to draw (a GraphWin)

    returns: the created triangle object (a Polygon)
    """
    # TODO: copy your previous code, but now also return

def main():
    win = GraphWin("Triangle!", 300, 300)

    p1 = win.getMouse()
    p1.draw(win)
    p2 = win.getMouse()
    p2.draw(win)
    p3 = win.getMouse()
    p3.draw(win)

    points = [p1, p2, p3]
    triangle = drawTriangle(points, "blue", win) # different!

    # Make a copy of the triangle (not an alias!)
    triangleCopy = triangle # bug!  use .clone() instead
    triangleCopy.setFill("yellow")
    triangleCopy.move(100, 0) # move 100 to the right
    triangleCopy.draw(win)

    win.getMouse()

main()

Back to Lesson 5

Exercise 4: Values and side effects

Part a: Prediction

Consider the following two functions:

def addTen(x):
    return x + 10

def printSum(a, b):
    print(a + b)

For each function, what is its value? What is its side effect?

Part b: Try it out!

Now type up this code in a small Python program, with this main function:

def main():
    print("Calling the two functions.")
    print("Any side effects resulting in print statements will happen now.")
    
    res1 = addTen(4)
    res2 = printSum(3, 7)

    print("Done calling the functions!")
    print() # add a blank line

    print("The value of addTen(4) is:", res1)
    print("The value of printSume(a, b) is:", printSum)

How did your predictions compare to what you saw? Make sure to ask any questions you have!

Back to Lesson 5

Exercise 5: Writing functions that return values

Part a: Summing values

Write two functions:

  • sumN(n) returns the sum of the first n natural numbers, i.e., 1+2+3+…+n
  • sumNSquares(n) returns the sum of the squares of the first n natural numbers

Here are their signatures:

def sumN(n):
    """
    Computes the sum of the first n natural numbers.

    n: the number of ints to sum (an int)

    returns: the sum of numbers 1-n (an int)
    """
    # TODO

def sumNSquares(n):
    """
    Computes the sum of the squares of the first n natural numbers.

    n: the number of ints' squares to sum (an int)

    returns: the sum of the squares of 1-n (an int)
    """
    # TODO

Now, write a program that asks the user for a value of n, and uses these functions to print out the sum of the first n natural numbers and the sum of their squares.

def main():
    n = # TODO

    # TODO

Question: does the code still run even if you name your variable something else in main?

Back to Lesson 5