杰瑞科技汇

Python中between in如何使用?

Of course! In Python, the concept of "between" is typically implemented using comparison operators. There isn't a single keyword called between like in some other languages (e.g., SQL's BETWEEN).

Python中between in如何使用?-图1
(图片来源网络,侵删)

The most common and Pythonic way to check if a value x is between two other values a and b is to use chained comparisons.

The Core Concept: Chained Comparisons

Python allows you to chain comparison operators together. This means you can write a < x < b and Python will evaluate it as (a < x) and (x < b).

This is the preferred, most readable, and most efficient method.


Numeric Values (Integers, Floats)

This is the most straightforward use case.

Python中between in如何使用?-图2
(图片来源网络,侵删)

Example: Exclusive Range (e.g., a < x < b)

This checks if x is strictly greater than a and strictly less than b.

score = 85
# Check if score is between 80 and 90 (exclusive)
if 80 < score < 90:
    print("Score is in the B range.")
else:
    print("Score is NOT in the B range.")
# Output: Score is in the B range.
# You can also use variables for the bounds
lower_bound = 80
upper_bound = 90
if lower_bound < score < upper_bound:
    print("Score is in the B range (using variables).")
# Output: Score is in the B range (using variables).

Example: Inclusive Range (e.g., a <= x <= b)

This checks if x is greater than or equal to a AND less than or equal to to b. This is often what people mean by "between".

age = 18
# Check if age is between 18 and 65 (inclusive)
if 18 <= age <= 65:
    print("You are a working-age adult.")
else:
    print("You are not a working-age adult.")
# Output: You are a working-age adult.

String Values

You can also use chained comparisons with strings. Python compares strings lexicographically (based on alphabetical order, using their Unicode/ASCII values).

name = "Molly"
# Check if the name starts with a letter between 'L' and 'P'
if 'L' <= name <= 'P':
    print("Name starts with a letter between L and P.")
else:
    print("Name does NOT start with a letter between L and P.")
# Output: Name starts with a letter between L and P.
# This works because 'Molly' > 'L' and 'Molly' < 'P' (lexicographically)

Handling "Between" for Lists or Sequences

What if you want to check if a value x is between two values that are not necessarily the lower and upper bounds? For example, is x between a and b, where a could be greater than b?

Python中between in如何使用?-图3
(图片来源网络,侵删)

In this case, you need to determine the minimum and maximum of the two bounds first.

x = 15
a = 10
b = 20
# This is the standard way to check if x is in the range defined by a and b
if min(a, b) <= x <= max(a, b):
    print(f"{x} is between {a} and {b}.")
else:
    print(f"{x} is NOT between {a} and {b}.")
# --- What if the bounds are reversed? ---
a_reversed = 20
b_reversed = 10
# The same logic still works!
if min(a_reversed, b_reversed) <= x <= max(a_reversed, b_reversed):
    print(f"{x} is between {a_reversed} and {b_reversed}.")
else:
    print(f"{x} is NOT between {a_reversed} and {b_reversed}.")
# Output for both:
# 15 is between 10 and 20.
# 15 is between 20 and 10.

Alternative (But Less Recommended) Methods

While chained comparisons are best, it's good to know other ways.

Method 2: Using the and Operator

This is equivalent to the chained comparison but is more verbose.

score = 85
if score > 80 and score < 90:
    print("Score is in the B range.")
# Output: Score is in the B range.

Why it's less ideal:

  • More verbose: You have to write score twice.
  • Less readable: The relationship between the parts isn't as immediately clear as 80 < score < 90.

Method 3: Using range() and in (for Integers)

This is a great option if you are working with a sequence of integers and want to check for membership. It's very readable for discrete steps.

score = 85
# Check if score is in a range of integers from 81 to 89
if score in range(81, 90): # Note: range is exclusive of the stop value
    print("Score is in the B range using range().")
# Output: Score is in the B range using range().

Why it's less ideal for general use:

  • It only works for integers. You cannot use score in range(80.5, 89.5).
  • It can be less memory-efficient for very large ranges, as range() creates an object, not a list in Python 3.

Summary: Which Method to Use?

Use Case Recommended Method Example
Any type (numeric, string) Chained Comparisons if a <= x <= b:
Integer membership in a sequence in with range() if x in range(10, 21):
Explicit and logic and operator (less common) if x > a and x < b:

For almost all situations, chained comparisons (a < x < b) are the most Pythonic, readable, and efficient choice.

分享:
扫描分享到社交APP
上一篇
下一篇