BMI calculator in Python
About the project:This program will ask user for its weight and height, calculate your BMI, and then tell you which category your BMI falls into.
You will also be able to choose between metric (kilograms and meters) and imperial (pounds and inches) units.
Here, You can calculate Body Mass Index (BMI) using weight and height you will input.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: choose any code snippet and follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# bmi_calculator.py
def get_numeric_input(prompt, unit_name, min_value=0):
"""
Helper function to get valid numeric input from the user.
Ensures the input is a positive number.
"""
while True:
try:
value = float(input(prompt).strip())
if value <= min_value:
print(f"Please enter a positive value for {unit_name}.")
else:
return value
except ValueError:
print("Invalid input. Please enter a number.")
def calculate_bmi(weight, height, unit_system):
"""
Calculates the Body Mass Index (BMI) based on weight, height, and unit system.
Returns the calculated BMI.
"""
if unit_system == "metric":
# BMI = weight (kg) / (height (m) * height (m))
return weight / (height ** 2)
elif unit_system == "imperial":
# BMI = (weight (lbs) / (height (in) * height (in))) * 703
return (weight / (height ** 2)) * 703
else:
return None # Should not happen with validation
def classify_bmi(bmi):
"""
Classifies the BMI into standard categories.
Returns a string representing the BMI category.
"""
if bmi < 18.5:
return "Underweight"
elif 18.5 <= bmi < 24.9:
return "Normal weight"
elif 25 <= bmi < 29.9:
return "Overweight"
else:
return "Obese"
def main():
"""Main function to run the BMI Calculator."""
print("--- Python BMI Calculator ---")
while True:
print("\nSelect your unit system:")
print("1. Metric (kilograms and meters)")
print("2. Imperial (pounds and inches)")
print("3. Quit")
choice = input("Enter your choice (1, 2, or 3): ").strip()
if choice == '3':
print("Exiting BMI Calculator. Goodbye!")
break
unit_system = ""
if choice == '1':
unit_system = "metric"
elif choice == '2':
unit_system = "imperial"
else:
print("Invalid choice. Please enter 1, 2, or 3.")
continue
weight = 0
height = 0
if unit_system == "metric":
weight = get_numeric_input("Enter your weight in kilograms (kg): ", "weight")
height = get_numeric_input("Enter your height in meters (m): ", "height")
elif unit_system == "imperial":
weight = get_numeric_input("Enter your weight in pounds (lbs): ", "weight")
height = get_numeric_input("Enter your height in inches (in): ", "height")
# Perform the BMI calculation
bmi = calculate_bmi(weight, height, unit_system)
if bmi is not None:
category = classify_bmi(bmi)
print(f"\nYour BMI is: {bmi:.2f}")
print(f"Classification: {category}")
else:
print("An error occurred during BMI calculation.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
- Run the Python script.
- You'll be prompted to select your unit system (Metric or Imperial).
- Based on your choice, the program will ask for your weight and height.
- It will then calculate and display your BMI and tell you which category you fall into (Underweight, Normal weight, Overweight, or Obese).
You can perform multiple calculations until you choose to quit.
Below is another code snippet with BMI Calculator to make it even more useful.
Below code will include:
BMI History: You can now save your calculated BMI results and view a log of all your previous entries.
Enhanced Health Advice: The calculator will provide a brief interpretation and general health advice based on your BMI category.
# bmi_calculator.py
import json
import os
from datetime import datetime
# Filename for storing BMI history
BMI_HISTORY_FILE = "bmi_history.json"
def get_numeric_input(prompt, unit_name, min_value=0):
"""
Helper function to get valid numeric input from the user.
Ensures the input is a positive number.
"""
while True:
try:
value = float(input(prompt).strip())
if value <= min_value:
print(f"Please enter a positive value for {unit_name}.")
else:
return value
except ValueError:
print("Invalid input. Please enter a number.")
def calculate_bmi(weight, height, unit_system):
"""
Calculates the Body Mass Index (BMI) based on weight, height, and unit system.
Returns the calculated BMI.
"""
if unit_system == "metric":
# BMI = weight (kg) / (height (m) * height (m))
return weight / (height ** 2)
elif unit_system == "imperial":
# BMI = (weight (lbs) / (height (in) * height (in))) * 703
return (weight / (height ** 2)) * 703
else:
# This case should ideally not be reached due to input validation
return None
def classify_bmi(bmi):
"""
Classifies the BMI into standard categories and provides general advice.
Returns a tuple: (category_string, advice_string)
"""
if bmi < 18.5:
category = "Underweight"
advice = "Being underweight can sometimes indicate nutritional deficiencies or other health issues. Consider consulting a healthcare professional."
elif 18.5 <= bmi < 24.9:
category = "Normal weight"
advice = "Your BMI is in the healthy range. Keep up good habits with a balanced diet and regular exercise."
elif 25 <= bmi < 29.9:
category = "Overweight"
advice = "Being overweight can increase the risk of certain health problems. Lifestyle changes like diet and exercise can help."
else: # bmi >= 30
category = "Obese"
advice = "Obesity significantly increases the risk of various health conditions. It's advisable to consult a healthcare professional for a personalized plan."
return category, advice
def save_bmi_entry(bmi, category, weight, height, unit_system):
"""
Saves a BMI entry to a JSON file.
"""
entry = {
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"bmi": round(bmi, 2),
"category": category,
"weight": round(weight, 2),
"height": round(height, 2),
"unit_system": unit_system
}
history = []
if os.path.exists(BMI_HISTORY_FILE):
try:
with open(BMI_HISTORY_FILE, 'r') as f:
history = json.load(f)
except json.JSONDecodeError:
# Handle empty or corrupted JSON file
print("Warning: BMI history file is corrupted or empty. Starting new history.")
history = []
history.append(entry)
with open(BMI_HISTORY_FILE, 'w') as f:
json.dump(history, f, indent=4)
print("BMI entry saved to history.")
def view_bmi_history():
"""
Displays all saved BMI entries from the JSON file.
"""
if not os.path.exists(BMI_HISTORY_FILE) or os.stat(BMI_HISTORY_FILE).st_size == 0:
print("\nNo BMI history found yet.")
return
try:
with open(BMI_HISTORY_FILE, 'r') as f:
history = json.load(f)
except json.JSONDecodeError:
print("Error: Could not read BMI history file. It might be corrupted.")
return
if not history:
print("\nNo BMI history found yet.")
return
print("\n--- Your BMI History ---")
for i, entry in enumerate(history):
print(f"\nEntry {i+1}:")
print(f" Date/Time: {entry.get('timestamp', 'N/A')}")
print(f" Weight: {entry.get('weight', 'N/A')} {entry.get('unit_system', 'N/A').replace('metric', 'kg').replace('imperial', 'lbs')}")
print(f" Height: {entry.get('height', 'N/A')} {entry.get('unit_system', 'N/A').replace('metric', 'm').replace('imperial', 'in')}")
print(f" BMI: {entry.get('bmi', 'N/A'):.2f}")
print(f" Category: {entry.get('category', 'N/A')}")
print("------------------------")
def main():
"""Main function to run the BMI Calculator."""
print("--- Python BMI Calculator ---")
while True:
print("\nSelect an option:")
print("1. Calculate New BMI")
print("2. View BMI History")
print("3. Quit")
choice = input("Enter your choice (1, 2, or 3): ").strip()
if choice == '3':
print("Exiting BMI Calculator. Goodbye!")
break
elif choice == '2':
view_bmi_history()
continue
elif choice == '1':
print("\nSelect your unit system for calculation:")
print("a. Metric (kilograms and meters)")
print("b. Imperial (pounds and inches)")
unit_choice = input("Enter your choice (a or b): ").strip().lower()
unit_system = ""
if unit_choice == 'a':
unit_system = "metric"
elif unit_choice == 'b':
unit_system = "imperial"
else:
print("Invalid choice. Please enter 'a' or 'b'.")
continue
weight = 0
height = 0
if unit_system == "metric":
weight = get_numeric_input("Enter your weight in kilograms (kg): ", "weight")
height = get_numeric_input("Enter your height in meters (m): ", "height")
elif unit_system == "imperial":
weight = get_numeric_input("Enter your weight in pounds (lbs): ", "weight")
# For imperial height, often input as feet and inches.
# For simplicity here, we'll ask for total inches.
height = get_numeric_input("Enter your height in inches (in): ", "height")
# Perform the BMI calculation
bmi = calculate_bmi(weight, height, unit_system)
if bmi is not None:
category, advice = classify_bmi(bmi)
print(f"\nYour BMI is: {bmi:.2f}")
print(f"Classification: {category}")
print(f"Advice: {advice}")
save_bmi_entry(bmi, category, weight, height, unit_system)
else:
print("An error occurred during BMI calculation. Please check your inputs.")
else:
print("Invalid choice. Please enter 1, 2, or 3.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
- When you run the script, you'll see a main menu with options to "Calculate New BMI" or "View BMI History".
- After calculating a BMI, the result, its classification, and a brief piece of health advice will be displayed.
- Each calculation you perform will now be saved to a file named bmi_history.json in the same directory as your script.