[Tutor] how to rewrite area.py

Steven D'Aprano steve at pearwood.info
Wed Feb 22 01:25:32 CET 2012


William Stewart wrote:
> hello
> I need to rewrite area.py program so that it has separate functions for the perimeter and area of a square, a rectangle, and a circle (3.14 * radius**2). 
> I am horrible at math and I cannot even figure out what I need to do for this
> Any help would be appreciated

Have you learned about functions? Here's an example. Put this in a file and 
try it.

def get_drink():
     answer = raw_input("Would you like a cup of tea? (y/n) ").lower()
     while answer not in ('y', 'yes', 'n', 'no'):
         print "I'm sorry, I don't understand that response."
         print "Please enter Yes or No."
         answer = raw_input("Would you like a cup of tea? (y/n) ").lower()
     if answer in ('y', 'yes'):
         return "a nice steaming cup of tea, with a couple of biscuits"
     else:
         return "a stale cup of bitter coffee"


drink = get_drink()
print "I have", drink


Notice a few things:

First, you define a function with the "def" keyword, and give it a name, in 
this case, "get_drink". Names should usually be verbs ("doing words"), because 
functions do things.

Second, the function normally should use the "return" statement to send a 
result back to the caller.

Third, you call the function by name, using round brackets (parentheses) to 
indicate to Python that you are calling it, and save the result in a variable 
("drink" in the above example).

And finally, you can then use the variable for further processing.

In your case, you want six functions, to get the area of a square, the 
perimeter of a rectangle, etc. So for each function, you need to decide on a 
descriptive name, such as this:

def get_area_of_square():
     # Ask the user for the width of the square.
     ...
     # Calculate the area.
     area = width**2
     return area


The dots ... need to be filled in by you. Your program already has code that 
asks the user for a width, just grab it and put it inside the function.

The formulae you need are:


SQUARES:
     area = width*width = width**2
     perimeter = width+width+width+width = 4*width

RECTANGLES:
     area = width*height
     perimeter = width+height+width+height = 2*(width+height)

CIRCLES:
     area = pi*radius**2
     circumference = 2*pi*radius


To get the value of pi, put this at the top of your program:

from math import pi

Hope this helps.



-- 
Steven


More information about the Tutor mailing list