Skip to main content

How to Check If a Number Is Within a Range in Python

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.

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

# ⛔️ Verbose: Traditional programming style (valid but Cluttered)
if score >= 0 and score <= 100:
print("Valid score (Verbose)")

# ✅ Correct: Pythonic Chained Comparison
if 0 <= score <= 100:
print("Valid score (Pythonic)")

Output:

Valid score (Verbose)
Valid score (Pythonic)
tip

You can chain as many operators as needed, though readability may suffer if overused. Example: 0 < x < y < 100 checks if x is between 0 and 100, y is between 0 and 100, and x is smaller than y.

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

# ✅ Correct: Explicit logical check
# Useful if 'temperature' was a function call you didn't want to repeat
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:

  1. Integers Only: range() does not support floats.
  2. Exclusive End: The stop parameter is not included in the range.
user_choice = 5

try:
# ⛔️ Incorrect: Checking a float against range()
# 5.5 is never "in" a sequence of integers
if 5.5 in range(1, 10):
print("Float found")
else:
print("Float NOT found in integer range")

# ⛔️ Incorrect: range(1, 5) includes 1, 2, 3, 4. It excludes 5.
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}")

# ✅ Correct: Ensure inputs are integers and account for exclusive stop
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)
note

Using x in range(a, b) is highly efficient in Python 3. It calculates membership mathmatically in O(1) time; it does not generate all numbers in memory.

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

# ✅ Correct: Use comparisons for ranges
if 0.0 <= val <= 0.5:
print(f"{val} is within range")

Output:

0.30000000000000004 is within range
warning

Avoid using range() for checking floats. Always use comparison operators (Method 1).

Conclusion

To check if a number is within a range in Python:

  1. Use Chained Comparison (min <= x <= max) for the most readable and efficient code.
  2. Use range(start, stop) only when checking for integers and remember that stop is exclusive.
  3. Avoid logical and unless you have specific side-effects to manage.