Python · Beginner
Operators in Python
In short: Operators are the symbols that combine values into expressions: + - * / // % ** for arithmetic, == != < > <= >= for comparison, and/or/not for logic, += and friends for updating a variable, and in for membership. Python applies them in a fixed precedence order, which parentheses override.
Expressions and operators
An expression is code that produces a value: 3 * 4, price > 100, name in guests. Operators are the symbols that say what to do with the values on either side of them, and Python groups them into families that each return a particular kind of result.
Arithmetic operators take numbers and return numbers, and three of them deserve attention. / is true division and always returns a float, even for 8 / 2. // is floor division: it divides and rounds down to the nearest whole number, so 7 // 2 is 3 and -7 // 2 is -4, not -3. % is the remainder left after floor division, and it takes the sign of the right operand, so -7 % 2 is 1. Together // and % answer questions such as "how many full boxes, and how many items are left over". ** raises to a power.
Comparison operators (==, !=, <, >, <=, >=) return a bool. They can be chained: 13 <= age < 20 means what it looks like it means. and, or and not combine bools. and and or short-circuit: the right side is skipped when the left side already decides the answer, which makes count > 0 and total / count > 5 safe when count is zero.
Augmented assignments such as +=, -=, *= and //= update a variable in place: total += 5 reads total, adds 5 and stores the result back. in and not in test membership in a string, list or other collection: "pea" in "peanut" is True.
When an expression mixes operators, precedence decides the order: powers first, then multiplication and division, then addition and subtraction, then comparisons, then not, and and or. Parentheses override everything; add them whenever the order is not obvious.
Syntax
a + b a - b a * b a / b # true division, always a float
a // b a % b a ** b # floor division, remainder, power
a == b a != b a < b a >= b # comparisons -> True or False
x and y x or y not x # logic
total += n total -= n total *= n total //= n
item in collection item not in collectionComparisons can be chained: 0 < x <= 10 checks both bounds and evaluates x only once.
Arithmetic operators, using 17 and 5
| Expression | Result | Meaning |
|---|---|---|
| 17 + 5 | 22 | addition |
| 17 - 5 | 12 | subtraction |
| 17 * 5 | 85 | multiplication |
| 17 / 5 | 3.4 | true division, always a float |
| 17 // 5 | 3 | floor division |
| 17 % 5 | 2 | remainder |
| 17 ** 2 | 289 | power |
| -17 // 5 | -4 | floors toward negative infinity |
| -17 % 5 | 3 | remainder takes the sign of the divisor |
Cartons and leftovers
Packing 47 eggs into cartons of 12 uses every arithmetic operator that matters.
eggs = 47
per_carton = 12
print("Full cartons:", eggs // per_carton)
print("Left over:", eggs % per_carton)
print("Exact:", eggs / per_carton)
print("Cartons needed:", (eggs + per_carton - 1) // per_carton)
print(2 ** 10)
print(-7 // 2, -7 % 2)Output
Full cartons: 3 Left over: 11 Exact: 3.9166666666666665 Cartons needed: 4 1024 -4 1
// and % split 47 into 3 full cartons and 11 spare eggs, while / gives a float that answers neither question. The rounding-up trick (n + d - 1) // d counts the cartons needed to hold every egg, a pattern that recurs in paging code. The last line shows floor division with a negative number: the quotient rounds down to -4 and the remainder is 1, so that -4 * 2 + 1 gets back to -7.
Comparisons and logic
The program is run with the two input lines 17 and yes.
age = int(input())
member = input() == "yes"
adult = age >= 18
print("adult:", adult)
print("member:", member)
print("adult and member:", adult and member)
print("adult or member:", adult or member)
print("not member:", not member)
print("teen:", 13 <= age <= 19)
print("free entry:", member and not adult)Input given to the program: 17 ↵ yes
Output
adult: False member: True adult and member: False adult or member: True not member: False teen: True free entry: True
Comparisons produce bools that can be stored in variables and combined later. input() == "yes" turns typed text into a bool in one step. The chained comparison 13 <= age <= 19 checks both bounds without repeating age. not binds tighter than and, so member and not adult reads as member and (not adult).
Updating variables, and precedence
Five augmented assignments, then expressions where the order of evaluation matters.
balance = 100
balance += 25
balance -= 40
balance *= 2
balance //= 3
print(balance)
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(-3 ** 2, (-3) ** 2)
print("pea" in "peanut", 4 in [1, 2, 3], "x" not in "abc")Output
56 14 20 512 -9 9 True False True
Each augmented assignment reads the variable, applies the operator and stores the result back, walking balance from 100 to 125, 85, 170 and finally 56. * before + gives 14; parentheses force 20. groups from the right, so 2 3 2 is 2 9, and it binds tighter than a leading minus, so -3 2 is -(3 2). Membership tests work on strings and lists alike.
Common mistakes
Expecting / to return an integer
Why it goes wrong:
10 / 2is5.0, a float. Using it as a list index or inside range() raises TypeError, because those need an int.Fix: Use
//when you want a whole-number result, or int() when you already have a float you must truncate.Python · fixitems = ["a", "b", "c", "d"] middle = len(items) // 2 print(items[middle])Using ^ for powers
Why it goes wrong: In Python
^is bitwise exclusive-or, so2 ^ 3is 1, not 8. No error is raised, so the wrong value travels on silently.Fix: Use
for exponentiation:2 3is 8.Writing a condition the way it is said in English
Why it goes wrong:
if x == 1 or 2:is always true, because Python reads it as(x == 1) or (2)and the number 2 on its own counts as true.Fix: Repeat the comparison, or use membership:
if x == 1 or x == 2:orif x in (1, 2):.Confusing = and ==
Why it goes wrong:
=binds a name and cannot appear inside an if condition;==compares and produces a bool.if total = 0:is a SyntaxError.Fix: Read
=as "becomes" and==as "is equal to".
Where you use this
Paging through search results is integer arithmetic. With 47 results and 10 per page you need (47 + 10 - 1) // 10, which is 5 pages, and result number 23 (counting from 0) sits on page 23 // 10 at position 23 % 10. The same pair of operators converts 135 minutes into 2 hours and 15 minutes and decides whether a year is a leap year with year % 4 == 0 and (year % 100 != 0 or year % 400 == 0). Comparison and logical operators then turn such numbers into decisions in if statements.
results = 47
per_page = 10
pages = (results + per_page - 1) // per_page
print(pages) # 5Key points
/always returns a float;//rounds down;%gives the remainder with the sign of the divisor.**is power and groups from the right;^is not power.- Comparisons return bools and can be chained:
0 < x < 10. andandorshort-circuit: the right side runs only when needed.+=,-=,*=and//=update a variable in place.- Precedence:
**, then* / // %, then+ -, then comparisons, thennot,and,or. Parentheses win.
Try it yourself
Read a number of minutes and print it as hours and minutes in the form 2 h 15 min. Use // for the hours and % for the leftover minutes.
minutes = int(input())
# print hours and remaining minutes
1352 h 15 minminutes = int(input())
print(minutes // 60, "h", minutes % 60, "min")
Practise this
Related lessons
- Data Types in PythonThe core Python data types int, float, str, bool and None: how to check a type with type() and convert between types with int(), float() and str().8 min
- Conditions: if, elif and else in PythonHow Python chooses between paths with if, elif and else, how truthiness works, why branch order matters, and how to write conditions that stay readable.8 min
- Variables in PythonHow Python variables work: assignment binds a name to a value, no type declaration is needed, and a variable is a label rather than a box. Runnable examples.7 min
Frequently asked questions
What is the difference between / and // in Python?
/ is true division and always returns a float: 7 / 2 is 3.5 and 8 / 2 is 4.0. // is floor division: it returns the largest whole number not greater than the exact quotient, so 7 // 2 is 3 and -7 // 2 is -4. When both operands are ints the result of // is an int; if either is a float the result is a float, so 7.0 // 2 gives 3.0.
How does % work with negative numbers in Python?
The result of a % b always has the same sign as b, and a == (a // b) * b + a % b holds for every pair. So -7 % 2 is 1 and 7 % -2 is -1. This differs from C and Java, where the remainder takes the sign of the dividend, and it is convenient for wrapping an index around a list: (i - 1) % len(items) never goes negative.
How this page was checked. Every program on it was run with CPython 3.11 at build time; runs in your browser on CPython 3.14 (Pyodide) by the publishing checks, and the output shown is what it printed. The Run buttons execute the same code on your device; nothing you type is sent anywhere.