Back to series
· 11 min read

Python Comparison Operators and Logical Operators


1. Overview of Comparison Operators and Logical Operators

In Python, comparison operators and logical operators are core components of conditional judgment.

Comparison operators answer what relationship exists between two objects, such as whether they are equal, which one is greater, or whether a certain element exists.

Logical operators combine multiple judgment results, such as whether multiple conditions are all true at the same time, whether at least one condition is true, and how to negate a condition.

For example:

age = 25
has_ticket = True
is_vip = False

result = age >= 18 and has_ticket

print(result)
# True

This code contains:

  • age >= 18: a comparison expression that checks whether the age meets the requirement.
  • and: a logical operator that requires the conditions on both sides to be satisfied.
  • has_ticket: a boolean value participating in the logical operation.

From a semantic perspective:

Comparison operators: produce a judgment result
Logical operators: combine judgment conditions

Note that Python's logical operators do not require their operands to be of type bool. They can perform truth-value testing on any object, and and and or may return the original operands.

2. Classification of Comparison Operators

Python provides six common comparison operators:

Operator Name Meaning Example Result
== Equal to Checks whether two values are equal 10 == 10 True
!= Not equal to Checks whether two values are not equal 10 != 5 True
> Greater than Checks whether the left side is greater than the right side 10 > 5 True
< Less than Checks whether the left side is less than the right side 5 < 10 True
>= Greater than or equal to Checks whether the left side is not less than the right side 10 >= 10 True
<= Less than or equal to Checks whether the left side is not greater than the right side 5 <= 10 True

1. The equality operator ==

== is used to check whether the values of two objects are equal.

a = 100
b = 100

print(a == b)
# True

For strings:

name1 = "Python"
name2 = "Python"

print(name1 == name2)
# True

For lists:

list1 = [1, 2, 3]
list2 = [1, 2, 3]

print(list1 == list2)
# True

== compares the equality relationship defined by the objects. For built-in containers, comparison is usually based on element content; for custom objects, it may be determined by __eq__().

2. The inequality operator !=

!= is used to check whether the values of two objects are not equal.

password = "123456"

if password != "admin":
    print("密码不是默认密码")

For built-in types, != usually produces the opposite result of ==, but custom types can implement __eq__() and __ne__() separately, so this relationship should not be treated as an absolute guarantee for all objects.

3. The greater-than operator >

> is used to check whether the left operand is greater than the right operand.

score = 85

print(score > 60)
# True

Common uses include:

  • Checking whether a score exceeds the passing line.
  • Checking whether inventory has reached a warning threshold.
  • Checking whether the temperature exceeds the limit.
  • Checking whether the user's balance is sufficient.

4. The less-than operator <

< is used to check whether the left operand is less than the right operand.

temperature = 12

if temperature < 15:
    print("天气较冷")

5. Greater Than or Equal To >=

>= means the left operand is greater than or equal to the right operand.

age = 18

print(age >= 18)
# True

6. Less Than or Equal To <=

<= means the left operand is less than or equal to the right operand.

quantity = 10

print(quantity <= 10)
# True

7. The Return Value of Comparison Operators

For comparisons between common built-in numbers and strings, the result is usually a Boolean value:

print(10 > 5)
# True

print(10 == 5)
# False

But from the perspective of Python's object model, comparison operators do not necessarily always return a true bool object. A custom class can make its comparison special methods return other objects.

Therefore, comparison expressions can be used directly in ordinary conditional tests; if a program requires a strict Boolean type, the result should be explicitly checked or converted.

III. Object Rules for Comparison Operations

Comparison operators do not apply the same rules to all types. Different data types have their own comparison semantics.

1. Numeric Comparison

Integers, floating-point numbers, and complex numbers follow somewhat different comparison rules.

Integers can be compared directly:

print(10 > 5)
# True

Integers and floating-point numbers can be compared numerically:

print(10 == 10.0)
# True

print(10 < 10.5)
# True

Complex numbers do not support ordering comparisons:

a = 3 + 4j
b = 5 + 2j

