Skip to content
Python

Python Operators: Comparison, Logical, is vs == and Precedence

Ihsan Ullah · Updated · 9 min read
Python course Lesson 9 cover: Python operators, comparison, logical, is vs == and precedence

Python course · Module 2: Values · Lesson 9 of 63

Quick answer: Python operators are symbols and words that work on values: arithmetic (+, , //), comparison (==, <, >=), logical (and, or, not), membership (in) and identity (is). Comparisons give True or False, and and/or stop as soon as the answer is known. When one line has several operators, precedence decides the order: 2 + 3 4 is 14 because * runs before +. Use brackets to make the order clear.

In this lesson you will learn:

  • the assignment shortcuts +=, -=, *= and //=
  • the six comparison operators and how comparisons can be chained
  • how and, or and not work, including short-circuit evaluation
  • how in tests membership and why is is not the same as ==
  • the operator precedence order, and when to add brackets

Before you start: finish Lesson 8, Python Type Conversion, so you know True, False and None. The arithmetic operators + - * / // % ** were covered in Lesson 6. All examples were run as scripts with Python 3.14.6, and Python 3.15.2, the newest release on python.org, gave the same output.

Assignment operators

Our running example is the checkout of an online shop. A cart total often changes step by step, and Python has a short way to write that.

cart_total = 1200
cart_total += 800
print(cart_total)
cart_total -= 150
print(cart_total)
cart_total *= 2
print(cart_total)
cart_total //= 3
print(cart_total)
2000
1850
3700
1233

cart_total += 800 means cart_total = cart_total + 800. Every arithmetic operator has a version like this: +=, -=, *=, /=, //=, %= and **=. 3700 // 3 is 1233 because // keeps only the whole part.

Comparison operators

A comparison asks a question and answers True or False.

cart_total = 2500
print(cart_total == 2500)
print(cart_total != 2500)
print(cart_total > 2000)
print(cart_total < 2000)
print(cart_total >= 2500)
print(cart_total <= 1000)
True
False
True
False
True
False
OperatorMeaningExampleResult
==equal to2500 == 2500True
!=not equal to2500 != 2500False
>greater than2500 > 2000True
<less than2500 < 2000False
>=greater than or equal to2500 >= 2500True
<=less than or equal to2500 <= 1000False

Remember: = assigns a value, == compares two values.

Chained comparisons, text and mixed types

age = 21
print(18 <= age <= 60)
print("apple" < "banana")
print("Zebra" < "apple")
print("SAVE10" == "save10")
print(5 == 5.0)
print("5" == 5)
True
True
True
False
True
False
  • 18 <= age <= 60 reads like maths: “age is between 18 and 60”. The expressions reference says x < y <= z “is equivalent to x < y and y <= z“.
  • Strings compare letter by letter, using each character’s Unicode number. Capital letters have smaller numbers than small letters, so "Zebra" < "apple" is True, and "SAVE10" is not equal to "save10".
  • 5 == 5.0 is True, because numbers of different types compare by value. But the text "5" is never equal to the number 5. Convert first, as in Lesson 8.

Logical operators: and, or, not

and, or and not combine True/False answers.

ExpressionResult is True when…
a and bboth a and b are true
a or bat least one of them is true
not aa is false
cart_total = 2500
is_member = True
coupon = ""

print(is_member and cart_total >= 2000)
print(is_member and cart_total >= 3000)
print(is_member or cart_total >= 3000)
print(not is_member)
print(coupon == "SAVE10" or cart_total > 2000)
True
False
True
False
True

The second line is False because one side, cart_total >= 3000, is false, and and needs both. The third line is True because or needs only one.

Short-circuit evaluation

Python reads and and or from left to right and stops as soon as it knows the answer. This is called short-circuit evaluation.

items = 0
total = 0
print(items > 0 and total / items > 100)

name = ""
print(name or "Guest")
name = "Ayesha"
print(name or "Guest")
print(not "Ayesha")
False
Guest
Ayesha
False
  • items > 0 is False, so and already knows the answer is false and never runs total / items. There is no ZeroDivisionError.
  • and and or return one of the two values, not always True or False. The reference says x or y returns x if x is true, otherwise y. An empty name is false, so name or "Guest" gives "Guest". This is a common way to set a default value.
  • not always returns a real True or False.

Membership: in and not in

in checks whether one value is inside another. With strings, it checks for a piece of text.

coupon = "EID-SAVE10"
print("SAVE" in coupon)
print("save" in coupon)
print("FREE" not in coupon)
print("" in coupon)
True
False
True
True

The check is case sensitive, so "save" is not found. The last line surprises people: the reference says empty strings “are always considered to be a substring of any other string”. You will use in with lists in Lesson 15.

Identity: is vs ==

== asks “do these two have the same value?”. is asks “are these the same object in memory?”. Lists (Lesson 15) show the difference clearly. A list is a collection written in square brackets.

cart_a = ["pen", "book"]
cart_b = ["pen", "book"]
cart_c = cart_a
print(cart_a == cart_b)
print(cart_a is cart_b)
print(cart_c is cart_a)

phone = None
print(phone is None)
print(phone is not None)
True
False
True
True
False

cart_a and cart_b have the same contents, so == is True. But they are two separate lists, so is is False. cart_c = cart_a puts a second label on the same list (as you saw with variables in Lesson 5), so cart_c is cart_a is True.

The rule for beginners is simple: use == to compare values, and use is only with None (x is None, x is not None). Python even warns you when you use is with a number:

count = 5
print(count is 5)
/home/learner/python-course/err2_is_literal.py:2: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
  print(count is 5)
True

It printed True this time, but is with numbers and strings is not reliable. Write count == 5.

Operator precedence

When an expression has several operators, Python runs them in a fixed order called precedence. This is a shortened version of the table in the expressions reference, from first to last:

OrderOperatorsDescription
1( )brackets
2**power
3-x, +xnegative, positive
4*, /, //, %multiply, divide, floor divide, remainder
5+, -add, subtract
6==, !=, <, >, <=, >=, in, not in, is, is notcomparisons, membership, identity
7notlogical NOT
8andlogical AND
9orlogical OR

Operators on the same row run from left to right, except **, which runs from right to left.

print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-3 ** 2)
print((-3) ** 2)
print(10 - 4 - 3)
14
20
512
-9
9
3
  • 2 + 3 * 4: first, so 2 + 12 is 14. Brackets change it to 5 4.
  • 2 3 2 runs right to left: 3 2 is 9, then 2 9 is 512.
  • -3 2 is -9, because runs before the minus sign: it means -(3 2). Write (-3) 2 to square a negative number.
  • 10 - 4 - 3 runs left to right: 6 - 3 is 3.

