154 Chapter 7
To convert a length in inches to its equivalent in centimeters,
we multiply the number of inches by 2.54—the approximate num-
ber of centimeters in an inch. To pass that calculation back to the
rest of the program, we would use a return statement. The value
after the keyword return will be passed back to the program as the
function’s return value, or result. Let’s define our function:
def convert_in2cm(inches):
return inches * 2.54
If you type these two lines into the Python shell and then type
convert_in2cm(72) and press enter, Python will respond with 182.88.
There are about 182.88 centimeters in 72 inches (or 6 feet—my
height). The value 182.88 is returned by the function, and in the
command line shell, we see the return value printed on the next
line after we call a function.
We could also perform
another useful conversion:
pounds to kilograms. To con-
vert pounds to kilograms, we
divide the weight in pounds
by 2.2, the approximate num-
ber of pounds in 1 kilogram.
Let’s create a function called
convert_lb2kg() that will take a
value in pounds as its param-
eter and return the converted
value in kilograms:
def convert_lb2kg(pounds):
return pounds / 2.2
The return statement is sort of like using parameters in
reverse, except that we can return only one value, not a set of
values like the parameters we take in. (That one value can be a
list, however, so with some work you can pass multiple values back
in a single return variable.)
Using Return Values in a Program
Using these two conversion functions, let’s build a silly application:
a Ping-Pong-ball height and weight calculator. This program will