script_12.py - BMI Calculator with Categories
Code
#!/usr/bin/env python3
"""BMI calculator with categories"""
weight = float(input("Enter weight in kg: "))
height = float(input("Enter height in meters: "))
bmi = weight / (height ** 2)
if bmi < 18.5:
print(f"BMI: {bmi:.1f} - Underweight")
elif bmi < 25:
print(f"BMI: {bmi:.1f} - Normal weight")
elif bmi < 30:
print(f"BMI: {bmi:.1f} - Overweight")
else:
print(f"BMI: {bmi:.1f} - Obese")
Explanation
Line 4-5: Variable assignments
- Two input() calls, both converted to float type
- weight and height store float values
- Float needed for decimal values like 70.5 kg or 1.75 meters
Line 7: bmi = weight / (height ** 2)
- / is division operator (returns float)
- ** is exponentiation operator (power)
- height ** 2 means height squared (height × height)
- Parentheses ensure exponentiation happens before division
- bmi variable stores the calculated float result
- BMI formula: weight in kg divided by height in meters squared
Line 10: print(f"BMI: {bmi:.1f} - Underweight")
- f-string with format specifier
- {bmi:.1f} formats float to 1 decimal place
- .1f means one digit after decimal point
- Prevents long decimal output like 23.4567891
Line 9: if bmi < 18.5:
- Checks if BMI is below 18.5 (underweight threshold)
- 18.5 is a float literal
Line 11: elif bmi < 25:
- Only checked if bmi >= 18.5 (not underweight)
- Effectively checks range 18.5 to 24.99
- Sequential elif creates ranges automatically