Functions: There’s a Name for That 155
answer the questions “How many Ping-Pong balls tall am I?” and
“What is my weight in Ping-Pong balls?”
An official Ping-Pong ball weighs 2.7 grams (0.095 ounces) and
measures 40 millimeters (4 centimeters, or 1.57 inches) in diameter.
To calculate how many Ping-Pong balls it would take to match our
height and weight, we need to divide our height in centimeters by 4
and divide our weight in grams by 2.7. But not everyone knows their
weight in grams or height in centimeters: in the United States, we
usually measure our weight in pounds and our height in feet and
inches. Fortunately, the two conversion functions we just developed
will help us convert those measurements to their equivalents in the
metric system. We can then use these numbers to perform the con-
version to Ping-Pong-ball units.
Our program will define the two conversion functions
convert_in2cm() and convert_lb2kg(). Then it will ask the user for
their height and weight, calculate the user’s height and weight in
Ping-Pong balls, and display the calculations on the screen. Type
and run the following code:
PingPongCalculator.py
u def convert_in2cm(inches):
return inches * 2.54
def convert_lb2kg(pounds):
return pounds / 2.2
v height_in = int(input("Enter your height in inches: "))
weight_lb = int(input("Enter your weight in pounds: "))
w height_cm = convert_in2cm(height_in)
x weight_kg = convert_lb2kg(weight_lb)
y ping_pong_tall = round(height_cm / 4)
z ping_pong_heavy = round(weight_kg * 1000 / 2.7)
{ feet = height_in // 12
| inch = height_in % 12
} print("At", feet, "feet", inch, "inches tall, and", weight_lb,
"pounds,")
print("you measure", ping_pong_tall, "Ping-Pong balls tall, and ")
print("you weigh the same as", ping_pong_heavy, "Ping-Pong balls!")