Operators and Expressions
Published by Brayan K
Learn how to perform calculations, compare values, and combine conditions using Python's operators.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
The seven arithmetic operators
An operator is a symbol, or a word such as and, that Python applies to values. Put values and operators together, as in price * 3, and you have an expression: something Python works out to a single value. These seven do arithmetic:
| Operator | What it does |
|---|---|
| + | adds |
| - | subtracts |
| * | multiplies |
| / | divides, and always gives a float |
| // | divides and rounds the result down |
| % | gives the remainder of that division |
| ** | raises to a power |
print(7 + 2, 7 - 2, 7 * 2)
print(7 / 2, 7 // 2, 7 % 2)
print(7 ** 2)
print(8 / 2)
# ✅ Expected output:
# 9 5 14
# 3.5 3 1
# 49
# 4.0The last line is the one that catches people out: / gives a float even when the division comes out exactly, so the answer has a .0 on the end. Use // when you need a whole number.
Dividing by zero has no answer, so Python stops the program:
print(10 / 0)
# ✅ Expected error:
# ZeroDivisionError: division by zeroAn operator also has to make sense for the types it's given. Subtracting a number from text doesn't, and the error names the operator and both types:
print("10" - 5)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for -: 'str' and 'int'The fix is to turn the text into a number first, with int("10"), as Variables and Data Types shows. Two operators do work on text, and they do something different there: + joins two strings and * repeats one. That's why a number that arrives as text, as everything from input() does, gives a surprising answer instead of an error:
print("3" + "4")
print("3" * 4)
print(3 * 4)
# ✅ Expected output:
# 34
# 3333
# 12Whole parts and remainders: // and %
// and % answer the two questions of whole-number division: how many times does it go in, and what's left over? Packing 20 eggs into boxes of 6:
eggs = 20
boxes = eggs // 6
loose = eggs % 6
print(boxes, loose)
print(17 % 2, 18 % 2)
# ✅ Expected output:
# 3 2
# 1 0The last line is the usual test for odd and even: a number is even when n % 2 is 0.
With negative numbers, "rounds down" means towards minus infinity, not towards zero. Python keeps // and % consistent with each other, so the remainder takes the sign of the number you divide by:
print(-7 // 2, -7 % 2)
print(int(-7 / 2))
# ✅ Expected output:
# -4 1
# -3-3.5 rounds down to -4, not -3. If you want the decimal part dropped instead, which rounds towards zero, int() does that. Because the remainder follows the sign of 2, n % 2 is 1 for every odd number, negative ones included. In JavaScript, C and Java the same remainder is -1, so an odd test written as n % 2 == 1 fails there for negative numbers; in Python it works.
Powers, and three surprises
** raises a number to a power, and a power of 0.5 is a square root. Three things about it surprise most people:
print(2 ** 3, 2 ^ 3)
print(-2 ** 2, (-2) ** 2)
print(2 ** 3 ** 2)
print(9 ** 0.5)
# ✅ Expected output:
# 8 1
# -4 4
# 512
# 3.0- ^ is not a power. It's a bitwise operator that works on the binary digits of whole numbers, so 2 ^ 3 runs without an error and gives the wrong answer for a power.
- ** is applied before a minus sign in front of it, so -2 ** 2 means -(2 ** 2). Put the negative number in parentheses to square it.
- A chain of ** is worked out from the right, so 2 ** 3 ** 2 is 2 ** 9, not 8 ** 2.
Order of operations
Python follows the order you know from maths: parentheses first, then powers, then *, /, // and %, then + and -. Operators on the same level are worked out left to right, apart from **. The classic bug is an average without parentheses:
a = 4
b = 8
print(a + b / 2)
print((a + b) / 2)
print(10 - 4 - 3)
# ✅ Expected output:
# 8.0
# 6.0
# 3The first print halves only b, because / goes before +. The last one works out (10 - 4) - 3, left to right. When an expression mixes operators, parentheses cost nothing and save the next reader from working the order out. The full order, including the operators below, is in a table further down this page.
Why 0.1 + 0.2 isn't 0.3
Floats are stored in binary, and most decimal fractions, 0.1 among them, have no exact binary form, so Python stores the nearest value it can. Usually the difference stays hidden, but it can add up enough to show, and then == fails:
import math
total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(math.isclose(total, 0.3))
print(round(total, 2))
# ✅ Expected output:
# 0.30000000000000004
# False
# True
# 0.3This isn't a Python bug: every language that uses standard floats gives the same sum. The first line, import math, loads Python's maths functions (importing has its own lesson, Modules and Packages). math.isclose() asks whether two floats are equal to within a tiny tolerance, which is the right question for floats, and round(total, 2) tidies a float for display. For money, where every cent has to be exact, the Decimal type in Numbers: int, float, Decimal & Fraction stores decimal values exactly.
Comparing values
A comparison asks a question and gives True or False. There are six: == (equal), != (not equal), <, <=, > and >=. Equality takes two equals signs; a single one assigns a value, as in Variables and Data Types.
age = 15
print(age >= 13, age != 15)
print(13 <= age <= 19)
print(3 == 3.0, 1 == "1")
print("apple" < "banana", "Zebra" < "apple")
# ✅ Expected output:
# True False
# True
# True False
# True True- 13 <= age <= 19 is a chain: it means 13 <= age and age <= 19, the way you'd write it in maths.
- Numbers compare by value whatever their type, so 3 == 3.0 is True. A number is never equal to text, so 1 == "1" is False, without an error.
- Text compares letter by letter, by each character's code number, and every capital letter A–Z comes before every lowercase one. That's why "Zebra" sorts before "apple". To compare without caring about case, lowercase both sides first with .lower(), from String Methods.
== can compare anything with anything, but <, <=, > and >= need values that have an order between them. A number and text don't:
print(1 < "1")
# ✅ Expected error:
# TypeError: '<' not supported between instances of 'int' and 'str'In real programs the text has usually come from input(), which always returns text. Convert it with int() before comparing.
Combining conditions: and, or, not
and is true when both sides are, or when at least one side is, and not turns true into false and false into true. Python works out not first, then and, then or, and all three come after comparisons, so conditions like these need no parentheses:
age = 20
has_ticket = True
print(age >= 18 and has_ticket)
print(age < 12 or age > 65)
print(not has_ticket)
# ✅ Expected output:
# True
# False
# Falseand and or don't always give True or False, though. They give back one of the values they were handed: or gives the first one that counts as true and and the first one that counts as false, and when there's no such value, both give the last one. Zero and empty text count as false:
print(0 or "guest")
print("" or "nobody")
print(3 and 5)
print(0 and 5)
# ✅ Expected output:
# guest
# nobody
# 5
# 0In a condition this makes no difference, because the value given back counts as true or false just as the plain answer would. Outside one it's a handy default: name or "guest" gives the name, or "guest" when the name is empty. Which values count as false is the subject of Booleans & Truthiness.
Both operators also stop as soon as the answer is known: and at the first false value, or at the first true one. The rest is never run, which is why this division by zero never happens:
x = 0
print(x != 0 and 10 / x > 1)
# ✅ Expected output:
# FalseUpdating a variable: +=, -= and the rest
total += 5 is short for total = total + 5. Every arithmetic operator has a version like it: -=, *=, /=, //=, %= and **=.
total = 10
total += 5
total *= 2
print(total)
total /= 4
print(total)
# ✅ Expected output:
# 30
# 7.5/= divides with /, so total becomes a float. If you know count++ from another language, Python doesn't have it, or -- either:
count = 0
count++
# ✅ Expected error:
# SyntaxError: invalid syntaxWrite count += 1. Watch out for count =+ 1 too: it runs, but it means count = +1 and sets count to 1 every time.
Is it in there? in and not in
in checks whether a value is one of the items of a collection, such as a list: values in square brackets, which get a lesson of their own, Lists and Collections. On text, in checks whether one piece of text appears inside another, and not in asks the opposite.
colours = ["red", "green"]
print("red" in colours, "blue" in colours)
print("blue" not in colours)
print("@" in "[email protected]")
print("cat" in "concatenate")
# ✅ Expected output:
# True False
# True
# True
# TrueOn text, in matches anywhere, even in the middle of a word, as the last line shows. On a list it matches only whole items.
is: the same object, not the same value
== asks whether two values are equal. is asks something stricter: whether both names refer to the very same object. Two lists built separately can hold equal values and still be two objects:
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)
result = None
print(result is None)
# ✅ Expected output:
# True False True
# TrueIn everyday code, use is for one thing: checking for None, as in result is None or result is not None. For numbers and text, whether is says True depends on how Python happens to store the values, so the same comparison can give different answers in different programs. Compare those with ==.
The order Python applies operators in
Every operator on this page, from the first applied to the last:
| Operators | Notes |
|---|---|
| ( ) | whatever is inside goes first |
| ** | a chain is worked out from the right |
| -x, +x | a sign in front of one value |
| * / // % | left to right |
| + - | left to right |
| == != < <= > >= in not in is is not | can be chained, as in 13 <= age <= 19 |
| not | flips the condition after it |
| and | true when both sides are |
| or | true when either side is; applied last |
Python's bitwise operators, such as ^, sit between + - and the comparisons. Assignment, including +=, isn't an operator in this sense: it always happens after the whole right-hand side has been worked out.
Practice: minutes into hours
This program turns 200 minutes into hours and minutes, then checks whether that's more than three hours. Fill the three blanks with the operators in the hint lines, in order, and run it.
minutes = 200
hours = minutes ___ 60
left = minutes ___ 60
print(hours, "h", left, "min")
print("Over three hours?", minutes ___ 180)
# 👉 replace ___ with //
# 👉 replace ___ with %
# 👉 replace ___ with >
# ✅ Expected output:
# 3 h 20 min
# Over three hours? TrueOn your own: leap years
A year is a leap year when it divides exactly by 4, except that a year dividing by 100 is a leap year only if it also divides by 400. Write one expression that is True for leap years, using %, ==, !=, and and or, and print it for 2024, 1900 and 2000. Only 1900 should come out False. Then compare with this solution:
year = 2024
print(year, year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))
year = 1900
print(year, year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))
year = 2000
print(year, year % 4 == 0 and (year % 100 != 0 or year % 400 == 0))
# ✅ Expected output:
# 2024 True
# 1900 False
# 2000 TrueWriting the same expression three times is clumsy; Functions shows how to give it a name and reuse it.
Practice quiz
What does print(-7 // 2) show?
- -3
- -4
- -3.5
- 3
Answer: -4. // rounds down, towards minus infinity, so -3.5 becomes -4. int(-7 / 2) would give -3.
What does print(-2 ** 2) show?
- 4
- An error
- -4
- -2
Answer: -4. ** is applied before the minus sign in front of it, so this is -(2 ** 2). Write (-2) ** 2 to square -2.
What does print(2 ^ 3) show?
- 1
- 8
- 6
- An error
Answer: 1. ^ is a bitwise operator, not a power, and it raises no error. 2 ** 3 is 8.
a = 4 and b = 8. Which line prints their average, 6.0?
- print(a + b / 2)
- print(a + b // 2)
- print(a / 2 + b)
- print((a + b) / 2)
Answer: print((a + b) / 2). / runs before +, so without the parentheses only b is halved and the first line prints 8.0.
What does print(0.1 + 0.2 == 0.3) show?
- True
- False
- An error
- 0.3
Answer: False. As floats, 0.1 + 0.2 is 0.30000000000000004, so == says False. math.isclose(0.1 + 0.2, 0.3) says True.
What does print(0 or "guest") show?
- guest
- True
- 0
- False
Answer: guest. or gives back the first value that counts as true, and 0 counts as false.
How do you add 1 to count in Python?
- count++
- ++count
- count += 1
- count =+ 1
Answer: count += 1. count++ is a SyntaxError. ++count is count with two plus signs in front, so nothing changes, and count =+ 1 sets count to 1.
Which line is the usual way to check that result holds None?
- result == None
- result is None
- result = None
- result in None
Answer: result is None. None is a single object, so Python's style guide asks for is None and is not None.
Continue this course
- Previous: Variables and Data Types
- Next: Control Flow - If/Else — Make decisions in code with if, elif, and else statements
- Quick reference: Python cheat sheet
Frequently asked questions
How large can a Python integer be?
There's no fixed limit. A whole number can grow as large as your computer's memory allows, and arithmetic on it stays exact: 2 ** 100 is a 31-digit number and Python keeps every digit. Floats are different. They have a fixed size, which is why their precision runs out.
Does Python have && and || like JavaScript or C?
No. Python spells them as words, and, or and not, and && or || in Python code is a SyntaxError. The single symbols &, | and ^ do exist, but they are bitwise operators with a different job, so use the words for conditions.