print(a == b)
# False

# Not supported:
# print(a > b)

Complex numbers can be compared for equality and inequality, but the greater-than, less-than, and other ordering comparison operators cannot be used directly.

2. String Comparison

Python compares strings using lexicographical ordering, comparing characters one by one according to their Unicode code points.

print("apple" < "banana")
# True

print("Python" == "Python")
# True

String comparison is case-sensitive:

print("Python" == "python")
# False

When case needs to be ignored, you can use casefold():

a = "Python"
b = "python"

print(a.casefold() == b.casefold())
# True

For scenarios that must follow the collation rules of a specific locale, you should not simply rely on the default string comparison; instead, use an appropriate localized sorting approach.

3. Comparing Lists and Tuples

Lists and tuples support element-by-element lexicographical comparison.

Comparison starts with the first element:

  1. If the current elements are not equal, the result of comparing them determines the overall result.
  2. If the current elements are equal, comparison continues with the next element.
  3. If all elements at shared positions are equal, the shorter sequence is less than the longer one.
  4. If both the length and the elements are the same, the two sequences are equal.

Example:

print([1, 2, 3] < [1, 2, 4])
# True

print([1, 2] < [1, 2, 0])
# True

print((1, 2) == (1, 2))
# True

If the elements at corresponding positions cannot be compared as required, the whole comparison may raise a TypeError.

4. Comparing Dictionaries and Sets

Dictionaries do not support ordinary ordering comparisons:

a = {"x": 1}
b = {"x": 2}

print(a == b)
# False

# Not supported:
# print(a < b)

Sets support equality tests as well as subset and superset relationship tests:

a = {1, 2}
b = {1, 2, 3}

print(a == b)
# False

print(a < b)
# True

print(a <= b)
# True

For sets:

  • < means proper subset.
  • <= means subset.
  • > means proper superset.
  • >= means superset.

These set operations express containment relationships, not a size ordering based on the number of elements.

For example:

a = {1, 2, 3}
b = {4, 5}

print(a > b)
# False

Even if a has more elements, it does not mean that it is a superset of b.

IV. Chained Comparisons

Python supports chained comparisons, allowing multiple comparison operators to be used in succession.

For example:

age = 25

print(18 <= age <= 60)
# True

This is equivalent to:

18 <= age and age <= 60

But chained comparisons also have an important feature: the middle operand is evaluated only once.

1. How Chained Comparisons Are Evaluated

x = 50

result = 0 < x < 100

print(result)
# True

It means:

0 < x and x < 100

Chained comparisons are very suitable for expressing:

  • Numeric ranges.
  • Age ranges.
  • Time ranges.
  • Score ranges.
  • Valid input ranges.

2. Chaining Multiple Conditions

score = 85

if 0 <= score <= 100:
    print("成绩有效")

If ordinary logical operators are used, it can also be written as:

if score >= 0 and score <= 100:
    print("成绩有效")

Chained comparisons are usually more concise.

3. The Middle Expression Is Evaluated Only Once

def get_value():
    print("获取数值")
    return 50

result = 0 < get_value() < 100

Output:

获取数值

get_value() is executed only once.

But if you write it directly as:

result = 0 < get_value() and get_value() < 100

The function may be executed twice.

Therefore, when the middle operand contains a function call, chained comparison is not only more concise but may also avoid duplicate computation or duplicate side effects.

4. Chained Comparisons Do Not Apply to All Expressions

For example:

a = 1
b = 2
c = 3

print(a < b < c)
# True

This does not mean that, in the mathematical sense, any number of conditions can be combined arbitrarily.

Each comparison relationship in a chained comparison must conform to Python's comparison rules. In scenarios involving complex conditions, parentheses and logical operators should be preferred to express intent clearly.

V. Identity Comparison and Value Comparison

There are two sets of comparison operations in Python that are easily confused:

  • ==: Checks whether values are equal.
  • is: Checks whether two references point to the same object.

Although is and is not are also comparison operations, they are not ordinary value comparison operators.

