Mr. Darto has 17 cups of coffee and trays that hold 5 cups each. How many trays do the 17 cups fill? How many of those trays are full? How many cups are left over? The three questions have three different answers: 3.4 trays, then 3 trays, then 2 cups. Python has one sign for each question: /, // and %.
Signs such as / and % are called operators: signs that work on values, such as adding, dividing or comparing.
Arithmetic operators
The operators for maths:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
add | 15 + 5 |
20 |
- |
subtract | 50 - 45 |
5 |
* |
multiply | 15 * 3 |
45 |
/ |
divide | 17 / 5 |
3.4 |
// |
divide, rounded down (floor division) | 17 // 5 |
3 |
% |
remainder (modulo) | 17 % 5 |
2 |
** |
power | 2 ** 8 |
256 |
The order is the same as in maths: ** first, then *, /, //, %, and after that + and -. So 2 + 3 * 4 is 14. Anything in parentheses is calculated first, so (2 + 3) * 4 is 20.
Three ways to divide
Here is Mr. Darto's calculation with the cups and trays:
cups = 17
per_tray = 5
print(cups / per_tray) # 3.4
print(cups // per_tray) # 3, the full trays
print(cups % per_tray) # 2, the cups left over
print(10 / 5) # 2.0
/always gives afloat(a fractional number), even when the division leaves no remainder. So10 / 5is2.0, not2.//divides, then rounds the result down, so the part after the dot is gone. Twointvalues give anint:17 // 5is3.%gives the remainder:17 % 5is2. Check: 3 trays × 5 cups + 2 cups = 17.%is also used to check for even numbers. An even number has a remainder of 0 when divided by 2, so8 % 2is0(even) and7 % 2is1(odd).
10 / 3 is 3.3333333333333335. A computer stores a float in binary (numbers made of only 0 and 1) with about 16 digits, so the last digit can look strange. This is not an error. It is how Python writes that result.
Power is **, not ^
2 ** 8 means 2 to the power of 8, which is 256. In Python the ^ sign means something else: XOR, an operation on bits (binary digits). So 2 ^ 8 gives 10, with no error. One more thing: -2 ** 2 gives -4, because the power is calculated before the minus sign. Write (-2) ** 2 if you mean 4.
Negative numbers: // rounds down
The same three ways to divide, now with -17 divided by 5:
print(-17 / 5) # -3.4
print(-17 // 5) # -4
print(-17 % 5) # 3
- "Down" means towards the smaller number on the number line. From -3.4, the whole number below it is -4, not -3.
%follows that//result so that the calculation is still correct: 5 × -4 + 3 = -17. In Python, the result of%has the same sign as the divisor (the number you divide by). When the divisor is 5, the result is always 0 to 4. If you already know JavaScript: there,-17 % 5gives-2.
Floats aren't always exact
Three results with floats:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(89 / 3) # 29.666666666666668
On the second line, == checks whether two values are equal. The result is False, because 0.1 + 0.2 is not exactly 0.3. A computer stores floats in binary, and 0.1 can't be stored exactly in binary. In the same way, 1/3 can't be written exactly in decimal: 0.333... never ends. That is why prices and money at the till are stored as an int: 15, a whole number of dollars, not 15.0. A long result, such as the $89 bill shared by 3 people on the third line, is made tidy when it is shown. The next lesson, Strings in Python, shows how.
There are three options for numbers that are not whole. The last two need an import line at the top of the code, which the lesson Modules & Imports explains:
- An
intof the smallest unit (used here): the till's prices are whole dollars, so it keeps whole dollars. A price with cents is kept in cents: $12.50 is stored as1250cents. Decimalfrom the built-indecimalmodule (ready-made code that comes with Python):Decimal("0.1") + Decimal("0.2") == Decimal("0.3")isTrue. Good for money that needs fractions, such as tax or exchange rates. Write the number as text, in quotes. Without quotes,Decimal(0.1)carries the float's error with it.math.isclose(a, b): for measurements such as weight or distance, check whether two floats are close enough.math.isclose(0.1 + 0.2, 0.3)isTrue.
Comparisons and logic
Comparison operators compare two values. Logic operators combine the results:
total = 89
print(total >= 50) # True
print(total >= 50 and total < 100) # True
print(total < 50 or total > 100) # False
print(not total >= 50) # False
- A comparison gives a
bool(TrueorFalse). The signs:==equal to,!=not equal to,<,>,<=(less than or equal to),>=(greater than or equal to). andisTruewhen both sides areTrue.orisTruewhen at least one side isTrue.notreverses the value on its right:TruebecomesFalse, andFalsebecomesTrue.=sticks a name onto a value, but==compares two values."5" == 5isFalse, because text and a number are never equal.
📌 The walrus :=
The := operator (Python 3.8 and later) sticks a name onto a value and uses that value in the same place:
data = [1, 2, 3, 4, 5]
if (n := len(data)) > 3:
print(n) # 5
[1, 2, 3, 4, 5]is a list (a row of values).len(data)counts the items in it: 5.(n := len(data))sticks the namenonto 5, and that 5 is compared with 3 right away. Because5 > 3isTrue, the line under theifruns and prints5. (The If, Elif, Else lesson explainsifin full.)
⚠️ Signs that look alike but mean different things
- Thinking
^means power.2 ^ 8gives10, not256, and no error tells you. Power is always**. - Expecting
/to give anint.10 / 5is2.0. Need a whole number? Use//. - Expecting
round()to always round 0.5 up.round()rounds a number to the nearest whole number.round(2.5)is2, whileround(3.5)is4: a number exactly halfway between two whole numbers is rounded to the nearest even number. - Comparing floats with
==.0.1 + 0.2 == 0.3isFalse. Store money as anint. =inside a condition.if total = 50:is refused withSyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
TL;DR: + - * work as usual, ** is power (2 ** 8 = 256, but ^ is not power: it is another operation called XOR). There are three ways to divide. / always gives a float (10 / 5 = 2.0, 10 / 3 = 3.3333333333333335). // rounds down (17 // 5 = 3, -17 // 5 = -4). % gives the remainder (17 % 5 = 2). Floats aren't always exact (0.1 + 0.2 = 0.30000000000000004), so money is stored as an int. Comparisons give True/False, and you can combine them with and, or, not. The walrus := sticks a name onto a value and uses that value at the same time.
⚡ Three ways to divide
Write:
cups = 17
per_tray = 5
print(cups / per_tray) # 3.4
print(cups // per_tray) # 3, the full trays
print(cups % per_tray) # 2, the cups left over
print(10 / 5) # 2.0
Meaning: / always gives a float (a fractional number), even when the division leaves no remainder: 10 / 5 is 2.0. // divides, then rounds down. % gives the remainder.
⚡ Power is **
Guess first: what is 2 ^ 8?
10, with no error. In Python, ^ is not power. It is XOR, another operation on bits (the 0s and 1s inside a computer).
Meaning: Power is written **: 2 ** 8 means 2 to the power of 8, which is 256.
⚡ Floats aren't always exact
Guess first: == checks whether two values are equal. What does 0.1 + 0.2 == 0.3 give?
False. 0.1 + 0.2 gives 0.30000000000000004, because a computer stores numbers in binary (only 0 and 1), and 0.1 can't be stored exactly.
Meaning: Float calculations aren't always exact. That is why prices at the till are stored as an int: 15, not 15.0.
⚡ Comparing
Meaning: == (equal to), != (not equal to), <, >, <= (less than or equal to) and >= (greater than or equal to) compare two values. The result is True or False. You can combine results with and (both are True), or (at least one is True) and not (turns True into False, and False into True). Remember: = sticks a name onto a value, == compares.