Numbers and Math
Python is a great calculator, and that's where most programs start: adding up prices, averaging scores, measuring things. In this lesson you'll learn how Python works with numbers.
Two kinds of numbers
Python has two main number types:
int: whole numbers, such as7,-3and1000000float: numbers with a decimal point, such as3.14,-0.5and2.0
print(type(42)) print(type(42.0)) print(type(-7)) print(type(3.5))
42 and 42.0 are the same amount, but different types: the decimal point makes 42.0 a float.
Arithmetic operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition | 7 + 2 |
9 |
- |
Subtraction | 7 - 2 |
5 |
* |
Multiplication | 7 * 2 |
14 |
/ |
Division | 7 / 2 |
3.5 |
// |
Whole-number division | 7 // 2 |
3 |
% |
Remainder | 7 % 2 |
1 |
** |
Power | 7 ** 2 |
49 |
print(7 + 2) print(7 - 2) print(7 * 2) print(7 / 2) print(7 // 2) print(7 % 2) print(7 ** 2)
Notice that / always gives a float, even when the numbers divide evenly:
print(10 / 2) # 5.0, not 5 print(10 // 2) # 5
Whole-number division and remainder
// and % are a pair. Think of sharing sweets: // tells you how many each person gets, and % tells you how many are left over.
sweets = 17
people = 5
print("Each person gets", sweets // people)
print("Left over:", sweets % people)They're handy for converting units, like minutes into hours:
total_minutes = 135 hours = total_minutes // 60 minutes = total_minutes % 60 print(hours, "hours and", minutes, "minutes")
A common trick: a number is even if number % 2 is 0, because nothing is left over when you divide it by 2.
print(10 % 2) # 0, so 10 is even print(7 % 2) # 1, so 7 is odd
Order of operations
Python follows the same rules as maths: ** first, then * / // %, then + -. Use parentheses to change the order, or just to make your intent clear.
Predict first: what will each line print?
print(2 + 3 * 4) print((2 + 3) * 4) print(10 - 4 - 3)
The first line gives 14 because multiplication happens before addition. Parentheses change that, so the second gives 20.
Mixing ints and floats
When you combine an int with a float, the result is a float:
print(3 + 2.0) print(4 * 0.5)
Floats aren't always exact
Computers store decimal numbers in a way that can't represent every value exactly. This surprises everyone the first time:
print(0.1 + 0.2)
That's not a Python bug; every programming language does this. The fix is simple: round results before showing them to people.
Rounding
round(number) rounds to the nearest whole number, and round(number, digits) keeps that many decimal places:
print(round(3.7)) print(round(3.14159, 2)) print(round(0.1 + 0.2, 2))
Showing a fixed number of decimals
Prices usually need exactly two decimal places, even when the number is whole. In an f-string, put :.2f after the value inside the braces:
price = 4.5
total = price * 3
print(f"Total: {total}")
print(f"Total: {total:.2f}")
print(f"Pi is about {3.14159:.2f}")Read .2f as "2 digits after the decimal point". You'll learn more of these formatting codes in the String Formatting lesson.
Going deeper: Rounding exact halves optional
You might expect round(2.5) to give 3, but Python gives 2. When a number is exactly halfway, Python rounds to the nearest even number. This is called "banker's rounding", and it avoids results drifting upwards when you round lots of numbers.
print(round(0.5)) print(round(1.5)) print(round(2.5)) print(round(3.5))
Updating a variable
You'll often change a variable based on its current value. Python has shortcuts for this:
score = 10 score += 5 # same as score = score + 5 print(score) score -= 3 # same as score = score - 3 print(score) score *= 2 # same as score = score * 2 print(score)
Read score += 5 as "add 5 to score".
Useful built-in functions
print(abs(-12)) # distance from zero: 12 print(min(4, 9, 1, 7)) # smallest: 1 print(max(4, 9, 1, 7)) # largest: 9
The math module
Python comes with extra toolboxes called modules. The math module has more advanced maths. Write import math once at the top of your program to load it, then use its tools with math. in front. (You'll learn more in the Modules and Imports lesson in Part 4.)
import math print(math.pi) print(math.sqrt(16)) # square root print(math.floor(3.7)) # round down print(math.ceil(3.2)) # round up
For example, the area of a circle is π × r²:
import math
radius = 5
area = math.pi * radius ** 2
print(f"Area: {area:.2f}")Going deeper: More number facts optional
Integers have no size limit. Python can work with enormous whole numbers. Underscores make long numbers easier to read:
print(2 ** 100) print(1_000_000 * 3)
Two more built-ins. pow(a, b) is the same as a ** b, and divmod(a, b) gives both a // b and a % b at once:
print(pow(2, 5)) print(divmod(17, 5))
Powers go right to left. Most operators work left to right, but ** works right to left, so 2 ** 3 ** 2 means 2 ** 9:
print(2 ** 3 ** 2) print((2 ** 3) ** 2)
Exercises
Exercise 1: Average of three scores
Calculate and print the average of the three scores, rounded to 1 decimal place. The expected output is 81.7.
score1 = 78 score2 = 92 score3 = 75
Add the three scores and divide by 3. Use parentheses so the adding happens first.
Wrap the result in round(..., 1) to keep one decimal place.
Exercise 2: Seconds to minutes
Convert 500 seconds into minutes and seconds using // and %. Print: 8 minutes and 20 seconds.
total_seconds = 500
total_seconds // 60 gives the whole minutes.
total_seconds % 60 gives the seconds left over.
Exercise 3: Shopping bill
A shirt costs 19.99 and you're buying 3. There's a 10% discount on the total. Print the final price with 2 decimal places: Total: 53.97.
price = 19.99 quantity = 3 discount = 0.10
First multiply the price by the quantity.
A 10% discount means subtracting total * discount. Print with f"Total: {total:.2f}".
Exercise 4: Hypotenuse
The hypotenuse of a right triangle is √(a² + b²). Use the math module to calculate it for sides 3 and 4. The answer is 5.0.
a = 3 b = 4
Add import math at the top.
Square each side with ** 2, add them together, then use math.sqrt() on the sum.
Number tools at a glance
A quick reference for later. The arithmetic operators (+, -, *, /, //, %, **) are in the table near the top of this lesson.
Built-in functions (no import needed)
| Function | What it does | Example | Result |
|---|---|---|---|
abs(x) |
Distance from zero (drops the minus sign) | abs(-7) |
7 |
round(x) |
Rounds to the nearest whole number | round(3.7) |
4 |
round(x, n) |
Rounds to n decimal places |
round(3.14159, 2) |
3.14 |
min(a, b, ...) |
The smallest value | min(4, 9, 1) |
1 |
max(a, b, ...) |
The largest value | max(4, 9, 1) |
9 |
sum(numbers) |
Adds up a list of numbers | sum([4, 9, 1]) |
14 |
pow(a, b) |
a to the power b, same as a ** b |
pow(2, 5) |
32 |
divmod(a, b) |
Whole-number division and remainder together | divmod(17, 5) |
(3, 2) |
Converting between types
| Function | What it does | Example | Result |
|---|---|---|---|
int(x) |
Makes a whole number; cuts off any decimals (doesn't round) | int(3.9) |
3 |
int(text) |
Turns text like "42" into a number |
int("42") |
42 |
float(x) |
Makes a decimal number | float(3) |
3.0 |
float(text) |
Turns text like "2.5" into a number |
float("2.5") |
2.5 |
str(x) |
Turns a number into text | str(3.5) |
'3.5' |
Updating a variable (each example starts from x = 10)
| Shortcut | Same as | Example | x afterwards |
|---|---|---|---|
x += n |
x = x + n |
x += 3 |
13 |
x -= n |
x = x - n |
x -= 3 |
7 |
x *= n |
x = x * n |
x *= 3 |
30 |
x /= n |
x = x / n |
x /= 4 |
2.5 |
x //= n |
x = x // n |
x //= 4 |
2 |
x %= n |
x = x % n |
x %= 4 |
2 |
x **= n |
x = x ** n |
x **= 2 |
100 |
The math module (write import math first)
| Function | What it does | Example | Result |
|---|---|---|---|
math.pi |
The number π | math.pi |
3.141592653589793 |
math.sqrt(x) |
Square root | math.sqrt(16) |
4.0 |
math.floor(x) |
Rounds down | math.floor(3.7) |
3 |
math.ceil(x) |
Rounds up | math.ceil(3.2) |
4 |
math.trunc(x) |
Cuts off the decimals, towards zero | math.trunc(-3.7) |
-3 |
math.hypot(a, b) |
Length of the long side of a right-angled triangle | math.hypot(3, 4) |
5.0 |
math.factorial(n) |
1 × 2 × ... × n |
math.factorial(5) |
120 |
math.gcd(a, b) |
Greatest common divisor | math.gcd(12, 18) |
6 |
math.log(x, base) |
Logarithm of x in the given base |
math.log(100, 10) |
2.0 |
math.isclose(a, b) |
Are two floats equal, allowing for tiny errors? | math.isclose(0.1 + 0.2, 0.3) |
True |
Summary
intholds whole numbers, andfloatholds numbers with a decimal point./always gives a float.//gives the whole part, and%gives the remainder.- Python follows the usual order of operations. Use parentheses to be clear.
- Floats can be slightly inexact, so round results before showing them:
round(x, 2)orf"{x:.2f}". score += 5is a shortcut forscore = score + 5.abs,min,maxandroundare built in.import mathgives yousqrt,pi,floorandceil.