BasicsChapter 13 of 114
Operators
Arithmetic, comparison, logic, membership and identity, plus what binds tightest.
Arithmetic
| Operator | Does | 7 and 3 give |
|---|---|---|
+ | add | 10 |
- | subtract | 4 |
* | multiply | 21 |
/ | divide, always a float | 2.3333333333333335 |
// | divide, rounded down | 2 |
% | remainder | 1 |
** | power | 343 |
print(7 + 3, 7 - 3, 7 * 3)
print(7 / 3, 7 // 3, 7 % 3, 7 ** 3)Output
10 4 21 2.3333333333333335 2 1 343
Comparison
print(5 == 5, 5 != 5)
print(5 > 3, 5 < 3, 5 >= 5, 5 <= 4)Output
True False True False True False
Comparisons can be chained, and they read the way the maths does:
age = 25
print(18 <= age < 65)Output
True
That is genuinely one comparison, not two joined by and, so age is only evaluated once.
Logical
and, or and not, covered in the previous chapter. The thing worth repeating is that they stop early:
def loud():
print("this ran")
return True
print(False and loud())
print(True or loud())Output
False True
Neither call happened. loud() was never needed.
Membership
in asks whether something is inside a container:
print("a" in "cat")
print(3 in [1, 2, 3])
print("x" not in "cat")
print("name" in {"name": "Ada"})Output
True True True True
For a dictionary, in looks at the keys, not the values.
Identity
== asks whether two values are equal. is asks whether they are the same object. They are different questions:
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b)
print(a is b)
print(a is c)Output
True False True
a and b hold equal contents in two separate lists. c is another name for the very same list.
Assignment shorthands
n = 10
n += 5
n -= 3
n *= 2
n //= 4
print(n)Output
6
The walrus
:= assigns and produces the value, so you can capture something in the same line that tests it:
values = [1, 2, 3, 4]
if (count := len(values)) > 3:
print(f"{count} values, which is plenty")Output
4 values, which is plenty
Precedence
** binds tightest, then unary minus, then * / // %, then + -, then comparisons, then not, and, or.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)Output
14 20 512
** groups right to left, so that last line is 2 ** 9, not 8 ** 2.
Test yourself
3 questionsWhat is the difference between == and is?
Show the answer
== compares values; is asks whether they are the same object — Two equal lists are ==, but not is. Keep is for None, True and False.
What is 2 3 2?
Show the answer
512 — groups right to left, so it is 2 9 rather than 8 ** 2.
What does 18 <= age < 65 do?
Show the answer
One chained comparison that evaluates age once — Python chains comparisons the way the maths does, and only evaluates the middle expression once.
User Input
Read something the person running your program typed, and convert it safely.