// Functions
RETURN Mini Project — BMI Calculator
The problem...
Your BMI Calculator calculates and prints — all in one function. But you can't use the BMI value anywhere else. You can't check the category. You can't store it. It's gone after the print.
The idea!
Split it. One function calculates and returns the BMI. Another receives the BMI and returns the category. A third prints everything. Each function has one job. return connects them.
The solution
def calculate_bmi(weight, height):
return weight / height ** 2
def get_category(bmi):
if bmi < 18.5:
return "Underweight"
elif bmi < 25:
return "Normal weight"
elif bmi < 30:
return "Overweight"
else:
return "Obese"
def print_bmi(weight, height):
bmi = calculate_bmi(weight, height)
category = get_category(bmi)
print(f"Weight: {weight}kg | Height: {height}m | BMI: {bmi:.1f} | {category}")
print_bmi(70, 1.75)
print_bmi(90, 1.80)
print_bmi(55, 1.60)
Test it
# Weight: 70kg | Height: 1.75m | BMI: 22.9 | Normal weight
# Weight: 90kg | Height: 1.80m | BMI: 27.8 | Overweight
# Weight: 55kg | Height: 1.60m | BMI: 21.5 | Normal weight
What's really happening
calculate_bmi() does the math and returns the number. get_category() receives the number and returns the label. print_bmi() calls both and prints the full summary. Three functions. Three jobs. return connects them.
You can also use the functions independently:
bmi = calculate_bmi(70, 1.75)
print(bmi) # 22.857...
print(f"{bmi:.1f}") # 22.9
print(get_category(bmi)) # Normal weight
Go further
- Add your name as a parameter to
print_bmi()— print"Bull | BMI: 22.9" - Call
calculate_bmi()andget_category()separately — use the returned values directly - Add a
is_healthy(bmi)function — returnsTrueif BMI is between 18.5 and 24.9
What you should understand now
- Each function has one job — calculate, categorize, or print
returnconnects functions — output of one becomes input of another- Functions can be used independently or together
- Small, focused functions are easier to read, fix, and reuse
// resources
// 0 comments
// No comments yet. Be the first.
// leave a comment