range类使用异常求助:基于体重身高的区间判断逻辑实现疑问
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
rangeis 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

