Kodewick
Lesson 3 of 31Contents

Numbers and math

Lesson 3 of 31 · Part 1 · Basics · about 20 minutes

Python makes a very good calculator. In this lesson you will use the two kinds of numbers, int and float, and the operators that work on them. Every result below is worked out live in your browser.

The basic operators

OperatorDoesExampleResult
+add7 + 310
-subtract7 - 34
*multiply7 * 321
/divide7 / 23.5
**power7 ** 249
main.py
1print(7 + 3)2print(7 - 3)3print(7 * 3)4print(7 / 3)5print(2 ** 10)
Output
10
4
21
2.3333333333333335
1024

Spaces around operators are optional, but they make code easier to read. Note * for multiply, not x, and ** for "to the power of".

Three ways to divide

/ always gives a float, even when the division comes out even. Two more operators split a division into its whole part and what is left over:

OperatorName17 and 5
/division3.4
//floor division: how many whole times3
%remainder (also called modulo)2
main.py
1print(6 / 3)2lamps = 173per_street = 54print("Full streets:", lamps // per_street)5print("Lamps left over:", lamps % per_street)6print(10 % 2, 11 % 2)
Output
2.0
Full streets: 3
Lamps left over: 2
0 1

% is handy more often than you might think: a number is even when % 2 gives 0, and % 60 turns a count of minutes into "minutes past the hour".

Guess first

What does this print?

1print(20 // 6, 20 % 6)

Order of operations

Python follows the same order as school math. Higher in the table goes first; on the same row, left to right, except **, which goes right to left: 2 ** 3 ** 2 is 2 ** 9.

OrderOperators
1( ) parentheses
2**
3*, /, //, %
4+, -
main.py
1print(2 + 3 * 4)2print((2 + 3) * 4)3print(2 * 3 ** 2)4print(-2 ** 2)
Output
14
20
18
-4

The last one surprises people: ** goes before the minus sign, so it means -(2 ** 2). When in doubt, add parentheses. They cost nothing and make your meaning clear.

Guess first

What does this print?

1print(10 - 4 / 2)

int and float together

You can mix the two kinds freely. If either side is a float, the result is a float:

main.py
1print(3 + 2.0)2print(type(3 + 2.0))3print(0.1 + 0.2)4print(1.1 * 3)
Output
5.0
<class 'float'>
0.30000000000000004
3.3000000000000003

The last two are not bugs in Python. Computers store floats in binary, and most decimals, like 0.1, cannot be stored exactly, the way 1/3 cannot be written exactly as 0.333... The error is tiny, but it shows when you print. Whole numbers (int) are always exact.

Rounding

round(x) rounds to a whole number; round(x, 2) keeps two decimal places. To round only how a number is shown, put :.2f after it in an f-string:

main.py
1share = 2 / 32print(share)3print(round(share, 2))4print(round(share))5print(f"Each gets {share:.2f}")6print(round(2.5), round(3.5))
Output
0.6666666666666666
0.67
1
Each gets 0.67
2 4

Tip: round() sends an exact half to the nearest even number, so round(2.5) is 2. That keeps totals fair when you round many values. For money, the usual habit is to keep the full value and format it with :.2f when printing.

Changing a variable by an amount

Adding to a variable is so common that it has a short form. oil += 5 means oil = oil + 5:

ShortMeans
x += 5x = x + 5
x -= 5x = x - 5
x *= 5x = x * 5
x /= 5x = x / 5
main.py
1oil = 102oil -= 33oil += 54oil *= 25print(oil)
Output
24

Handy built-in functions

main.py
1print(abs(-7))2print(min(4, 9, 2))3print(max(4, 9, 2))4print(sum([4, 9, 2]))
Output
7
2
9
15

abs drops the minus sign; min and max pick the smallest and largest of any number of values. sum adds up a whole list of numbers; the square brackets make a list, which you will meet properly in lesson 9.

The math module

More math lives in the math module. import math once at the top, then write math. before each name:

main.py
1import math2print(math.sqrt(16))3print(math.pi)4print(math.floor(3.7), math.ceil(3.2))
Output
4.0
3.141592653589793
3 4
NameGives
math.sqrt(x)square root (a float)
math.pithe number pi
math.floor(x)round down to a whole number
math.ceil(x)round up to a whole number

math.ceil is the one to use when you need "enough": 17 lamps in boxes of 5 need math.ceil(17 / 5), which is 4 boxes.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it.

Exercise 1

Hours and minutes

Turn minutes into hours and minutes, and print the line below.

It should print
2 hours 5 minutes
exercise1.py
1minutes = 1252print(minutes)
Output
Press Run or Ctrl+Enter
Exercise 2

A tidy total

Three lamps cost 1.10 each. The total prints with a tiny float error. Show it with exactly two decimals.

It should print
Total: 3.30
exercise2.py
1price = 1.102count = 33print(f"Total: {price * count}")
Output
Press Run or Ctrl+Enter
Exercise 3

Fix the average

This should print the average of the three scores, but the answer is wrong. Fix it.

It should print
8.0
exercise3.py
1a = 72b = 83c = 94print(a + b + c / 3)
Output
Press Run or Ctrl+Enter

What you learned

  • + - * / work as in math; ** is a power.
  • / always gives a float; // gives the whole part and % the remainder.
  • ** goes first, then * / // %, then + -; parentheses override everything.
  • Mixing an int with a float gives a float; floats can be very slightly off.
  • round(x, 2) rounds; f"{x:.2f}" shows two decimals.
  • x += 1 is short for x = x + 1.
  • abs, min, max, sum are built in; import math gives sqrt, pi, floor, ceil.