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,orandnotwork, including short-circuit evaluation - how
intests membership and whyisis 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.
Table of Contents
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
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 2500 == 2500 | True |
!= | not equal to | 2500 != 2500 | False |
> | greater than | 2500 > 2000 | True |
< | less than | 2500 < 2000 | False |
>= | greater than or equal to | 2500 >= 2500 | True |
<= | less than or equal to | 2500 <= 1000 | False |
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 <= 60reads like maths: “age is between 18 and 60”. The expressions reference saysx < y <= z“is equivalent tox < 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"isTrue, and"SAVE10"is not equal to"save10". 5 == 5.0isTrue, because numbers of different types compare by value. But the text"5"is never equal to the number5. Convert first, as in Lesson 8.
Logical operators: and, or, not
and, or and not combine True/False answers.
| Expression | Result is True when… |
|---|---|
a and b | both a and b are true |
a or b | at least one of them is true |
not a | a 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 > 0isFalse, soandalready knows the answer is false and never runstotal / items. There is noZeroDivisionError.andandorreturn one of the two values, not alwaysTrueorFalse. The reference saysx or yreturnsxifxis true, otherwisey. An empty name is false, soname or "Guest"gives"Guest". This is a common way to set a default value.notalways returns a realTrueorFalse.
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:
| Order | Operators | Description |
|---|---|---|
| 1 | ( ) | brackets |
| 2 | ** | power |
| 3 | -x, +x | negative, positive |
| 4 | *, /, //, % | multiply, divide, floor divide, remainder |
| 5 | +, - | add, subtract |
| 6 | ==, !=, <, >, <=, >=, in, not in, is, is not | comparisons, membership, identity |
| 7 | not | logical NOT |
| 8 | and | logical AND |
| 9 | or | logical 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, so2 + 12is14. Brackets change it to5 4.2 3 2runs right to left:3 2is9, then2 9is512.-3 2is-9, becauseruns before the minus sign: it means-(3 2). Write(-3) 2to square a negative number.10 - 4 - 3runs left to right:6 - 3is3.
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:givesSyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?. Use==to compare. - Comparing text with a number.
"21" > 18givesTypeError: '>' not supported between instances of 'str' and 'int', and"5" == 5is quietlyFalse. Convert withint()first. - Using
isto compare values.count is 5givesSyntaxWarning: "is" with 'int' literal. Did you mean "=="?. KeepisforNone. - Forgetting that
andruns beforeor.a and b or cmeans(a and b) or c. Add brackets when you meana and (b or c). - Writing
-32 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>=returnTrueorFalse, and can be chained like18 <= age <= 60.and,orandnotcombine conditions;and/orstop early (short-circuit) and return one of their values.intests membership;istests identity, so useisonly withNone.- Precedence runs from
**down toor; 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
- Expressions: comparisons, Boolean operations and operator precedence (Python language reference)
- Built-in Types: comparisons and Boolean operations (Python docs)
- PEP 8: Style Guide for Python Code, whitespace around operators
- Python downloads page (python.org)





