Python's numbers work about the way you'd expect, with one standout difference: Python integers have no size limit, growing as large as memory allows.
| Function | What it does | Example |
|---|---|---|
| round(n) | Rounds to the nearest whole number | round(4.5) → 4 (see the callout below) |
| round(n, decimals) | Rounds to a set number of decimal places | round(3.14159, 2) → 3.14 |
| math.floor(n) | Always rounds down | math.floor(4.9) → 4 |
| math.ceil(n) | Always rounds up | math.ceil(4.1) → 5 |
round(4.5) is not what you'd expect
Python's round() uses "round half to even" (also called banker's rounding) — round(4.5) gives 4, not 5, and round(5.5) gives 6. This is a deliberate design choice, not the simple "always round .5 up" rule you might expect, and it surprises almost everyone the first time they hit it.
floor() and ceil(), along with most other math functions, live in Python's math module rather than being available by default — you'll look at import properly in an upcoming lesson, but the pattern is simple enough to use right away:
import math
print(math.floor(4.9)) # 4
print(math.ceil(4.1)) # 5
print(math.sqrt(64)) # 8.0
print(math.pi) # 3.141592653589793print(abs(-7)) # 7 — absolute value
print(max(3, 9, 2)) # 9 — largest of the arguments
print(min(3, 9, 2)) # 2 — smallest of the arguments
print(pow(2, 10)) # 1024 — same as 2 ** 10An f-string with a format specifier is the standard way to control decimal places and add thousands separators — the Strings lesson covers format specifiers in full:
value = 1234567.891
print(f"{value:,.2f}") # "1,234,567.89"The random module — another standard library module, like math — generates random numbers and makes random choices:
import random
print(random.randint(1, 6)) # a random integer from 1 to 6, both included
print(random.random()) # a random float from 0.0 up to (not including) 1.0
print(random.choice(["red", "green", "blue"])) # picks one item at randomNot for security-sensitive values
random is fine for games, quizzes, and sampling — it is not secure enough for anything like a password reset token or an API key. For that, the standard library's secrets module exists specifically to generate values safe for security purposes.