…
…
Python Programming Fundamentals · Lesson 3 / 40 · Numbers and math
PreviewIn this lesson you will
// and %, and fix an expression that gives a wrong result with parenthesesYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Three friends are sitting at the same table at Corner Café and have ordered 2 lattes, 1 cookie, and 1 espresso (latte $4.25, cookie $2.00, espresso $3.00). Ada at the register wants to see the receipt subtotal, the 10% sales tax, the total with tax, and each person's share if the bill is split three ways. By the end of this lesson you will write the program that produces this output yourself:
OutputSubtotal: 13.5
Tax: 1.35
Total: 14.85
Per person: 4.95In the last lesson you learned to put values into variables and to update them with +=. In this lesson you will do real math with those variables. A café register asks the same three questions all day: "What is the total?", "How much is the tax?", and "How do we split this among people?". Behind each of these questions there is a rule about numbers that Python expects you to know.
In this lesson you will be able to:
round// and %Look at the order on the table: 2 lattes, 1 cookie, 1 espresso. The quantities are integers, because nobody orders half a latte. Prices, on the other hand, are not always integers: a latte is $4.25. Python keeps these two cases in two separate number types. Why keep them apart? Because counting something and measuring something are different jobs, and their results look different.
A number without a decimal point is an integer (int in Python): 85, 2, 0, -15. A number with a decimal point is a float (float in Python): 4.25, 0.10, 3.0. Look closely at the last example: 3.0 is equal to 3 in value, but because it has a decimal point, it is a float.
Here is a point worth noticing. In many countries the decimal separator is a comma, and people write prices like 3,75. In Python the decimal separator is always a decimal point: 3.75. A comma has a different job in Python; you will see it with a real example in the "Common mistake" section at the end of the lesson.
What happens when the two types are mixed in one operation? The rule is simple: if there is even one float in the operation, the result is a decimal. 3.75 * 2 gives 7.5; even if 2 is an integer, 3.75 is a decimal, so the result is a decimal too. The division operator / is even stricter: it always gives a float, even when the result comes out whole. 10 / 2 gives 5.0, not 5. Python knows that the result of a division is often not whole, so it keeps the result as a decimal from the start.
There is no separate operator for percentages in Python. "Ten percent" means "ten parts out of a hundred", that is, 10 / 100 or 0.10; to find 10% of an amount, you multiply the amount by 0.10. If an order is $5, its tax is 5 * 0.10, that is, $0.50.
#### Example 1: Brownie, tax, and division
We do three small calculations: the cost of two brownies, the 10% tax on a $5 order, and a division that comes out whole.
brownie = 3.75 print(brownie * 2) print(5 * 0.10) print(10 / 2)
Output7.5
0.5
5.0All three lines gave a decimal result. In the first because 3.75 is a decimal, in the second because 0.10 is a decimal, and in the third because / always gives a decimal.
What does this code print on the screen?
print(10 / 2)Now we come to a property of floats that you need to know. A computer stores numbers inside using only 0 and 1, that is, the binary system. Some decimals, like 0.1, cannot be written exactly in binary; just like 1/3 goes on forever as 0.3333... in decimal. The computer stores this number with a value that is very close, and sometimes this tiny difference shows up on the screen. This is not a bug in Python; you will see the same result in almost every programming language.
#### Example 2: The floating point surprise
We add two small decimals, and then round the result to two places.
total = 0.1 + 0.2 print(total) print(round(total, 2))
Output0.30000000000000004
0.3The difference really is small: at the sixteenth place after the decimal point. It does not spoil the accuracy of the calculation, but it looks ugly on a receipt. That is why you use round(number, places) when you show a decimal result. Two values are written inside the parentheses: the number to round and how many places to keep after the decimal point. round(104.567, 2) gives 104.57. If you are showing money, two places are usually enough. Notice the comma inside the parentheses: here the comma is not a decimal separator; it separates the two values from each other.
In the cell below, try the tax calculation yourself. First run the code as it is. Then change the tax rate to 0.20 and see how the two lines change. After that, set the rate back to 0.10, remove the rounding on the last line (make the line print("Total:", subtotal + tax)), and set subtotal to 19.99. What do you see on the two lines? What changes when you put the rounding back?
Try it now· not graded; doesn't affect progress
With this cell you have tested two misunderstandings at once. The first is the thought "0.1 + 0.2 is exactly 0.3, and if it is not, Python is calculating wrongly": Python calculates correctly; it only stores decimals approximately. The second is taking rounding to be the calculation itself: round is not used to change the result but to show it neatly.
What happens if the three friends at the table, leaving the tax aside, want to share a $13 bill? Normal division 13 / 3 gives 4.333333333333333. But nobody can pay the register $4 and 33.3333 cents. In real life the question is: "How many whole dollars does everyone pay, and how many dollars are left over?" This question comes up very often in programming: how many tables fill up completely, how many boxes fill up completely, how many hours and how many minutes something takes. Python gives two operators for this.
Floor division // gives only the whole part of the quotient: 13 // 3 is 4. The remainder % gives what is left over from the division: 13 % 3 is 1. Think of the division you learned in primary school: 3 goes into 13 four times and 1 is left over. If you want to check, 3 * 4 + 1 is 13 again. The two signs together answer the two halves of the question "how many full groups, how many left over".
#### Example 3: Splitting the bill
We split a 13-dollar bill among three people in three different ways.
bill = 13 people = 3 print(bill / people) print(bill // people) print(bill % people)
Output4.333333333333333
4
1/ measures and goes all the way down to the cent; // counts and gives only the whole part; % tells you what is left over. The results of // and % on two integers are integers too, which is why you do not see a decimal point in the output.
What does this code print?
print(7 // 2, 7 % 2)Here are all the math operators you have seen so far in one table. The list has one new operator: ** raises to a power; 2 ** 3, that is, 2 × 2 × 2, is 8. It is rarely used in café math, but it belongs in the table.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 4 + 2 | 6 |
- | Subtraction | 13 - 4 | 9 |
* | Multiplication | 2 * 3 | 6 |
/ | Division (always a decimal) | 13 / 3 | 4.333333333333333 |
// | Floor division |
Floor division and the remainder have another job at the register: giving change. The customer paid $20, the bill is $13; the change is $7. If the register only has $5 notes, how many notes do you give, and how many dollars are left over? 7 // 5 gives 1 note, and 7 % 5 leaves $2. In the block below, change the amount paid and the note; every time you choose, the output of the code changes at once. Try all nine combinations and see in which ones nothing is left over.
How many notes is the change, and how many dollars are left?
Pick a value; predict the output first, then look.
1paid = 202note = 53amount = 134change = paid - amount5count = change // note6left = change % note7print(change, count, left)
7 1 2
Faded lines didn't run with this value. The three numbers in the output are, in order, the change, the number of notes, and the dollars left over. If the remainder is 0, the change is paid completely in notes.
When $15 is paid and the $10 note is chosen, the change is $2 and not a single $10 note can be given: 2 // 10 is 0, and the whole $2 stays as the remainder. If the number being divided is smaller than the number you divide by, floor division is 0 and the remainder is the number itself.
Ada is curious about the average price of two items: latte 4.25, cookie 2.00. The average is the sum of the two divided by 2; the answer should be 3.125. If you write this as 4.25 + 2.00 / 2, Python finds 5.25. No error message comes, the program runs, but the result is wrong. Why? Because Python does not read an expression from left to right and calculate in order. It follows an order of precedence, as in math.
| Precedence | Operators |
|---|---|
| 1 (highest) | ( ) parentheses |
| 2 | ** |
| 3 | *, /, //, % |
| 4 (lowest) | +, - |
First what is inside the parentheses, then the power, then the group of multiplication and division, and last addition and subtraction. In the expression 4.25 + 2.00 / 2, division comes before addition: first 2.00 / 2 is calculated, 1.0 comes out, then 4.25 is added and 5.25 is found. If you want to add first, you put the addition inside parentheses: (4.25 + 2.00) / 2 gives 3.125.
If operations with the same precedence sit side by side, they are done from left to right. In the expression 10 - 4 - 3, first 10 - 4 is calculated, 6 comes out, then 3 is subtracted: the result is 3. If we had started from the right, 4 - 3 would be 1 and 10 - 1 would be 9; Python does not do it that way. The best habit is this: if you are not sure, put in parentheses. Extra parentheses do not spoil the result, and they tell the person reading the code your intention clearly.
#### Example 4: Precedence and parentheses
We compare the calculation without and with parentheses, using the same two prices.
latte = 4.25 cookie = 2 print(latte + cookie * 2) print((latte + cookie) * 2)
Output8.25
12.5The first line means "one latte and two cookies": first cookie * 2 is calculated. The second line means "two each of a latte and a cookie": first what is in the parentheses is added. Which one is right depends on what the question asks; Python only does what you wrote.
Follow the code below step by step. At each line, watch how the variable boxes fill up, and on the last two lines see how the parentheses change the result.
Run the code line by line: see which line runs next, the variable boxes and the output.
bill = 13 people = 3 share = bill // people left = bill % people print(share, left) print(2 + 3 * 4) print((2 + 3) * 4)
Now find the result of each expression yourself. First decide, according to the precedence table, which operation is done first, then choose the result. There are two extra results in the list; they are the results of common misreadings.
Choose the result of each expression in Python.
For each row, pick its match from the list, then check.
4 + 2 / 2(4 + 2) / 22 + 3 * 4(2 + 3) * 410 - 4 - 32 ** 3The misunderstanding of this section is the thought "operations are done from left to right". The danger of this misunderstanding is that it gives no error message: the program runs, prints a number on the screen, and the number looks right even though it is wrong. That is why it is a good habit to check the result of a program that does math by hand with a small example whose answer you know.
Now we write the program from the start of the lesson with all its parts. Each step is named with a comment; you will use the same steps again in the exercises.
# 1. Subtotal subtotal = 4.25 * 2 + 2.00 + 3.00 # 2. Tax tax = subtotal * 0.10 # 3. Total total = subtotal + tax # 4. Per person per_person = total / 3 print("Subtotal:", subtotal) print("Tax:", tax) print("Total:", total) print("Per person:", per_person)
OutputSubtotal: 13.5
Tax: 1.35
Total: 14.85
Per person: 4.95On the first line, precedence does its job: first the 4.25 * 2 multiplication is calculated, then everything is added; no parentheses are needed. The result is 13.5, because there is a float like 4.25 in the operation. Every following line uses the result of the line before: the tax is calculated from the subtotal, the total from the tax, and each person's share from the total.
The lines of the table's bill got mixed up. Put the lines in order so that the program works correctly.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Floor division and the remainder are not only about money. We find how many hours and minutes a 135-minute movie lasts: since an hour is 60 minutes, the number of whole hours comes from
Writing a float with a comma. If you write the brownie price as 3,75 out of habit, Python does not raise an error, but 3.75 is not created either. A comma puts two separate values side by side; price is now a pair made of two numbers: (3, 75). When you multiply it by two, Python writes the pair twice in a row:
price = 3,75
print(price * 2)Output(3, 75, 3, 75)Instead of the 7.5 you expected, a strange result comes out, and later calculations either give wrong results or stop with an error message. The fix: use a decimal point as the decimal separator, price = 3.75.
Here is a similar silent mistake: writing 4.25 + 2.00 / 2 for the average of two prices. This line does not raise an error either, but it gives 5.25, because division is done before addition. The fix is (4.25 + 2.00) / 2. In the exercises you will find and fix this mistake yourself.
int), a number with a decimal point is a decimal (float); the decimal separator is a decimal point, / always gives a decimal result, and when you show a decimal result you use round(number, 2).// gives the whole part of the quotient and % gives the remainder; together they answer "how many full groups, how many left over". % is not percent; for 10 percent you multiply by 0.10.**, then * / // %, and + - last; with the same precedence it goes from left to right. If you are not sure, put in parentheses.Next lesson: The "2" that comes from the order screen is not a number but a string; we will learn the types of values and how to convert from one type to another.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
13 // 34 |
% | Remainder | 13 % 3 | 1 |
** | Power | 2 ** 3 | 8 |
//%minutes = 135 print(minutes // 60, "hours", minutes % 60, "minutes")
Output2 hours 15 minutesThe same pattern works for every "full groups and leftover" question: turning seconds into minutes, eggs into boxes, students into teams. The number you divide by is the size of the group; // tells you how many full groups there are, and % tells you how many items could not fit into a group.