Write a program that calcuates BMI in is, it should be robust
- User
Write a program that calcuates BMI in is, it should be robust
- Assistant
Write a program that calcuates BMI in is, it should be robust
Here's a Python program that calculates Body Mass Index (BMI) using SI units (meters and kilograms). The program includes robust error handling to ensure that only valid inputs are processed.
def calculate_bmi(weight_kg, height_m):
"""
Calculate BMI given weight in kilograms and height in meters.
"""
try:
bmi = weight_kg / (height_m ** 2)
return bmi
except ZeroDivisionError:
print("Error: Height cannot be zero.")
return None
def get_positive_float(prompt):
"""
Prompt the user for a positive floating-point number.
"""
while True:
try:
value = float(input(prompt))
if value <= 0:
print("Please enter a number greater than zero.")
else:
return value
except ValueError:
print("Invalid input. Please enter a numeric value.")
def main():
print("Welcome to the BMI Calculator!")
# Get user input with validation
weight_kg = get_positive_float("Enter your weight in kilograms: ")
height_m = get_positive_float("Enter your height in meters: ")
# Calculate BMI
bmi = calculate_bmi(weight_kg, height_m)
if bmi is not None:
print(f"Your BMI is: {bmi:.2f}")
# Interpret the BMI result
if bmi < 18.5:
status = "underweight"
elif bmi < 25:
status = "normal weight"
elif bmi < 30:
status = "overweight"
else:
status = "obese"
print(f"You are considered {status}.")
if __name__ == "__main__":
main()
Explanation:
calculate_bmi: A function that computes the BMI using the formula ( \text{BMI} = \frac{\text{weight (kg)}}{\text{height (m)}^2} ). It includes error handling for division by zero.
get_positive_float: A helper function that repeatedly prompts the user until they enter a valid positive floating-point number.
main: The main function orchestrates the program flow:
Key Features of Robustness:
Input Validation: Ensures that the weight and height entered are positive numbers and handles non-numeric inputs gracefully.
Error Handling: Catches and handles potential exceptions, such as division by zero and invalid input conversion.
User Guidance: Provides clear messages to guide the user in providing correct input.
How to Use the Program:
70).1.75).Sample Output:
Welcome to the BMI Calculator!
Enter your weight in kilograms: 70
Enter your height in meters: 1.75
Your BMI is: 22.86
You are considered normal weight.
By ensuring thorough input validation and clear error messages, this program provides a robust solution for calculating BMI.
Not yet included in a published release.