livepython.net
CHAPTER 05Working With Data Types
5.2  NUMBERS

Python Numbers: int, float and Math Operators

Integers and Floats

Python has two main kinds of numbers. You met them in chapter 4; now let's see how they behave.

TypeMeaningExamples
inta whole number, no decimal point100, -5, 0
floata number with a decimal point19.99, 2.5, 10.0
PYTHONedit me
score = 100
price = 19.99
print(type(score))
print(type(price))
OUTPUT
<class 'int'>
<class 'float'>

Think of an int as counting things you can't split, like people or goals, and a float as measuring things you can, like weight or money.

Mixing them

When you combine an int and a float, the answer is a float:

PYTHONedit me
print(2 + 0.5)
print(3 * 1.0)
OUTPUT
2.5
3.0

3 * 1.0 is a whole amount, but because one side was a float, the result is 3.0.

Big numbers and underscores

For long numbers, you can use _ to make them easier to read. Python ignores it:

PYTHONedit me
population = 1_400_000_000
print(population)
OUTPUT
1400000000

Floats are not always exact

Computers store floats in a way that can't hold every decimal exactly:

PYTHONedit me
print(0.1 + 0.2)
OUTPUT
0.30000000000000004

This surprises everyone the first time! It's not a bug in Python; almost every programming language does it. You'll learn how to round the result in the last lesson of this topic.

Whole numbers are int, decimal numbers are float. Mix them, and you get a float.

your turnPick the right idea

What type is the result of 4 + 1.5?

Think about it, then pick one.

Math Operators

Python's maths symbols are called operators. You know the first four from chapter 2. Here are all seven:

OperatorNameExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//floor divide7 // 23
%remainder (modulo)7 % 21
**power7 ** 249
PYTHONedit me
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)
OUTPUT
3.5
3
1
49

The three new ones

  • // divides and throws away the decimal part: 7 // 2 is 3.
  • % gives what's left over after dividing: 7 sweets shared by 2 friends leaves 1 sweet. So 7 % 2 is 1.
  • ** means "to the power of": 7 ** 2 is 7 times 7.

Think of // and % as a pair: // says how many fit, % says how many are left.

/ always gives a float

PYTHONedit me
print(6 / 2)
OUTPUT
3.0

Even when the answer is a whole number, / returns a float. Use // when you want a whole number.

Dividing by zero

PYTHONedit me
print(5 / 0)
OUTPUT
ZeroDivisionError: division by zero

Just like in maths, you can't divide by zero.

// counts how many fit, % gives what's left, ** raises to a power.

your turnType the output

Type what this prints

print(17 % 5)
Read the code line by line, then type the output exactly.
your turnFill the gap

Make it print 8

print(2 ? 3)

It should print: 8

Which piece makes this code work?

The Order of Operations

What does 2 + 3 * 4 give? In Python, as in maths, multiplication comes first:

PYTHONedit me
print(2 + 3 * 4)
print((2 + 3) * 4)
OUTPUT
14
20

Without brackets: 3 * 4 is 12, plus 2 makes 14. With brackets: 2 + 3 is 5, times 4 makes 20.

The order Python follows

  1. Brackets ( ) first.
  2. Powers **.
  3. Multiply and divide: *, /, //, %, from left to right.
  4. Add and subtract: +, -, from left to right.

You may know this from school as BODMAS, BIDMAS or PEMDAS. Python uses the same idea.

Use brackets to be clear

Even when you don't need them, brackets make your intention obvious:

PYTHONedit me
marks = 80
bonus = 10
total = (marks + bonus) * 2
print(total)
OUTPUT
180

A reader sees straight away that the bonus is added before doubling.

A real example: the average

PYTHONedit me
a = 70
b = 80
c = 90
print((a + b + c) / 3)
print(a + b + c / 3)
OUTPUT
80.0
180.0

The second line is a classic bug: only c is divided by 3. Brackets fix it.

Brackets first, then powers, then * and /, then + and -.

your turnPredict the output

What will this print?

print(10 - 2 * 3)
Your turn! What will this code show on the screen?
your turnFix the code

Fix the average so it prints 80.0

It should print: 80.0

a = 70
b = 80
c = 90
print(a + b + c / 3)
This code does not work yet. Fix it, then press Run.

Shortcuts: +=, -= and More

In chapter 4 you updated a variable with its own value: score = score + 5. That's so common that Python has a shortcut:

PYTHONedit me
score = 10
score += 5
print(score)
OUTPUT
15

score += 5 means exactly the same as score = score + 5. Read it as "add 5 to score".

The whole family

ShortcutSame as
x += 2x = x + 2
x -= 2x = x - 2
x *= 2x = x * 2
x /= 2x = x / 2
PYTHONedit me
lives = 3
lives -= 1
print("Lives left:", lives)
coins = 50
coins *= 2
print("Coins:", coins)
OUTPUT
Lives left: 2
Coins: 100

Think of a scoreboard: you don't rewrite the whole board each time, you just add or take away points.

It works with strings too

+= with a string adds text to the end:

PYTHONedit me
message = "Hello"
message += ", Sunny!"
print(message)
OUTPUT
Hello, Sunny!

The variable must exist first

+= uses the old value, so there must be one:

PYTHONedit me
total += 10
OUTPUT
NameError: name 'total' is not defined

Create it first, for example total = 0, then add to it. You'll use this pattern a lot in the loop chapters, to count and to add up totals.

x += 5 is short for x = x + 5. The variable must already have a value.

your turnType the output

Type what this prints

coins = 10 coins += 5 coins -= 3 print(coins)
Read the code line by line, then type the output exactly.
your turnOrder the lines

Put the lines in order to print 20

  1. total = 0
  2. total += 15
  3. print(total)
  4. total += 5
These lines are mixed up. Put them back in order, then press Check.

Rounding Numbers with round()

Long decimals are hard to read. The built-in round() function tidies them up. Give it the number and how many decimal places you want:

PYTHONedit me
pi = 3.14159
print(round(pi, 2))
print(round(pi))
OUTPUT
3.14
3
  • round(pi, 2) keeps two digits after the point: 3.14.
  • round(pi), with no second number, rounds to the nearest whole number: 3, an int.

Fixing the 0.1 + 0.2 surprise

Remember 0.30000000000000004 from the first lesson? round() fixes the display:

PYTHONedit me
print(round(0.1 + 0.2, 2))
OUTPUT
0.3

round() vs :.2f

You saw :.2f in f-strings. They're related, but not the same:

CodeResultNote
round(4.5, 2)4.5a number; trailing zeros are dropped
f"{4.5:.2f}"4.50text; always shows two digits

For money on screen, use :.2f, so it always shows 4.50. For calculations, use round().

A surprise with halves

PYTHONedit me
print(round(2.5))
print(round(3.5))
OUTPUT
2
4

When a number is exactly halfway, Python rounds to the nearest even number. It's called "banker's rounding", and it keeps totals fair when you round many numbers. You rarely need to worry about it, but now it won't surprise you.

round(x, 2) keeps two decimal places; round(x) gives the nearest whole number.

your turnPredict the output

What will this print?

print(round(7.456, 1))
Your turn! What will this code show on the screen?
your turnPredict the output

What will this print?

a, b = 1, 2 a, b = b, a print(a)
Your turn! What will this code show on the screen?

Practice: Numbers

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 37.Python Program to Find the Quotient and RemainderEasySolve
  2. 38.Python Program to Calculate Simple InterestMediumSolve
  3. 39.Python Program to Convert Minutes to Hours and MinutesMediumSolve