Lecture 7 - Useful Functions


As usual, create two directories for today's class. Create a directory called lecture7 under activities, and a directory called lab7 under labs.


Functional Parameters

Writing your own function can greatly increase readability, as well as code reuse. Last class, we saw how we could write a function using the input function to create an interactive function. There is a better way to define these functions, using parameters.


In-class Activity 1

Lots of Rectangles

In a file called lots_of_rectangles.py, create a Python function that takes an x coordinate, a y coordinate, a width, and a height and draws a rectangle of the specified dimensions that is centered on the specified position.

You will need to use the turtle.penup and turtle.pendown to allow the turtle to move without drawing. You can use the turtle.goto function to move the turtle to an arbitrary location.

Use your newly defined function to draw a small grid pattern on the screen.


Functional Style

There are some things you need to know, in order to make your code more readable when using functions. Specifically, how to comment these functions.


Return Statements

As you have no doubt noticed, all of the functions you have written thus far have done one thing, and displayed the result to the screen in some way (either by drawing or printing). That's not the only way to allow a function to provide its information; You have certainly seen functions that provide information back to where it was called from. We can do that using return statements.


In-class Activity 2

Paint Volume

Create a function called calculate_paint_volume in a file called paint.py.The function should return the number of gallons of paint that are required to paint walls of rectangular room given the length, width, and height of the room in feet. Assume that the floor and ceiling will also be painted and that paint can cover 350 square feet of wall per gallon. The number of gallons should be a real number.


Lab Assignment 7

BMI Redux

In a file called bmi_redux.py, create two functions called convert_pounds_to_kg and convert_feet_into_meters. Each function should take one parameter: a weight in pounds and a height in feet respectively. They should return a weight in kilograms and a height in meters.

Write a new BMI computation function, bmi_us that takes as input a weight in pounds and a height in feet. Your new function should call the function that we finished writing in class today, and return the BMI of the requested individual.


Submission

When you have finished, create a tar file of your lab7 directory. To submit your activity, go to cseval.roanoke.edu. You should see an available assignment called Lab Assignment 7. Only one of your pair should submit your activity. Make sure both partners are listed in the header of your file.

Do not forget to email your partner todays files!


Last modified: Tue Sep 10 18:08:16 EDT 2013