Python Basics · Lesson 3 of 12

Numbers and Math

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:

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//divide and round down7 // 23
%remainder7 % 21
**to the power of7 ** 249

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

  1. A pizza costs 12 and you order 3. Create subtotal from price * pizzas.
  2. Create tip as 15 percent of the subtotal (multiply by 0.15).
  3. Create total as the subtotal plus the tip.
  4. Four friends share the bill. Create per_person as the total divided by friends, rounded to 2 decimals.
  5. Print total, then print per_person.
  • subtotal is 36, calculated from the variables
  • tip is 15 percent of the subtotal
  • total is the subtotal plus the tip
  • per_person is the total divided by four, rounded to 2 decimals
  • The total and the amount per person are printed