Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 149 ยท Operators

Comparison and Logical Operators

Compare values with ==, !=, < and >, chain comparisons like 0 < x < 10, and combine conditions with and, or and not, including short-circuit evaluation.

Programs constantly ask questions. Is the cart empty? Is the user old enough? Did the score beat the record? Comparison operators ask these questions and answer with True or False. Logical operators then combine several answers into one: "is the user logged in and an admin?"

Together they form the conditions you'll write in every if statement and while loop. This lesson covers both groups, Python's elegant chained comparisons, and the short-circuit behavior of and and or, which is useful well beyond simple Booleans.

The comparison operators

Operator Meaning Example Result
== equal to 5 == 5 True
!= not equal to 5 != 3 True
< less than 2 < 9 True
> greater than 2 > 9 False
<= less than or equal to 4 <= 4 True
>= greater than or equal to 3 >= 4 False

Every comparison produces a bool, which you met in Booleans and Truthiness.

Python Comparing numbers and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few results deserve a closer look:

  • 0.1 + 0.2 == 0.3 is False because floats are approximations, as covered in Numbers. Compare floats with math.isclose(a, b) instead.
  • Strings compare lexicographically: character by character, using each character's Unicode code point. All uppercase letters come before lowercase ones, so "Zebra" < "apple". Use .lower() on both sides for a case-insensitive comparison.
  • "10" < "9" is True because "1" comes before "9". Convert text to numbers first, as shown in Type Conversion.

Warning: = stores a value; == compares two values. Writing if score = 100: is a SyntaxError in Python, which at least stops the bug before it runs.

Comparing different types

== works between any two values; unrelated types are simply not equal, so "5" == 5 is False. Ordering operators like < are stricter: "5" < 5 raises a TypeError, because Python has no sensible way to order text against numbers. Lists and tuples compare item by item, which is how sorted() orders them.

Chained comparisons

In math you write 0 โ‰ค x โ‰ค 100 to say "x is between 0 and 100". Python lets you write exactly that:

Python Chaining comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

a < b < c means a < b and b < c, with b evaluated only once. Chains are clearer than the long form, and they're idiomatic Python. Keep them readable, though: a < b > c is legal but confusing.

Logical operators: and, or, not

Logical operators combine or invert conditions. Python spells them as English words:

  • and is true when both sides are true.
  • or is true when at least one side is true.
  • not flips a value: not True is False.
Python Combining conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Precedence matters here too: not runs first, then and, then or. All three run after comparisons and arithmetic, so x + 1 > 5 and y < 3 needs no parentheses. When you mix and with or, add parentheses anyway; they make your intent obvious.

Short-circuit evaluation

Python evaluates and and or from left to right and stops as soon as the answer is known:

  • A and B: if A is falsy, the result is already false, so B never runs.
  • A or B: if A is truthy, the result is already true, so B never runs.

This is called short-circuiting, and it lets the left side protect the right side:

Python Short-circuiting protects you

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the last example, total / count would raise ZeroDivisionError. Because count != 0 is False, Python never evaluates the division. Put the cheap or protective check on the left.

and and or return a value, not just True or False

Here's a Python detail that surprises people coming from other languages: and and or don't convert their result to a bool. They return one of the operands:

  • A or B returns A if it's truthy, otherwise B.
  • A and B returns A if it's falsy, otherwise B.

not is the exception; it always returns True or False.

Python What and/or actually return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This makes or a quick way to supply a default, as in name or "Guest". Remember the caveat from None: or replaces every falsy value, including 0 and "". If 0 is a valid value, use value if value is not None else default.

Tip: In an if condition, the returned operand is judged by truthiness, so everything works as you'd expect. The "returns an operand" behavior only matters when you store or print the result.

Beware of x == 1 or 2

A classic mistake is to write if color == "red" or "blue":. Python reads that as (color == "red") or "blue", and since "blue" is a non-empty string, the condition is always truthy. Write color == "red" or color == "blue", or better, color in ("red", "blue"). The in operator is covered in Membership and Identity Operators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does 3 < 7 < 5 evaluate to?

    The chain means 3 < 7 and 7 < 5. The second part is False, so the whole chain is False.
  2. 2. What does "" or "N/A" return?

    or returns the first truthy operand. The empty string is falsy, so the result is "N/A".
  3. 3. In items and items[0] > 3, what happens when items is an empty list?

    An empty list is falsy, so and short-circuits and returns the empty list without touching items[0].
  4. 4. Why is if size == "S" or "M": a bug?

    Python reads it as (size == "S") or "M". Use size in ("S", "M") instead.
  5. 5. Which operator is evaluated first in not a or b and c?

    not has the highest precedence of the three, then and, then or: (not a) or (b and c).

Summary

  • ==, !=, <, >, <= and >= compare values and return True or False.
  • Strings compare character by character by code point, so uppercase sorts before lowercase and "10" < "9".
  • Chained comparisons like 0 <= x <= 100 mean 0 <= x and x <= 100.
  • and, or and not combine conditions; precedence is not, then and, then or.
  • and and or short-circuit and return one of their operands; not always returns a bool.
  • x == "a" or "b" is always truthy; use x in ("a", "b").

Next: Assignment Operators and the Walrus, shortcuts for updating variables and assigning inside expressions.