Coding a BMI Calculator in Python
My Java Script BMI Calculator post, which was written a little over three years ago still generates a decent amount of traffic. We’ve also previously covered writing a VBA code for this calculation. Today we’ll try to refresh our programming skills and take a stab at building a Python version of this code. There are some great reasons why Python is overtaking R in becoming the leading programming language for data science projects. Before we delve into any data analysis type of exercise, I thought it would be helpful to get orientated to this language via easy to follow calculation: BMI = (Weight/(Height^2)) * 703.06957964 , where Weight is measured in pounds , while Height is in inches . Before we write the first line of code, one thing to keep in mind is that while Python is a fairly easy programming language to understand and follow along; it’s rather peculiar as far as indentation is concerned. Please exercise a due care to ensure that your code compiles successfully by eliminating all of the extra blank spaces in your code and following proper indentation rules.
STEP 1. Getting input variables.
One thing that makes Python easy to work with is the lack of requirement to explicitly define your variables; you can do so as you go. Since we typically measure height in both: feet and inches, we would need to have two corresponding entries for the height and a separate one for the weight. The input command lets us ask for and retain a variable entry; all we need to do is to provide clear and concise instructions for the program user to follow. We will do some error handling in a batch later on in the code, but another alternative would be to validate each entry at a time. The reason I didn’t take this route was that I thought I could save a few lines of code in this program:
# Prompt for input variables heightft = input("Enter your height (feet): ") heightin = input("Enter your height (inches): ") weight = input("Enter your weight (pounds): ")
STEP 2. Error Handling: Part 1 – blank entries.
As mentioned earlier we want to be able to handle some errors with the data entry prior to proceeding to the actual BMI calculation. The first thing we we want to ensure is the fact that the entry is not a blank one. This code utilizes Boolean IF operator, as well as a combination of IF and OR functions, in addition to == operator to check if a variable equals to a value of interest, or a blank entry in our case. Should we actually encounter an error, let’s notify folks about it using a message via the print command and then exit the program:
# Ensure that entries are not blanks if heightft == "" or heightin =="": print ("Please enter your height.") exit() if weight == "": print ("Please enter your weight.") exit()
STEP 3. Format entry as a numeric data type
Once we know that the entries are not blank values, let’s format them as a float data types so we could use them in subsequent calculations:
# Format entries as float data type heightft = float(heightft) heightin = float(heightin) weight = float(weight)
STEP 4. Error Handling: Part 2 – abnormal entries.
Some things are common sense, while others are simply impossible. Let’s see if we are getting negative values for the weight or height entries; perhaps someone enters more than 12 for the inches portion of their height; or maybe someone thinks they weigh more than 1,500 pounds ? There are a few other conditions I thought it would be prudent to check, let me know if I missed anything?
# Handle abnormal entries for heights and weights if heightft <0 or heightin <0: print ("You cannot possibly have a negative height!") exit() if heightft < 3: print ("Standing " + str(heightft) + " feet tall you must be a child; this is an adult BMI calcuator!") exit() if heightft > 10: print ("Are you really " + str(heightft) + " feet tall ?!") exit() if heightin > 12: print ("Your height in inches shouldn't exceed 12!") exit() if weight < 0: print ("Your weight can only be negative in Theoretical Physics..., NOT in real life.") if weight < 30: print ("Weighing " + str(weight) + " lbs, you must be a child; this is an adult BMI calcuator!") exit() if weight > 1500: print ("Do you really weigh " + str(weight) + " pounds?!") exit()
STEP 5. Perform calculations.
Before we go any further, let’s calculate the height by combining feet and inches together. We then would use our trusted BMI formula to complete this calculation:
# Calculate total height in inches height = heightft*12 + heightin # Compute BMI thisBMI = round((weight /(height*height)) * 703.06957964,2)
STEP 6. Interpret BMI score.
I used Center for Disease Control guidelines to provide users with helpful and arguably encouraging feedback pertaining to their health:
# Interpret BMI if thisBMI < 18.5: print ("Your BMI is ", thisBMI, " Underweight - eat a bagel!") elif 18.5 <= thisBMI <= 24.99: print ("Your BMI is ", thisBMI, " - Normal, keep it up!") elif 25 <= thisBMI <= 29.99: print ("Your BMI is ", thisBMI, " - Overweight, exercise more!") elif 30 <= thisBMI <= 39.99: print ("Your BMI is ", thisBMI, " - Obese, get off the couch!") elif thisBMI >=40: print ("Your BMI is ", thisBMI, " - Morbidly Obese - take action!") else: print("Please check your input values, BMI cannot be calculated.")
This wasn’t that difficult, after all, correct? Feel free to download full script of this program.
What are your favorite Python projects?