Python技术咨询:如何验证两个值是否处于指定数值区间内
Hey there! Let's break down what's wrong with your original code and get you a working solution for verifying if both tobe1 and tobe2 fall within the interval defined by val1 and val2.
First, Why Your Original Code Doesn't Work
Your line if tobe1, tobe2 in range(val1, val2): has two critical flaws:
range()only supports integers: Your values are floats (like 23.04), so passing them torange()will throw aTypeErrorsince it expects integer arguments.- Incorrect membership check: The syntax
tobe1, tobe2 in range(...)checks if the tuple(tobe1, tobe2)exists as an item in the range object—this is never what you want here. You need to validate each value individually against the interval bounds.
Correct Implementation
The simplest, most flexible way to handle this (works for both integers and floats) is to use direct comparison operators, and first normalize your interval bounds to account for cases where val1 might be larger than val2.
Basic Solution
val1 = 23.04 val2 = 29.04 tobe1 = 24.04 tobe2 = 27.04 # Normalize the interval to get consistent low and high bounds interval_low = min(val1, val2) interval_high = max(val1, val2) # Check if both values are within the CLOSED interval [interval_low, interval_high] if interval_low <= tobe1 <= interval_high and interval_low <= tobe2 <= interval_high: print("Both values are inside the interval!") else: print("At least one value is outside the interval.")
For Open Intervals (Optional)
If you don't want to include boundary values (e.g., values equal to val1 or val2 don't count), just replace the <= with <:
if interval_low < tobe1 < interval_high and interval_low < tobe2 < interval_high: print("Both values are strictly inside the interval!")
Reusable Function (Cleaner Approach)
If you need to perform this check multiple times, wrap the logic in a function for reusability:
def both_within_interval(val_a, val_b, check_val1, check_val2): interval_low = min(val_a, val_b) interval_high = max(val_a, val_b) return (interval_low <= check_val1 <= interval_high) and (interval_low <= check_val2 <= interval_high) # Usage example val1 = 23.04 val2 = 29.04 tobe1 = 24.04 tobe2 = 27.04 if both_within_interval(val1, val2, tobe1, tobe2): print("Both values are within the interval!") else: print("At least one value is outside the interval.")
This approach avoids the pitfalls of range() for non-integer intervals and works reliably for any numeric type.
内容的提问来源于stack exchange,提问作者Laurentiu Ionut

