Python · Lesson 1.2

Numbers

Whole numbers and decimals, the maths operators, and rounding.

1Whole numbers and decimals

Python has two kinds of number you'll use daily: int for whole numbers and float for numbers with a decimal point.

units = 12        # int
price = 3.75      # float
print(units * price)
Python

Practice

A shop sold 18 mugs at 9.5 each. Print the revenue.

mugs = 18
price = 9.5
# Print the revenue
Python

2The maths operators

+ - * / work as you'd expect, and ** is "to the power of". Dividing with / always gives a float.

print(7 + 3, 7 - 3, 7 * 3)
print(7 / 2)
print(2 ** 10)
Python

Practice

Sales of 1000 grow by 7% a year, so after 3 years they're 1000 * 1.07 ** 3. Print that value rounded to 2 decimals with round(value, 2).

start = 1000
# Print the sales after 3 years, rounded to 2 decimals
Python

3Whole division and remainders

// divides and drops the remainder, and % gives just the remainder. They're handy for splitting things into groups.

minutes = 135
print(minutes // 60, "hours and", minutes % 60, "minutes")
Python

Practice

You have 250 items and each box holds 12. Print how many boxes you can fill completely, then on a second line how many items are left over.

items = 250
per_box = 12
# Print full boxes, then leftovers
Python

4Rounding and the decimal surprise

round(x, 2) rounds to 2 decimals. Floats are stored in binary, so some decimals come out slightly off, and rounding tidies them.

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
Python

Tip

Never compare floats with == straight after maths: 0.1 + 0.2 == 0.3 is False. Round both sides first, or check that the gap is tiny.

Practice

Three daily temperatures were 21.4, 19.8 and 22.9. Print their average, rounded to 1 decimal.

a, b, c = 21.4, 19.8, 22.9
# Print the average, rounded to 1 decimal
Python