An expression is anything that produces a value: 3 + 4, price * 2, age >= 18. Operators are the symbols that combine values into expressions.
Arithmetic#
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
// | divide, keep the whole part | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
/ always gives a float, even for 8 / 2, which is 4.0. When you want a whole number, use //.
The three that matter most for problems#
// and % together take a number apart. For any whole number n, n % 10 is its last digit and n // 10 is everything else:
n = 4071
print(n % 10) # 1
print(n // 10) # 407
% tests divisibility. n % 2 == 0 means even; n % 3 == 0 means divisible by three.
% wraps around. To step through positions 0 to k - 1 in a circle, (i + 1) % k returns to 0 after k - 1.
Comparisons#
These produce True or False:
5 == 5 # equal
5 != 3 # not equal
5 > 3 # greater
5 <= 5 # less or equal
= assigns and == compares. Mixing them up is one of the most common beginner mistakes.
Python lets you chain comparisons the way you would write them in maths:
0 <= x < 10 # is x between 0 and 9?
and, or, not#
age = 20
has_ticket = True
age >= 18 and has_ticket # True: both are true
age < 13 or has_ticket # True: at least one is true
not has_ticket # False
Python stops as soon as it knows the answer. In a and b, if a is false, b is never looked at. That lets you write checks safely:
items = []
len(items) > 0 and items[0] == "x" # False, and items[0] is never read
Shorthand assignment#
score = 10
score += 5 # score = score + 5 -> 15
score -= 3 # 12
score *= 2 # 24
score //= 5 # 4
There is no ++ in Python. Write count += 1.
Order of operations#
Python follows the usual maths order: brackets, then **, then * / // %, then + -, then comparisons, then not, and, or.
2 + 3 * 4 # 14, not 20
(2 + 3) * 4 # 20
-2 ** 2 # -4: the power happens before the minus
When in doubt, add brackets. They cost nothing and make your intent clear to the next reader.
Key points#
/gives a float,//gives the whole part,%the remainder.n % 10andn // 10take a number apart one digit at a time.==compares;=assigns.andandorstop as soon as the answer is known.- Use
+=instead of++, and brackets whenever the order is not obvious.
Next: working with text, and reading what the user types.