Lesson 27 min read
Operators & Expressions
The math and logic behind every decision your code makes
Arithmetic Operators
Python is basically a super-powered calculator. You've got all the usual suspects — plus, minus, multiply, divide — but also some cool extras that most calculators don't have.
+Addition,-Subtraction,*Multiplication — the classics./True division — always gives you a float:7 / 2→3.5.//Floor division — divides and rounds down to the nearest whole number:7 // 2→3.%Modulo — gives you the remainder after dividing:7 % 2→1. Super handy for checking if a number is even or odd!**Power — exponentiation:2 ** 10→1024.
Arithmetic in Action
Comparison & Logical Operators
Comparison operators let you ask questions about values. The answer is always True or False.
==Equal to (two equals signs — one=is assignment!)!=Not equal to<,>,<=,>=Less/greater than (or equal)
Logical operators let you combine multiple True/False values:
and— Both must be True:True and False→Falseor— At least one must be True:True or False→Truenot— Flips the value:not True→False
Making Comparisons
Operator Precedence
Just like in math class, Python follows an order of operations. Here's the priority from highest to lowest:
()— Parentheses first (always wins)**— Exponentiation*,/,//,%— Multiplication family+,-— Addition family==,!=,<,>, etc. — Comparisonsnot→and→or— Logical (not beats and beats or)
When in doubt, use parentheses! They make your code easier to read AND guarantee the right order.
Precedence Surprises
Note: Think of
and as a strict teacher who needs ALL homework done, and or as a chill teacher who's happy if you did ANY of it. And not? That's the kid who does the opposite of whatever you say.