Lab: Defining Functions

3 minute read

Exercise 1

Consider the following program that waits for the user to click twice and then tells them the distance between the two points they clicked on.

# Prints the distance between two mouse clicks
#
# Author:
#   Titus Klinge

from graphics import *
import math

def distance(p1, p2):
    # Returns the distance between the Point objects given
    diffx = p2.getX() - p1.getX()
    diffy = p2.getY() - p1.getY()
    return math.sqrt(diffx**2 + diffy**2)

def main():
    # Create the window and draw a prompt
    win = GraphWin("Mouse Distance", 500, 500)
    text = Text(Point(250, 400), "Click on the Window Twice")
    text.draw(win)
    
    # Get two clicks from the user
    mouse1 = win.getMouse()
    mouse2 = win.getMouse()
    
    # Draw a line between the clicks
    Line(mouse1, mouse2).draw(win)
    
    # Compute the distance between the points and update
    # the label with it
    dist = distance(mouse1, mouse2)
    text.setText("Distance: " + str(dist))
    
main()

a. Copy and paste the above code into a new file named mouse_distance.py.

b. Read the code carefully with your partner and make sure you understand what it is doing.

c. Run the code a few times to see it working first-hand.

d. Run the code in debug mode and trace through the code around the line that calls the function distance(mouse1, mouse2). Make sure the variables pane is visible so you can trace how the variables change over time.

Exercise 2

Create a file named functions_lab.py somewhere on your computer, and put your function definitions from the following exercises in it.

Recall that max(a,b) is a function that returns the maximum of the numbers a and b and min(a,b) returns the minimum.

Consider the following function:

def bound(num):
    return min(max(num, 0), 100)

a. Add the above function to your functions_lab.py file and click the green “Run” button. This will execute the definition statement so that you can use the bound function in the shell.

b. With your partner, predict the result of evaluating the following three expressions, then verify your predictions by executing them in the shell.

>>> bound(50)
>>> bound(105)
>>> bound(-5)

c. Now suppose we want to modify the bound function so that instead of just bounding numbers between 0..100, we can bound numbers between -1..1 and 10..20. In fact, it would be nice if we could bound numbers using any choice of lower and upper bounds. Copy and paste the following function template at the bottom of your functions_lab.py file.

def bound_between(num, lower, upper):
    return #--REPLACE THIS WITH YOUR SOLUTION--#

d. Finish implementing the function and run the functions_lab.py file so you have access to it in the shell.

HINT: Think about how bound bounds a number between 0 and 100 and use that idea in terms of lower and upper instead.

e. Test your solution on the following inputs:

>>> bound_between(3, -1, 1)
1
>>> bound_between(10, 0, 20)
10
>>> bound_between(-10, 0, 100)
0

Exercise 3

Now let’s try to create a runnable script that uses your bound_between function from exercise 2.

a. Copy and paste the following code at the end of your functions_lab.py file.

def main():
    num = float(input("Enter a number: "))
    bound_between(num, 0, 100)
    bound_between(num, -10, 10)

main()

b. Now when you run the file, it should prompt you to enter a number. With your partner, predict what will happen when you enter 50 as the number. Did the bounded numbers actually print?

NOTE: Since we did not print the values returned by bound_between, nothing is printed once we type in the number.

c. Now change each of the lines of code inside the main function to print(bound_between(num, 0, 100)), etc., and rerun the program.

WARNING: It is easy to confuse printing a value with returning a value. Here bound_between “returned” values but they were not printed.

Exercise 4

It is possible to have a function that does not return anything. Create a new file named greet.py and add the following function to it:

def greet(name):
    print("Hello " + name + ". It is nice to meet you!")

a. Run the file, then predict what the following statement will do in the shell:

>>> val = greet("Grace Hopper")
>>> print(val)

b. Verify your prediction by executing it in the shell and checking what the value in val is.

NOTE: Functions that don’t return anything are called void functions, and in Python these functions return a value called None. This is a special value that literally means “nothing.”