1. Equal Values Do Not Mean the Same Object

a = [1, 2, 3]
b = [1, 2, 3]

print(a == b)
# True

print(a is b)
# False

The two lists have the same contents, but they are two independent objects.

2. Two Names Can Point to the Same Object

a = [1, 2, 3]
b = a

print(a == b)
# True

print(a is b)
# True

At this point, both a and b reference the same list object.

3. Why None Should Be Checked Using is

None is a singleton object in Python that represents a null value.

Recommended:

result = None

if result is None:
    print("没有返回结果")

Not recommended:

if result == None:
    print("没有返回结果")

The reason is that custom objects can overload ==, but they cannot change the object identity semantics of is.

Therefore, when checking for None, use:

if value is None:
    pass

if value is not None:
    pass

4. Do Not Use is to Check Whether Numbers or Strings Are Equal

a = 100
b = 100

print(a == b)
# True

Some Python implementations may cache or reuse certain integer and string objects, so:

print(a is b)

It may return True, but you cannot rely on this behavior.

Correct principle:

  • Comparing values: use ==.
  • Checking whether something is None: use is None.
  • Checking object identity: use is only when it is truly needed.

VI. Classification of Logical Operators

Python provides three main logical operators:

Operator Name Function
and Logical AND Returns the right operand when both sides are true
or Logical OR Returns the left side when it is true; otherwise returns the right side
not Logical NOT Negates the truth value of the operand and returns a boolean

Logical operators are commonly used for:

  • User permission checks.
  • Input data validation.
  • Combining business rules.
  • Program flow control.
  • Null value handling.
  • Conditional filtering.

VII. The Logical AND Operator and

and is used to combine multiple conditions. When the left operand is true, it continues evaluating the right operand; when the left operand is false, it directly returns the left operand.

1. Basic Rules of and

Left Side Right Side Result
True True True
True False False
False True False
False False False

Example:

print(True and True)
# True

print(True and False)
# False

print(False and True)
# False

2. Practical Applications of and

For example, a user must satisfy both the age and ticket conditions in order to enter:

age = 25
has_ticket = True

if age >= 18 and has_ticket:
    print("允许进入")
else:
    print("不允许进入")

Only when both conditions hold is the overall condition true.

3. and Returns an Operand

This is where Python differs from some other languages.

and does not necessarily return True or False; instead, it returns one of the operands involved in the operation.

print(10 and 20)
# 20

print(0 and 20)
# 0

print("Python" and "AI")
# AI

print("" and "AI")
# ""

Its rules can be summarized as follows:

  • If the left side is false, return the left side.
  • If the left side is true, return the right side.

Therefore, and can be used both for combining conditions and for selecting a value based on truthiness.

4. Using and for Safe Checks

user = None

if user is not None and user.is_active:
    print("用户处于激活状态")

When user is None, the left condition is false, the right side is not executed, and therefore no attribute of None is accessed.

This pattern is a very common way of writing defensive conditional checks in Python.

VIII. The Logical OR Operator or

or is used to combine multiple conditions; as long as one operand is true, the entire logical expression can evaluate to true.

1. Basic Rules of or

Left Side Right Side Result
True True True
True False True
False True True
False False False

Example:

print(True or True)
# True

print(True or False)
# True

print(False or True)
# True

print(False or False)
# False

2. Practical Applications of or

For example, a user can enjoy a discount as long as they have VIP status or a valid coupon:

is_vip = False
has_coupon = True

if is_vip or has_coupon:
    print("可以享受优惠")

3. or Returns an Operand

or likewise does not guarantee a Boolean return value.

print(10 or 20)
# 10

print(0 or 20)
# 20

print("" or "默认值")
# 默认值

print("Python" or "默认值")
# Python

The rule is:

  • If the left side is truthy, return the left side.
  • If the left side is falsy, return the right side.

4. Using or to Provide a Default Value

username = ""

display_name = username or "匿名用户"

print(display_name)
# 匿名用户

This is a concise way to handle default values.

However, note the following:

count = 0

