13. Numbers and math
Python numbers come in two main kinds, do the usual arithmetic, and plug into standard library modules for more helpers. This chapter covers what you need for game logic: rounding, random numbers, basic maths.
Integers and floats
Python has two common number types:
- int. A whole number with no decimal part:
0,7,-42. - float. A number with a decimal point:
3.14,0.5,-1.0.
Most of the time you do not have to care which is which.
7 is an int, 7.0 is a float. When you mix them
in arithmetic the result is a float.
type(x).__name__ tells you which you have:
print(type(7).__name__) # int
print(type(7.0).__name__) # float
print(type(3.14).__name__) # floatArithmetic
The familiar operators are all here, plus two less common in everyday maths:
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
addition | 3 + 2 |
5 |
- |
subtraction | 7 - 4 |
3 |
* |
multiplication | 6 * 7 |
42 |
/ |
float division | 7 / 2 |
3.5 |
// |
integer division | 7 // 2 |
3 |
% |
modulo (remainder) | 7 % 3 |
1 |
** |
power | 2 ** 8 |
256 |
Three are worth a closer look:
Float division / always gives a float
in Python, even when the answer is whole. 6 / 3 is
2.0, not 2. This is different from some other
languages where dividing two integers gives an integer.
Integer division // drops everything
after the decimal point. 7 // 2 is 3.
-7 // 2 is -4, because it rounds toward
negative infinity, not toward zero.
Modulo % is the remainder after integer
division. 7 % 3 is 1 because
7 = 2 * 3 + 1. It is the standard way to ask "is this
number even?" — n % 2 is 0 for evens and
1 for odds.
print(7 / 2) # 3.5
print(7 // 2) # 3
print(7 % 2) # 1
print(2 ** 8) # 256Open exercises/13/01-arithmetic.py. Predict each printed
result before running, then run and check.
The math module
Python's math module has the helpers you reach for most.
Add import math at the top of your file to use them:
import math| Function | What it does |
|---|---|
math.floor(x) |
Largest integer not greater than x.
floor(3.7) -> 3. |
math.ceil(x) |
Smallest integer not less than x.
ceil(3.2) -> 4. |
abs(x) |
The absolute value. abs(-5) -> 5. Built-in, no
import. |
math.sqrt(x) |
Square root. |
min(a, b) |
The smaller of two numbers. Built-in, no import. |
max(a, b) |
The larger of two numbers. Built-in, no import. |
math.pi |
The constant 3.1415... (a value, not a function). |
Call them like any other function:
import math
print(math.floor(3.7)) # 3
print(math.ceil(3.2)) # 4
print(math.sqrt(16)) # 4.0
print(min(7, 3)) # 3
print(math.pi) # 3.141592653589793abs(), min(), and max() are
built into Python and always available. math.floor,
math.ceil, math.sqrt, and math.pi
require import math at the top of the file.
Random numbers
Random numbers live in the random module. Import it at
the top:
import randomrandom.random()returns a float between0.0and1.0.random.randint(a, b)returns a whole number fromatob, both ends included.random.randint(1, 6)is a six-sided die.
import random
print(random.random()) # e.g. 0.6238...
print(random.randint(1, 6)) # e.g. 4
print(random.randint(1, 100)) # e.g. 73random.randint(a, b) includes both a and
b in the possible results. This matches the expected
behaviour for dice rolls and similar uses.
Turning text into a number
When a value arrives as a string but you need to do maths with it,
use int() for a whole number or float() for a
decimal:
text = "42"
n = int(text)
print(n + 1) # 43
decimal_text = "3.14"
x = float(decimal_text)
print(x * 2) # 6.28If the text cannot become a number, Python raises a
ValueError:
int("hello") # ValueError: invalid literal for int()You will use these conversions a lot in the next chapter, where the program reads keyboard input. Whatever the user types arrives as a string, even if they typed digits.
Homework
Problem 1 — Rectangle area
Open exercises/13/homework/01-rectangle-area.py. Two
variables hold a rectangle's width and height.
Compute the area and print it with a label, for example
Area: 24.
Problem 2 — Floor and ceil
Open exercises/13/homework/02-floor-and-ceil.py. A
variable holds the float 3.7. Print it as-is, after
math.floor, and after math.ceil. Add one
comment line explaining the difference between floor and ceil.
Problem 3 — Roll two dice
Open exercises/13/homework/03-roll-two-dice.py. "Roll"
two six-sided dice and print the results like this:
Die 1: 4
Die 2: 6
Total: 10
Use random.randint for the rolls. Roll each die
separately so the two values are independent.
Challenge — Hypotenuse
Open exercises/13/homework/04-hypotenuse.py. Two
variables hold the two short sides of a right triangle (a
and b). Compute and print the hypotenuse c
using the Pythagorean theorem:
c = sqrt(a**2 + b**2)
Print all three values labelled. Round the hypotenuse to two decimal
places with an f-string and the :.2f format spec from
chapter 12.
Stuck or finished? Open the homework solutions page.