Skip to main content

BMI Calculator in Python

In this guide, we'll walk through the process of creating a simple Body Mass Index (BMI) calculator using Python. This application will allow users to calculate their BMI based on their height and weight, using both metric and imperial measurement systems. We'll cover the essential steps, including input handling, BMI calculation, classification, and a user-friendly interface.

Step 1: Setting Up Your Environment​

Before we begin coding, ensure you have Python installed on your system. You can download it from python.org. Once installed, you can use any text editor or integrated development environment (IDE) like VSCode, PyCharm, or even a simple text editor to write your code.

Step 2: Import Required Libraries​

Start by importing the necessary libraries at the beginning of your script. For this simple application, we’ll use the os and sys libraries for clearing the console and managing program exit.

import os
import sys

Step 3: Create a Function for Input Handling​

We need a way to get user input and validate it. The get_float_input function will prompt the user for input until they provide a valid float.

def get_float_input(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("INVALID.\n")

Step 4: Calculate BMI​

Next, we’ll create two functions to calculate BMI based on the user’s choice of measurement system: metric and imperial.

Metric Calculation​

The calculate_bmi_metric function will ask for height in meters and weight in kilograms.

def calculate_bmi_metric():
height_meters = get_float_input("Height in meters:\n>> ")
weight_kg = get_float_input("Weight in kilograms:\n>> ")

bmi = round(weight_kg / (height_meters ** 2), 2)
return bmi

Imperial Calculation​

The calculate_bmi_imperial function will ask for height in feet and weight in pounds, converting these values to metric for BMI calculation.

def calculate_bmi_imperial():
height_feet = get_float_input("Height in feet (e.g., 5.5 for 5 feet 6 inches):\n>> ")
weight_pounds = get_float_input("Weight in pounds:\n>> ")

height_meters = height_feet * 0.3048
weight_kg = weight_pounds * 0.453592
bmi = round(weight_kg / (height_meters ** 2), 2)
return bmi

Step 5: Classify the BMI​

Create a function to classify the BMI into categories. This will help users understand their weight status.

def classify_bmi(bmi):
if bmi < 18.5:
return "Severely Underweight"
elif bmi <= 24.90:
return "Normal"
elif bmi <= 29.90:
return "Overweight"
elif bmi <= 34.90:
return "Severely Overweight"
elif bmi <= 39.90:
return "Obese"
else:
return "Severely Obese"

Step 6: Build the Main Function​

Now, we’ll create the main function that ties everything together. It will present the application header, clear the console, prompt the user for their measurement system, and display the results.

def main():
os.system("cls" if os.name == 'nt' else "clear")
app_name = "Body Mass Index Calculator - mkeithX"
border_length = len(app_name) + 4

print("+" + "-" * (border_length - 2) + "+")
print(f"| {app_name} |")
print("+" + "-" * (border_length - 2) + "+")
print("Normal BMI: 18.50 - 24.90\n")

while True:
print("Choose a measurement system:")
print("[1] METRIC")
print("[2] IMPERIAL\n")
choice_measure = input(">> ").strip()

if choice_measure == "1":
bmi = calculate_bmi_metric()
break
elif choice_measure == "2":
bmi = calculate_bmi_imperial()
break
else:
print("Error. Please select 1 or 2.")

classification = classify_bmi(bmi)
print(f"\nYour BMI is {bmi} and classified as {classification}.")

Step 7: Loop for Continuation​

To allow users to calculate their BMI multiple times, we will include a loop at the end of the main function.

    while True:
response = input("\nDo you want to continue? [Y/n] ").strip().lower()
if response == "y":
main()
elif response == "n":
print("\nThank you.\n")
sys.exit()
else:
print("\nERROR: Please select Y or N.\n")

Step 8: Execute the Program​

Finally, ensure your main function runs when the script is executed:

if __name__ == "__main__":
main()

Congratulations!​

You've successfully created a BMI calculator in Python! This application not only allows users to compute their BMI but also provides a classification to understand their weight status better. You can further enhance this calculator by adding features like data storage, more health metrics, or even a graphical user interface. Happy coding!