result = count or 10

print(result)
# 10

If 0 is a legitimate value, this pattern may produce incorrect business results.

Therefore, or cannot be treated as a universal null check for every scenario.

If you only want to use a default value when a variable is None, you should test for it explicitly:

count = 0

result = 10 if count is None else count

print(result)
# 0

IX. The Logical NOT Operator not

not is used to invert the truth value of an object.

1. Basic Rules of not

Truth value of operand Result of not
True False
False True

Example:

print(not True)
# False

print(not False)
# True

2. not Can Be Applied to Any Object

print(not 0)
# True

print(not 1)
# False

print(not "")
# True

print(not "Python")
# False

print(not [])
# True

not first evaluates the truth value of the object, then returns the opposite Boolean result.

3. not Always Returns a bool

Unlike and and or, the result returned by not is always a Boolean value.

result = not "Python"

print(result)
# False

print(type(result))
# <class 'bool'>

4. Practical Uses of not

items = []

if not items:
    print("没有数据")

It can also be used to check that a condition does not hold:

is_active = False

if not is_active:
    print("账户未激活")

For complex conditions, judicious use of parentheses can make the logic clearer:

if not (age >= 18 and has_ticket):
    print("不满足进入条件")

X. Python's Truth Value Testing Mechanism

Logical operators can work with non-Boolean objects because Python provides a unified truth value testing mechanism (Truth Value Testing).

Any object can be tested in a context that requires a Boolean decision.

1. Common Falsy Objects

The following objects are generally treated as falsy:

Type Example of a falsy value
Boolean False
Null value None
Integer 0
Float 0.0
Complex number 0j
String ""
List []
Tuple ()
Dictionary {}
Set set()
Custom object __bool__() returns False, or __len__() returns 0

Example:

values = [
    False,
    None,
    0,
    0.0,
    0j,
    "",
    [],
    (),
    {},
    set()
]

for value in values:
    print(bool(value))

When these objects are converted to Boolean values, the result is False in every case.

2. Truth Value Evaluation Examples

print(bool(100))
# True

print(bool(-1))
# True

print(bool("0"))
# True

print(bool("False"))
# True

print(bool([0]))
# True

Pay special attention to the following:

  • The numeric zero is falsy, but the string "0" is truthy.
  • The Boolean value False is falsy, but the string "False" is truthy.
  • An empty list is falsy, but a list containing one element is truthy, even if that element is 0.

What is being evaluated is whether the object itself is empty or satisfies the truth-value rules, not the literal meaning of the text inside the object.

3. Differences Between bool() and Logical Operators

bool() explicitly converts an object to a Boolean value:

print(bool("Python"))
# True

In contrast, and and or return the original operands:

print("Python" and 100)
# 100

not, however, always returns a Boolean value:

print(not "Python")
# False

The three have different semantics and should not be conflated.

11. Truth Value Evaluation for Custom Objects

Python allows custom objects to define their own truth-value rules.

This is mainly implemented through two special methods:

  • __bool__(): Defines the Boolean value of the object.
  • __len__(): Defines the length of the object.

1. Using bool()

If an object implements __bool__(), Python gives it priority when performing a truth value test.

class User:
    def __init__(self, active):
        self.active = active

    def __bool__(self):
        return self.active


user1 = User(True)
user2 = User(False)

print(bool(user1))
# True

print(bool(user2))
# False

__bool__() must return an actual bool object; otherwise, it will raise TypeError.

2. Using len()

If __bool__() is not defined but __len__() is, Python determines the truth value based on length.

A length of zero is falsy; a nonzero length is truthy.

class Collection:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)


a = Collection([])
b = Collection([1, 2, 3])

print(bool(a))
# False

print(bool(b))
# True

__len__() must return a non-negative integer.

3. When Both Methods Exist

If an object implements both __bool__() and __len__(), the truth value test gives priority to __bool__().

class Example:
    def __bool__(self):
        return False

    def __len__(self):
        return 10


obj = Example()

print(bool(obj))
# False

