Calculations with User Input

Now that we know how to get input from the user and store it into variables and since we know how to do some basic math, we can now write our first useful program!

bmicalc.py
1
2
3
4
5
6
7
8
from __future__ import print_function
input = raw_input

m = float(input("Your height in m: "))
kg = float(input("Your weight in kg: "))
bmi = kg / m**2

print("Your BMI is", bmi)

What You Should See

Your height in m: 1.75
Your weight in kg: 73
Your BMI is 23.8367346939

This exercise is (hopefully) pretty straightforward. We have three variables (all floats): m (meters), kg (kilograms) and bmi (body mass index). We read in values for m and kg, but bmi's value comes not from the human but as the result of a calculation. On line 6 we compute the mass divided by the square of the height and store the result into bmi. And then we print it out.

The body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations. So this result would be informative for a health professional. For now that's all we can do with it.

Eventually we will learn how to display a different message on the screen depending on what value is in the BMI variable, but for now this will have to do.

Today's exercise is hopefully pretty easy to understand, but the Study Drills are quite a bit tougher than usual this time. If you can get them done without help, then your understanding is probably pretty good.

Study Drills

  1. Make it so the human can input their height in feet and inches (use two new variables for this) and in pounds instead of kilograms. Then add some code to convert those values into kilograms and meters.

To test your new code, a person that is 5 feet 9 inches and weighs 160 pounds should have a BMI of approximately 23.6.




©2017 Graham Mitchell