Precedence with and/or

and runs before or. This can change the meaning of a rule. Our shop rule: “a member gets free delivery if the cart is 2,000 or more, or if they have the coupon SAVE10”.

is_member = False
cart_total = 500
coupon = "SAVE10"

print(is_member and cart_total >= 2000 or coupon == "SAVE10")
print(is_member and (cart_total >= 2000 or coupon == "SAVE10"))
print(not cart_total > 1000)
True
False
True

Without brackets, Python reads the first line as (is_member and cart_total >= 2000) or coupon == "SAVE10", so anyone with the coupon gets free delivery, even a non-member. The brackets in the second line keep the rule “members only”. In the third line, not runs after the comparison: not (500 > 1000) is True. When in doubt, add brackets; PEP 8 also suggests spacing like x = x*2 - 1 to show which operators run first.

Try it yourself

Exercise 1: A simple email check

For email = "sara@mail.com", print True if the email contains "@" and does not contain a space. Test it again with "sara mail.com".

Exercise 2: Predict the results

Write down what each line prints, then run it.

print(10 + 2 * 3)
print(10 / 2 * 5)
print(2 ** 2 ** 3)
print(not 5 > 3 or 2 > 1)
print(7 % 3 == 1 and 4 > 5)

Exercise 3: Fix the crash

This line stops with ZeroDivisionError: division by zero when items is 0. Change the order so it prints False instead.

items = 0
total = 0
print(total / items > 100 and items > 0)

Solutions

Solution 1

email = "sara@mail.com"
looks_valid = "@" in email and " " not in email
print("Looks valid:", looks_valid)

email = "sara mail.com"
looks_valid = "@" in email and " " not in email
print("Looks valid:", looks_valid)
Looks valid: True
Looks valid: False

The second email has no @ and has a space, so and gives False. (A real email check needs more rules; this is only practice.)

Solution 2

print(10 + 2 * 3)
print(10 / 2 * 5)
print(2 ** 2 ** 3)
print(not 5 > 3 or 2 > 1)
print(7 % 3 == 1 and 4 > 5)
16
25.0
256
True
False

2 * 3 runs first (16); / and run left to right, 5.0 5 (25.0); 2 ** 8 (256); (not True) or True (True); True and False (False).

Solution 3

items = 0
total = 0
print(items > 0 and total / items > 100)
False

With the safe check first, and stops at items > 0 and never divides by zero.

Common mistakes

  • Using = instead of ==. if cart_total = 2500: gives SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?. Use == to compare.
  • Comparing text with a number. "21" > 18 gives TypeError: '>' not supported between instances of 'str' and 'int', and "5" == 5 is quietly False. Convert with int() first.
  • Using is to compare values. count is 5 gives SyntaxWarning: "is" with 'int' literal. Did you mean "=="?. Keep is for None.
  • Forgetting that and runs before or. a and b or c means (a and b) or c. Add brackets when you mean a and (b or c).
  • Writing -3 2 to square a negative number. It gives -9. Write (-3) 2.

Frequently asked questions

What is the difference between is and == in Python?

== checks whether two values are equal, while is checks whether two names point to the very same object. Two separate lists with the same items are == but not is. Use == for values and is only for None.

What is the order of operations in Python?

Brackets first, then **, then the unary minus, then *, /, // and %, then + and -, then comparisons, and finally not, and and or. Operators of the same level run from left to right, except **, which runs from right to left.

Does Python use && and || for and/or?

No. Python uses the words and, or and not. Writing is_member && True gives SyntaxError: invalid syntax. The symbols & and | do exist, but they are bitwise operators for a different job, so beginners should always use the words.

Summary

  • +=, -=, *= and the others update a variable in one step.
  • ==, !=, <, >, <= and >= return True or False, and can be chained like 18 <= age <= 60.
  • and, or and not combine conditions; and/or stop early (short-circuit) and return one of their values.
  • in tests membership; is tests identity, so use is only with None.
  • Precedence runs from ** down to or; brackets make your intention clear.

Related lessons: Python variables, Python numbers, Python if, elif and else.

Next lesson

Next: Lesson 10, Python input() Function: Read User Input and Print Output.

Sources

Ihsan Ullah

Written & tested by Ihsan Ullah

Data analyst with 3 years of experience and a Bachelor's degree in Computer Science. I write clear, practical guides on data, SQL, Python and AI.

More about me →

Leave a comment

Your email address will not be published. Required fields are marked *