Even if the object's length is 10, __bool__() still determines its truth value.

4. When Neither Method Is Defined

If an object implements neither __bool__() nor __len__(), it is considered truthy by default.

class User:
    pass


user = User()

print(bool(user))
# True

5. Execution Flow of Truth Value Testing

你这条消息里没有明确的问题——我按“审阅这段图文”来理解,先给出结论,再列细节。 **流程图结论:逻辑正确。** `__bool__` 优先、非 bool 返回值抛 `TypeError`、不回退到 `__len__`,这几点都对。有三处可以更精确: 1. **节点 B 的措辞**:`__bool__` 是沿类型 MRO 查找的,实例属性 `self.__bool__ = ...` 不生效。建议写成“类型上是否可找到 `__bool__`”。 2. **`__len__` 分支缺少异常路径**:`__len__` 返回值不是整数 → `TypeError`;返回负数 → `ValueError`。流程图里 H → J 是直线,实际上这里会分叉。 3. 节点 I“默认视为 True”成立,但前提是既没有 `__bool__` 也没有 `__len__`(`__len__` 返回 0 也会是 False)。 **正文结论:表述正确,但有一处会误导读者。** `and`/`or` 返回的是**操作数本身**,不是布尔值: ```python 0 and check() # 0,不是 False "" or get_default() # "默认值" [] or [1, 2] # [1, 2] ``` 你的两个示例都恰好用了 `True`/`False` 和 `"Python"`,这一点被掩盖了,建议补一个 `0` 或 `[]` 的例子,否则读者容易以为结果是 `bool`。另外可顺带提一句 `and` 优先级高于 `or`。 **第 4 节只写了一句话就断了**(“短路求值也意味着某些函数可能根本不会执行。”)。这一节真正要讲的是副作用丢失的风险,典型如: ```python # 本意是"取出并处理",但空列表时 pop 抛异常,非空时返回元素本身参与判断 while stack and stack.pop() is not None: ... ``` 或者反过来的坑:`log() or save()` 这种写法里 `save()` 可能永远不执行而无人察觉。 需要我把第 4 节补完,或者按上面三点改一版流程图(加 `__len__` 的异常分支)吗?
def update_status():
    print("更新状态")
    return True

enabled = False

result = enabled and update_status()

Here, update_status() will not run.

Therefore, do not hide side effects that must be executed on the right side of and or or.

Not recommended:

# Not recommended: whether update_status executes depends on enabled
enabled and update_status()

A clearer way:

if enabled:
    update_status()

5. Short-circuit evaluation and exception avoidance

Short-circuiting can also be used to avoid certain invalid operations:

numbers = []

if numbers and numbers[0] > 10:
    print("第一个元素大于 10")

When the list is empty, numbers is false, so numbers[0] on the right side will not be evaluated, and therefore IndexError will not be raised.

XIII. Precedence of logical operators

When an expression contains multiple logical and comparison operators, Python determines the evaluation order according to precedence.

The common precedence order from high to low is as follows:

Precedence Operator Description
Higher <、>、<=、>=、==、!= Comparison operations
is、is not Identity comparison
in、not in Membership test
not Logical NOT
and Logical AND
Lower or Logical OR

Comparison operators, identity operators, and membership operators are at the same precedence level and support chained comparison syntax.

1. not has higher precedence than and

a = True
b = False

result = not a and b

print(result)
# False

Its evaluation structure is equivalent to:

(not a) and b

rather than:

not (a and b)

2. and has higher precedence than or

a = True
b = False
c = True

result = a or b and c

print(result)
# True

It is equivalent to:

a or (b and c)

3. Use parentheses to clarify logical relationships

For complex conditions, it is recommended to use parentheses explicitly:

if (
    (age >= 18 and has_ticket)
    or is_vip
):
    print("允许进入")

Parentheses can make business logic more intuitive and also help avoid misunderstandings about precedence.

XIV. Logical Operators and Conditional Evaluation

Comparison operators and logical operators are usually used together with statements such as if, elif, and while.

1. Using comparison operators in if