Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

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 // 5 gives -4, not -3. Floor division always rounds down, towards the smaller number; it doesn't just chop off the decimals.
  • divmod gives 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.

x and y are two names for one list object, z points to a separate list with the same values; x is y is True, x is z is False, x == z is True x y z [1, 2, 3] one object [1, 2, 3] another x is y → True x is z → False x == z → True y.append(4) changes x
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:

  1. Brackets ( ), which beat everything
  2. Power **
  3. *, /, //, %
  4. +, -
  5. Comparisons, with in and is
  6. not, then and, then or

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 and gives True.
  • not 1 > 2 or False: the comparison is False, not flips 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

OperatorDoesExample
/exact division, always a float17 / 5 is 3.4
//floor division, rounds down-17 // 5 is -4
%remainder17 % 5 is 2
**power17 ** 2 is 289
and / orreturn one of the values"" or "Guest" is "Guest"
+=update in placescore += 5
inis it inside?"Easy" in "StudyEasy"
issame 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 7 of 48

Previous
Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
Next post
Python Conditionals and Loops: if/elif/else, for, while, break and continue

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.

On this page

  • Arithmetic and the kinds of division
  • Dividing by zero
  • Comparison operators
  • A float surprise
  • Logical operators: and, or, not
  • What and and or really give back
  • Assignment operators
  • Membership: in
  • Identity: is versus ==
  • Where is gets used
  • The precedence ladder
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.