Python 03 Exercises
Python 03 Exercises
Practical Programming
in Python
Inspired by ’Practical Programming’ by Paul Gries, Jennifer Campbell, Jason Montojo
• If you made assumptions about the values of parameters or you know that your function
won’t work with particular values, write a precondition to warn other programmers.
Lecture 3: Exercises
When writing code, only use Python concepts that have been introduced
in the lectures already.
Exercise 1:
Two of Python’s built-in functions are min and max. In the Python shell, execute the following
function calls:
a. min(2, 3, 4)
Exercise 2:
For the following function calls, in what order are the subexpressions evaluated?
Exercise 3:
Following the function design recipe, define a function that has one parameter, a number, and
returns that number tripled.
Exercise 4:
Following the function design recipe, define a function that has two parameters, both of which
are numbers, and returns the absolute value of the difference of the two. Hint: Call built-in
function abs.
Exercise 5:
Following the function design recipe, define a function that has one parameter, a distance in
kilometers, and returns the distance in miles. (There are 1.60934 kilometers per mile.)
Exercise 6:
Following the function design recipe, define a function that has three parameters, grades be-
tween 0 and 100 inclusive, and returns the average of those grades.
Exercise 7:
Following the function design recipe, define a function that has four parameters, all of them
grades between 0 and 100 inclusive, and returns the average of the best 3 of those grades.
Hint: Call the function that you defined in the previous exercise.
Exercise 8:
Complete the examples in the docstring and then write the body of the following function:
Examples:
"""
Exercise 9:
Consider this code:
def square(n):
"""
Return the square of n.
Examples:
>>> square(3)
9
"""
In the table below, fill in the Example column by writing square, num, square(3), and 3 next
to the appropriate description.
Description Example
Parameter
Argument
Function name
Function call
Exercise 10:
Write the body of the square function from the previous exercise.