Operators
Operators
An operator is a symbol that combines values to produce a new value. You already know + from arithmetic. Python has several families of them, and knowing which family a symbol belongs to tells you what kind of result to expect.
Arithmetic operators
| Operator | Meaning | a = 17, b = 5 |
Result |
|---|---|---|---|
+ |
Addition | a + b |
22 |
- |
Subtraction | a - b |
12 |
* |
Multiplication | a * b |
85 |
/ |
Division | a / b |
3.4 |
// |
Floor division | a // b |
3 |
% |
Modulus (remainder) | a % b |
2 |
** |
Exponent (power) | a ** 2 |
289 |
a = 17
b = 5
print(a + b)
print(a / b)
print(a // b)
print(a % b)
print(a ** 2)
print(2 ** 10)
Integer and float division
/ and // are genuinely different operators, and the distinction trips up nearly everyone once.
/ always produces a float, even when the division is exact. 10 / 2 gives 5.0, not 5. If you have come from C, this will surprise you: there, integer division truncates.
// discards the fractional part and gives you the whole-number part of the division. 17 // 5 is 3. With positive numbers you can think of it as "how many times does b fit completely into a".
print(10 / 2) # 5.0 - a float
print(10 // 2) # 5 - an int
print(17 / 5) # 3.4
print(17 // 5) # 3
print(-17 // 5) # -4, not -3
print(7.0 // 2) # 3.0 - float in, float out
Note -17 // 5 giving -4. Floor division rounds down towards negative infinity, not towards zero. This rarely matters in first-year work, but it is worth knowing so the result does not look like a bug.
% gives the remainder, and it is more useful than it first appears:
n % 2 == 0tests whethernis even.n % 5 == 0tests divisibility by 5.seconds % 60gives the seconds left over after whole minutes.
total_seconds = 3725
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
print(f"{hours}h {minutes}m {seconds}s")
print(f"Is 3725 even? {total_seconds % 2 == 0}")
That pairing of // and % — quotient and remainder — is the standard way to split a total into units.
Comparison operators
These compare two values and always produce a boolean, True or False.
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal to |
<= |
Less than or equal to |
= assigns a value. == compares two values. Writing if marks = 40: is a syntax error in Python, which is a small mercy — in C it silently assigns and the condition becomes true. Read == aloud as "is equal to" and = as "gets".
marks = 62
pass_mark = 40
print(marks > pass_mark)
print(marks == 62)
print(marks != 62)
print("apple" < "banana")
print(3 == 3.0)
The last two are worth explaining. Strings compare alphabetically by character codes, so "apple" < "banana" is True. And 3 == 3.0 is True because Python compares numeric value, not type, even though type(3) and type(3.0) differ.
Python also allows chained comparisons, which read exactly as they do in mathematics:
marks = 62
print(40 <= marks <= 100)
print(0 < marks < 50)
Logical operators
and, or and not combine boolean values.
A and BisTrueonly when both areTrue.A or BisTruewhen at least one isTrue.not Aflips the value.
attendance = 82
marks = 55
eligible = attendance >= 75 and marks >= 40
print("Eligible:", eligible)
needs_attention = marks < 40 or attendance < 75
print("Needs attention:", needs_attention)
print(not eligible)
print(True and False, True or False, not True)
Python's words and, or, not do the job of &&, || and ! in C and Java. Do not mix them up — && is not valid Python.
These operators short-circuit: in A and B, if A is already False, Python never evaluates B, because the answer cannot change. In A or B, if A is True, B is skipped. This is occasionally useful and occasionally surprising.
Assignment operators
Beyond plain =, there are compound forms that combine an operation with assignment.
score = 10
score += 5 # same as score = score + 5
print(score)
score -= 3
print(score)
score *= 2
print(score)
score //= 4
print(score)
message = "Total"
message += ": 24"
print(message)
+= works on strings too, joining rather than adding. These forms are shorter and make the intent — "update this variable" — clearer than repeating the name.
Precedence
When several operators appear in one expression, Python applies them in a fixed order. From highest priority to lowest:
**- Unary minus, as in
-x *,/,//,%+,-- Comparisons:
==,!=,<,>,<=,>= notandor
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)
print(10 - 4 - 3)
print(True or False and False)
Two details in there. 2 3 2 gives 512, not 64, because groups right to left: it is 2 (3 ** 2). Everything else at the same level groups left to right, so 10 - 4 - 3 is (10 - 4) - 3.
And True or False and False is True, because and binds tighter than or.
You are not marked down for using brackets. If an expression takes more than a moment to parse in your head, add them. (attendance >= 75) and (marks >= 40) is not clumsy — it is readable.
Common mistakes
Using = in a condition. if marks = 40: is a SyntaxError. Comparison needs ==.
Expecting / to give a whole number. total / count gives a float. If you need an integer count of items, use //.
Writing &&, || or ! from C. Python uses and, or, not. if a > 0 && b > 0: is a syntax error.
Comparing a string to a number. "85" > 80 raises TypeError in Python 3, because there is no meaningful ordering between text and numbers. Convert first: int("85") > 80.
Testing float equality directly. 0.1 + 0.2 == 0.3 is False due to binary floating-point representation. Compare with a tolerance instead: abs((0.1 + 0.2) - 0.3) < 0.000001.
Chaining or with values instead of comparisons. if grade == "A" or "B": does not do what it looks like. "B" on its own is a non-empty string, which counts as true, so the condition is always true. Write if grade == "A" or grade == "B":.
Practice
Try the operator exercises on the practice page.