如何修复我编写的Python BMI计算器代码?
Fix Your Python BMI Calculator
Got it, let's fix your BMI calculator step by step. Here are the key issues in your code and how to resolve them:
Key Issues in the Original Code
- Return type mismatch: Your function returns a string (like
"Your BMI is 22.5"), but you're trying to compare this string to numeric values (18, 25) later—this will throw aTypeError. - Incomplete
elseclause: The finalelse...is cut off, which causes a syntax error. - Rigid input type for weight: Using
int()for weight means users can't enter decimal values (e.g., 62.5 kg) without an error. - Minor UX tweak: Adding a space at the end of input prompts makes typing feel more natural.
Fixed Code
print('BMI calculator V1') name = input("What's your name? ") # Use float for weight to support decimal values weight = float(input("Your weight in Kilograms: ")) height = float(input("Your height in Metres: ")) def calculate_bmi(w, h): # Return the numeric BMI value instead of a string bmi = w / h ** 2 return bmi # Calculate BMI first (numeric value) user_bmi = calculate_bmi(weight, height) # Print the formatted BMI string separately print(f"Your BMI is {user_bmi:.2f}") # .2f rounds to 2 decimal places for readability # Now we can compare the numeric BMI value correctly if user_bmi < 18.5: # Updated to standard BMI threshold (18.5 instead of 18) print(f"{name}, you are underweight") elif user_bmi > 25: print(f"{name}, you are overweight") else: print(f"{name}, you have a healthy weight")
What Changed?
- Function returns numeric BMI: The
calculate_bmifunction now returns the raw number instead of a string, so we can use it for comparisons. - Fixed input type: Weight uses
float()to accept decimal values. - Completed
elseclause: Added the missing colon and a message for healthy weight. - Improved formatting: Used an f-string to print BMI rounded to 2 decimal places (easier to read than a long float).
- Updated threshold: Changed the underweight cutoff to 18.5, which aligns with standard BMI guidelines (optional, but more accurate).
内容的提问来源于stack exchange,提问作者SepiaAR16
相关产品推荐
相关产品推荐

