Python has two main kinds of number:
- Integers (
int) are whole numbers:7,-3,1000. - Floats (
float) have a decimal point:2.5,0.1,3.0.
These are the arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
// | divide and round down | 7 // 2 | 3 |
% | remainder | 7 % 2 | 1 |
** | to the power of | 7 ** 2 | 49 |
Normal division / always gives a float, even when the answer is whole: 6 / 2 is 3.0. Use // when you want a whole number.
Multiplication and division happen before addition and subtraction. Brackets change the order:
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
Updating a variable
To change a variable based on its current value, there are shortcuts:
points = 10
points += 5 # same as points = points + 5
points -= 2
points *= 2
Rounding
round(4.6) gives 5. A second number says how many decimals to keep: round(3.14159, 2) gives 3.14.
Your Task
- A pizza costs 12 and you order 3. Create
subtotalfromprice * pizzas. - Create
tipas 15 percent of the subtotal (multiply by0.15). - Create
totalas the subtotal plus the tip. - Four friends share the bill. Create
per_personas the total divided byfriends, rounded to 2 decimals. - Print
total, then printper_person.
subtotalis36, calculated from the variablestipis 15 percent of the subtotaltotalis the subtotal plus the tipper_personis the total divided by four, rounded to 2 decimals- The total and the amount per person are printed
Lesson complete!
Next Lesson: Strings