TExcelTAD
Home › Basic Math & Pre-Algebra › Math with Python

Math with Python

Python makes an excellent calculator: you type a calculation, run it, and read the answer. This lesson teaches the few pieces of Python you need for the whole course: the arithmetic operators, whole-number division and remainders, powers, rounding, and exact fractions. No programming experience is needed.

Your first calculation

A Python program is a list of instructions, run from top to bottom. The instruction print(...) shows a value on the screen. Put a calculation inside the brackets and Python works it out first:

python · try it yourself
print(2 + 3)
print(10 - 4)
print(6 * 7)
print(12 / 5)
print("Total cost:", 3 * 4 + 2)
5
6
42
2.4
Total cost: 14

Text in quotes ("Total cost:") is printed exactly as written. Commas inside print separate several things and put a space between them. Notice that Python follows the usual rule "multiplication before addition": 3 * 4 + 2 is 14, not 18 (see Order of Operations).

The operators

Math Python Example Result
addition a+ba + b a + b 7 + 2 9
subtraction a−ba - b a - b 7 - 2 5
multiplication a×ba \times b a * b 7 * 2 14
division a÷ba \div b a / b 7 / 2 3.5
whole-number division a // b 7 // 2 3
remainder a % b 7 % 2 1
power aba^b a ** b 7 ** 2 49

Keyboards have no ×\times or ÷\div keys, so programming languages use * and /. The power operator is two stars: 2 ** 10 means 2102^{10}. Be careful: ^ is not power in Python (it is a bit operation you will meet in Binary and Hexadecimal).

Variables: giving numbers names

A variable is a name that holds a value. You create one with =, which in Python means "store this value under this name", not "is equal to".

python · try it yourself
price = 4.50        # one ticket
tickets = 3
total = price * tickets
print("Total:", total)

minutes = 135
hours = minutes // 60       # whole hours
left = minutes % 60         # minutes that remain
print(minutes, "minutes =", hours, "h", left, "min")
print("2 to the power 8:", 2 ** 8)
Total: 13.5
135 minutes = 2 h 15 min
2 to the power 8: 256

Everything after # on a line is a comment: a note for humans that Python ignores. The // and % pair is extremely useful: 135 minutes is 2 whole hours (//) with 15 minutes remaining (%). You will use both all the time in Division and Remainders.

Integers and floats

Python has two everyday kinds of number:

  • int (integer): whole numbers such as 7, -3, 1000000. Python integers have no size limit.
  • float (floating-point): numbers with a decimal point such as 2.5, -0.75, 3.0.

The / operator always gives a float, even when the answer is whole: 8 / 2 is 4.0. The // operator on two ints gives an int. Floats are stored in binary with about 16 significant digits, so some decimal answers are a tiny bit off:

python · try it yourself
print(8 / 2, type(8 / 2))
print(8 // 2, type(8 // 2))
print(2 ** 100)                 # ints can be huge
print(0.1 + 0.2)                # a float surprise
print(round(0.1 + 0.2, 2))      # round to 2 decimal places
print(round(3.14159, 3), round(2.5), round(3.5))
4.0 <class 'float'>
4 <class 'int'>
1267650600228229401496703205376
0.30000000000000004
0.3
3.142 2 4

round(x, n) rounds to n decimal places. Look at round(2.5) and round(3.5): Python rounds an exact half to the even neighbour ("banker's rounding"), so 2.5 becomes 2 and 3.5 becomes 4. School rounding would give 3 for 2.5. The Place Value and Rounding lesson explains both rules.

Note: 0.30000000000000004 is not a Python bug. Every language that uses standard floats (JavaScript, C, Java) prints the same thing. The Floating Point lesson shows why.

Exact fractions

When you need exact answers, the fractions module stores a number as a numerator and a denominator, and always keeps it in lowest terms. An import line at the top loads the module:

python · try it yourself
from fractions import Fraction

a = Fraction(1, 3)
b = Fraction(1, 6)
print(a + b)                  # 1/3 + 1/6
print(Fraction(6, 8))         # simplified automatically
print(Fraction(1, 10) + Fraction(2, 10) == Fraction(3, 10))
print(float(Fraction(7, 8)))  # convert to a decimal
1/2
3/4
True
0.875

== asks "are these equal?" and prints True or False. With fractions, one tenth plus two tenths is exactly three tenths, which floats cannot promise. You will use Fraction throughout the Fractions section.

In software

The operators in this lesson are the same in nearly every programming language, with small differences worth knowing:

  • In C, Java and Rust, 7 / 2 between two integers gives 3 (whole-number division). Python 3 gives 3.5 and keeps // for the whole-number version.
  • % is how programs test "is this number even?" (n % 2 == 0), wrap around a list, or cycle animation frames.
  • Money is never stored in plain floats in serious finance code; it is kept in whole cents (ints) or in exact decimal types.

If you want to learn Python as a language, the Python course covers it in depth, starting with Python Operators and Python Numbers.

Exercises

Exercise 1: Predict the results

Without running anything, write down what Python prints for 17 // 5, 17 % 5, 17 / 5 and 2 ** 5.

Answer

3, 2, 3.4, 32

Solution
text
17 = 5 × 3 + 2      →  17 // 5 = 3  and  17 % 5 = 2
17 ÷ 5 = 3.4        →  17 / 5 = 3.4   (always a float)
2⁵ = 2 × 2 × 2 × 2 × 2 = 32
python · try it yourself
print(17 // 5, 17 % 5, 17 / 5, 2 ** 5)
3 2 3.4 32

Exercise 2: Seconds to minutes

A video is 500 seconds long. Write a short program that prints its length as minutes and seconds.

Answer

8 minutes 20 seconds.

Solution

Whole minutes come from // 60, the leftover seconds from % 60: 8×60=4808 \times 60 = 480 and 500−480=20500 - 480 = 20.

python · try it yourself
seconds = 500
print(seconds // 60, "min", seconds % 60, "s")
8 min 20 s

Exercise 3: int or float?

Which of these give an int and which a float: 10 / 5, 10 // 5, 3 * 2.0, 7 ** 2?

Answer

float, int, float, int (2.0, 2, 6.0, 49).

Solution

/ always produces a float. // and ** on two ints produce an int. As soon as one number in a calculation is a float (2.0), the result is a float.

python · try it yourself
for value in [10 / 5, 10 // 5, 3 * 2.0, 7 ** 2]:
    print(value, type(value).__name__)
2.0 float
2 int
6.0 float
49 int

Exercise 4: Exact thirds

Compute 13+13+13\frac{1}{3} + \frac{1}{3} + \frac{1}{3} once with floats and once with Fraction. Do both give exactly 1?

Answer

Here, yes: the float sum prints 1.0 and the fraction sum prints 1. (Floats are lucky in this case; with tenths they are not, as 0.1 + 0.2 showed.)

Solution
python · try it yourself
from fractions import Fraction

print(1/3 + 1/3 + 1/3)
third = Fraction(1, 3)
print(third + third + third)
print(0.1 + 0.1 + 0.1 == 0.3, Fraction(1, 10) * 3 == Fraction(3, 10))
1.0
1
False True

The float rounding errors in 13\frac{1}{3} happen to cancel out, but for three tenths they do not. Fractions are exact every time.

Test yourself

What does 23 % 4 give in Python?

  1. 5
  2. 5.75
  3. 3
  4. 92

How do you write 3 to the power 4 in Python?

  1. 3 ^ 4
  2. 3 ** 4
  3. pow 3 4
  4. 3 x 4

What does print(9 / 3) show?

  1. 3
  2. 3.0
  3. 3 remainder 0
  4. An error