// Functions
ErrorHandling Mini Project — BMI Calculator
The problem...
You've built the BMI Calculator three times. Each version was better than the last.
But none of them handled bad input. Type a word — crash. Enter a negative weight — wrong result. Enter zero as height — division by zero.
Time to make it bulletproof.
The idea!
Three functions. Each with one job. Built in the order you need them.
Step 1 — get valid input
def get_input(prompt):
while True:
try:
value = float(input(prompt))
if value <= 0:
raise ValueError("Value must be greater than zero.")
return value
except ValueError as e:
print(f"Invalid input: {e}")
Keeps asking until the user provides a valid positive number. Handles both wrong types and wrong values.
Step 2 — calculate BMI
def calculate_bmi(weight, height):
return weight / height ** 2
Clean and simple — validation already happened in get_input().
Step 3 — get the category
def get_category(bmi):
if bmi < 18.5:
return "Underweight"
elif bmi < 25:
return "Normal weight"
elif bmi < 30:
return "Overweight"
else:
return "Obese"
Put it together
weight = get_input("Enter your weight (kg): ")
height = get_input("Enter your height (m): ")
bmi = calculate_bmi(weight, height)
category = get_category(bmi)
print(f"Weight: {weight}kg | Height: {height}m | BMI: {bmi:.1f} | {category}")
Test it
# Enter your weight (kg): abc
# Invalid input: could not convert string to float: 'abc'
# Enter your weight (kg): -5
# Invalid input: Value must be greater than zero.
# Enter your weight (kg): 70
# Enter your height (m): 1.75
# Weight: 70kg | Height: 1.75m | BMI: 22.9 | Normal weight
Go further
- Add a name parameter to the final print —
"Bull | BMI: 22.9 | Normal weight" - Wrap everything in a
while True— let the user calculate multiple times - Add
raiseinsidecalculate_bmi()as an extra safety net
What you should understand now
get_input()— validates before anything else runscalculate_bmi()— clean logic, no validation neededget_category()— one job, one result- Three functions, built in order, each feeding the next
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment