Checking if a number falls within a specific interval is a fundamental operation in programming, used for data validation, game logic, and statistical analysis. Unlike many other languages that require verbose logical operators, Python supports mathematical chained comparison operators, allowing for cleaner and more readable code.
This guide explains the most Pythonic way to check ranges, how to use the range() function for integers, and how to handle common edge cases like exclusive boundaries.
Method 1: Chained Comparison Operators (Recommended)
Python is unique among popular programming languages because it allows you to chain comparison operators logically, exactly as you would write in mathematics (e.g., 0 < x < 10). This is the most readable and efficient method.
Syntax: min_val <= variable <= max_val
score = 85
if score >= 0 and score <= 100:
print("Valid score (Verbose)")
if 0 <= score <= 100:
print("Valid score (Pythonic)")Output:
Valid score (Verbose)
Valid score (Pythonic)Method 2: Using Logical and Operators
If you are coming from C, Java, or JavaScript, you might be used to explicitly combining two conditions using the and operator. While valid in Python, it is less concise than Method 1.
This method is sometimes necessary if the logic is dynamic or involves function calls that shouldn't be repeated.
temperature = 25
if temperature > 10 and temperature < 30:
print("Temperature is pleasant.")Output:
Temperature is pleasant.Method 3: Using range() (Integers Only)
The range() function generates a sequence of numbers. You can use the in operator to check membership. However, this comes with specific constraints:
- Integers Only:
range()does not support floats. - Exclusive End: The
stopparameter is not included in the range.
user_choice = 5
try:
if 5.5 in range(1, 10):
print("Float found")
else:
print("Float NOT found in integer range")
if 5 in range(1, 5):
print("5 is in range")
else:
print("5 is NOT in range(1, 5)")
except TypeError as e:
print(f"Error: {e}")
if user_choice in range(1, 6): # Covers 1, 2, 3, 4, 5
print(f"{user_choice} is a valid choice (1-5)")Output:
Float NOT found in integer range
5 is NOT in range(1, 5)
5 is a valid choice (1-5)Common Pitfall: Floating Point Boundaries
When checking ranges for floating-point numbers, standard comparison operators (<, <=) work fine. However, attempting to use range() or strict equality (==) with floats can lead to bugs due to precision issues.
val = 0.1 + 0.2 # Technically 0.30000000000000004 due to float precision
if 0.0 <= val <= 0.5:
print(f"{val} is within range")Output:
0.30000000000000004 is within rangeConclusion
To check if a number is within a range in Python:
- Use Chained Comparison (
min <= x <= max) for the most readable and efficient code. - Use
range(start, stop)only when checking for integers and remember thatstopis exclusive. - Avoid logical
andunless you have specific side-effects to manage.