Operators
Arithmetic, comparison and logical operators, and the order in which they run.
Arithmetic operators
| The operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 2 | 9 |
- | Subtraction | 7 - 2 | 5 |
* | Multiplication | 7 * 2 | 14 |
/ | Division | 7 / 2 | 3.5 |
// | Floor division | 7 // 2 | 3 |
% | Remainder | 7 % 2 | 1 |
** | Exponentiation | 7 ** 2 | 49 |
Comparison operators
return a Boolean value True or False:
5 == 5 # True
5 != 3 # True
3 < 2 # False
0 < 5 < 10 # True (chained comparison)Logical operators
accuracy = 0.91
loss = 0.2
accuracy > 0.9 and loss < 0.3 # True
not (accuracy > 0.95) # Trueand andor are evaluated with short-circuiting: if the result is decided by the first operand, the second is not evaluated.
Membership and compound assignment
"ai" in "explainable ai" # True
count = 0
count += 1 # equivalent to count = count + 1Operator precedence
Exponentiation first, then multiplication and division, then addition and subtraction, then comparisons, then not then and then or. When in doubt, use parentheses: (a + b) * c is clearer and safer.
Lesson terms
- Operator precedence
- The rules that determine the order in which operations are carried out in an expression containing more than one operation.
- Floor division
- The // operator, which returns the result of division rounded down.
Abstract
Python provides arithmetic operators (+ - * / // % **), comparison operators (== != < > <= >=), logical operators (and or not) and membership operators (in). Operator precedence determines which operations run first, and parentheses can be used to make the order clear.
Review questions
-
What is the result of 7 // 2, and of 7 % 2?
The first is 3 (floor division) and the second is 1 (remainder).
-
What is the difference between = and ==?
= is for assignment, and == is for comparing equality.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate