You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复我编写的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 a TypeError.
  • Incomplete else clause: The final else... 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?

  1. Function returns numeric BMI: The calculate_bmi function now returns the raw number instead of a string, so we can use it for comparisons.
  2. Fixed input type: Weight uses float() to accept decimal values.
  3. Completed else clause: Added the missing colon and a message for healthy weight.
  4. Improved formatting: Used an f-string to print BMI rounded to 2 decimal places (easier to read than a long float).
  5. Updated threshold: Changed the underweight cutoff to 18.5, which aligns with standard BMI guidelines (optional, but more accurate).

内容的提问来源于stack exchange,提问作者SepiaAR16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:22:40