Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
Python's six operator drawers with real output: 17 sweets shared by 5 friends for /, // and %, and/or short-circuiting, += and friends, in on lists and strings, is versus == with one shared list, and the precedence ladder.
What you will learn
- Use /, //, % and ** correctly, including floor division on negative numbers
- Combine comparisons with and, or and not, and predict what and/or return
- Tell == (same value) from is (same object) and use is for None
- Work out the order of a mixed expression with the precedence ladder
Before you start
- Python Data Types, Variables and Strings
- Python Lists, Tuples, Sets and Dicts
Variables, strings and collections hold values. Operators are what let you work on them: calculate, compare and combine. An operator is a small symbol that does a job on some values and gives you one value back. a + b takes 17 and 5 and hands back 22.
Think of a toolbox where each tool has one job. Python's toolbox has six drawers: arithmetic, comparison, logical, assignment, membership and identity. Open them one at a time, then see which one goes first when they're mixed.
Arithmetic and the kinds of division
a = 17
b = 5
print(a + b)
print(a - b)
print(a * b)
print(a / b)
22
12
85
3.4
A single slash always gives a float, even when the numbers divide evenly. Division is where it gets interesting, because Python has a few kinds. Picture 17 sweets shared between 5 friends:
a = 17
b = 5
print(a / b)
print(a // b)
print(a % b)
print(a ** 2)
print(-17 // 5)
print(divmod(a, b))
3.4
3
2
289
-4
(3, 2)
/gives the exact answer, 3.4. But you can't hand out 0.4 of a sweet.//is floor division: everyone gets 3 whole sweets.%is modulo, the remainder: 2 left over. It has nothing to do with percentages.**is power: 17 squared is 289.-17 // 5gives -4, not -3. Floor division always rounds down, towards the smaller number; it doesn't just chop off the decimals.divmodgives both answers at once.
Dividing by zero
items = 12
people = 0
print(items // people)
Traceback (most recent call last):
File "S01L07_Operators\zero_division.py", line 4, in <module>
print(items // people)
~~~~~~^^~~~~~~~
ZeroDivisionError: integer division or modulo by zero
Dividing by zero doesn't give a wrong answer. It's an error, and the program stops there. / and % behave the same way.
Comparison operators
age = 18
score = 74.5
name = "Alice"
print(age == 18)
print(age != 21)
print(score > 80)
print(score <= 74.5)
print(name == "Alice")
print(18 <= age < 65)
True
True
False
True
True
True
A comparison asks a question, and the answer is always True or False. One = stores a value; == asks whether two values are the same. <= is happy with equal, comparisons work on strings too, and you can chain them like maths: 18 <= age < 65.
A float surprise
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
0.30000000000000004
False
True
Floats are stored in binary, so many decimals carry a tiny error. When you compare floats, don't trust == on its own; round them first.
Logical operators: and, or, not
age = 20
has_id = True
temperature = 37.8
can_enter = age > 18 and has_id
fever = temperature > 37.5 or temperature < 35
blocked = not has_id
print(can_enter)
print(fever)
print(blocked)
True
True
False
For a concert you need to be over 18 and have an ID. With and, both sides must be True. With or, one True side is enough: the temperature is above 37.5, so it's a fever even though it isn't below 35. not flips a value. Say the rule in plain words first, and the code almost writes itself.
What and and or really give back
name = ""
print(name or "Guest")
print("Alice" or "Guest")
print(0 and 5)
print(3 and 5)
Guest
Alice
0
5
Most beginners miss this: these two don't always return True or False. They return one of the values. Python reads from the left and stops as soon as it knows the answer. An empty string and 0 count as false; most other values count as true.
So name or "Guest" moves past the empty string and gives "Guest", a neat way to set a default. 0 and 5 stops at 0, because and needs both sides and 0 already failed. or gives the first true value it finds; and gives the first false one, or else the last value.
Assignment operators
score = 10
print(score)
score += 5
print(score)
score *= 2
print(score)
score -= 4
print(score)
score //= 3
print(score)
score **= 2
print(score)
10
15
30
26
8
64
score += 5 is short for score = score + 5. Each of these reads the old value, works out a new one and stores it back. 26 floor-divided by 3 keeps 8. Python has no ++, so to count up you write += 1.
Membership: in
skills = ["Python", "SQL", "React"]
name = "StudyEasy"
print("Python" in skills)
print("Java" not in skills)
print("Easy" in name)
print("easy" in name)
True
True
True
False
in asks whether something is inside something else: an item in a list, or letters in a string. Strings are case sensitive, so "easy" with a small e isn't found.
Identity: is versus ==
Think about two friends who share one notebook. Two names, one notebook: if one writes on a page, the other sees it. A third friend buys a notebook that looks the same, with the same words in it. Same content, separate notebook. Asking whether the content matches is ==. Asking whether it's the very same notebook is is.
y = x adds a second name; [1, 2, 3] written again builds a new list.x = [1, 2, 3]
y = x
z = [1, 2, 3]
print(x is y)
print(x is z)
print(x == z)
y.append(4)
print(x)
print(z)
True
False
True
[1, 2, 3, 4]
[1, 2, 3]
y = x doesn't make a new list; y is a second name for the same one. z looks the same, but those square brackets build a brand new list. The proof is the last two lines: appending through y changes the list x sees, and z stays as it was.
Where is gets used
result = None
print(result is None)
print(result is not None)
True
False
Day to day, you use is mostly with None, Python's way of saying "no value". There's only one None object, so is asks the right question. The rule: use == to compare values, and keep is for None or for when you really want to know it's the same object.
The precedence ladder
When several operators sit in one line, higher rungs go first:
- Brackets
( ), which beat everything - Power
** *,/,//,%+,-- Comparisons, with
inandis not, thenand, thenor
Assignment happens after all of that, which is why the right side is worked out first.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 * 3 ** 2)
print(10 - 4 - 3)
print(2 + 3 > 4 and 10 % 3 == 1)
print(not 1 > 2 or False)
14
20
18
3
True
True
2 + 3 * 4: multiply first, 12, then plus 2.2 * 3 ** 2: power before multiply, 9 times 2.10 - 4 - 3: same rung, so left to right: 6, then 3.- The mixed line: arithmetic gives 5 and 1, comparisons give True and True, then
andgives True. not 1 > 2 or False: the comparison is False,notflips it, and True or False is True.
You don't have to memorise all of it. When a line looks unclear, add brackets, and whoever reads it next will thank you.
Quick recap
| Operator | Does | Example |
|---|---|---|
/ | exact division, always a float | 17 / 5 is 3.4 |
// | floor division, rounds down | -17 // 5 is -4 |
% | remainder | 17 % 5 is 2 |
** | power | 17 ** 2 is 289 |
and / or | return one of the values | "" or "Guest" is "Guest" |
+= | update in place | score += 5 |
in | is it inside? | "Easy" in "StudyEasy" |
is | same object? | result is None |
Try it yourself
Turn a number of minutes into hours and minutes using // and %. Or prompt an AI tool to do it, and then read every line it gives you.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python for AI: The Five Tools You Actually Need
The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.
Thinking Like a Python Architect in an AI-First World
Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.
Your First Python Program: print, Comments, sep and end
Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.
Set Up PyCharm for Python: Install, First Project and First Run
Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.
