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

range类使用异常求助:基于体重身高的区间判断逻辑实现疑问

Fixing Your BMI Range Logic (And Why range Isn't the Right Tool Here)

Hey there! Let's sort out this BMI check logic for you. First off, let's clear up why range isn't working for your case: the range class in Python is designed to generate sequences of integers (like range(1, 5) gives you 1,2,3,4). But your BMI calculation will almost certainly be a floating-point number (e.g., 22.7, 18.9), so range can't properly check if a float falls within a continuous numerical interval.

Instead, we'll use simple comparison operators to handle the ranges, which is way more straightforward for this kind of check. Here's the full, working code with explanations:

Step 1: Calculate BMI Correctly

First, you need to convert height from centimeters to meters (since BMI uses meters for height). Then compute the BMI value:

# Get user inputs
weight = float(input('What is your weight (kg)? '))
height_cm = float(input('What is your height (cm)? '))

# Convert height to meters and calculate BMI
height_m = height_cm / 100
bmi = weight / (height_m ** 2)

Step 2: Add the Range Check Logic

Now use if-elif-else to evaluate the BMI against your desired ranges:

# Check BMI ranges and output the corresponding message
if bmi < 19:
    print("you are skinny as rail")
elif 19 <= bmi <= 25:
    print("you are fit as a butcher's dog")
else:  # BMI >25
    print("you are as plum as a partridge")

Putting It All Together

Here's the complete script:

weight = float(input('What is your weight (kg)? '))
height_cm = float(input('What is your height (cm)? '))

height_m = height_cm / 100
bmi = weight / (height_m ** 2)

if bmi < 19:
    print("you are skinny as rail")
elif 19 <= bmi <= 25:
    print("you are fit as a butcher's dog")
else:
    print("you are as plum as a partridge")

Why This Works Better Than range

  • range is meant for iterating over integer sequences, not checking if a float falls within a continuous numerical range.
  • Direct comparisons (<, <=, >=, >) are precise for floating-point values and make your logic easy to read and maintain.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:45:17