Python Numbers and Math · Lesson 14 of 149

Python Number Functions

What you will learn

  • abs() for the size of a number
  • round(): decimal places, negative places, and how ties are handled
  • divmod(): quotient and remainder in one step
  • pow(), including its three-argument form
  • min(), max() and sum() on several values or a list

Python has many built-in functions that are always available, with no import. This lesson covers the ones for numbers. The math module (lesson 3.6) adds more.

1. abs(): the size of a number

abs(x) removes the minus sign:

print(abs(-7), abs(-3.5), abs(0))
7 3.5 0

It is useful for distance: the gap between two numbers is abs(a - b), whichever is bigger.

Quick check: what is `abs(10 - 25)`?

15. The result of 10 - 25 is -15, and abs removes the sign.

2. round()

round(x, n) rounds x to n decimal places. Without n, it rounds to a whole number and returns an int:

print(round(3.14159, 2), round(3.14159, 3), round(7.9))
print(type(round(5.5)), type(round(5.5, 1)))
3.14 3.142 8
<class 'int'> <class 'float'>

Ties go to the even number

When a number is exactly halfway between two choices, round picks the even one. This is called "round half to even" (or banker's rounding), and it avoids a bias that always rounding up would create:

print(round(0.5), round(1.5), round(2.5), round(3.5), round(-2.5))
0 2 2 4 -2

So round(2.5) is 2, not 3. This surprises many learners who were taught "5 rounds up".

Negative places

A negative n rounds to tens, hundreds and so on:

print(round(1234, -2), round(1250, -2), round(1350, -2))
1200 1200 1400

1250 is exactly halfway between 1200 and 1300, so the even choice 1200 wins.

A warning about floats

Python's documentation warns that round() on floats can give a surprising result, because many decimals cannot be stored exactly (lesson 3.4):

print(round(2.675, 2))
2.67

You might expect 2.68. The stored value of 2.675 is just below it, so it rounds down. If you need exact decimal rounding, for example for money, use the decimal module (lesson 3.5).

3. divmod(): quotient and remainder together

divmod(a, b) gives the pair (a // b, a % b) in one step:

print(divmod(17, 5), divmod(-17, 5), divmod(7.5, 2))
(3, 2) (-4, 3) (3.0, 1.5)

The result is a pair of values (a tuple, chapter 8). You can store the parts in two names:

minutes, seconds = divmod(400, 60)
print(minutes, seconds)
6 40

4. pow()

With two arguments, pow(a, b) is the same as a ** b:

print(pow(2, 10), pow(2, -1))
1024 0.5

With three arguments, pow(a, b, m) gives (a ** b) % m but computes it efficiently, even for huge numbers. It is common in cryptography and number theory:

print(pow(2, 10, 1000), 2 ** 10 % 1000)
print(pow(3, 4, 5))
24 24
1

For everyday work, ** is clearer.

5. min(), max() and sum()

min and max return the smallest and largest value. They accept several values or one collection:

print(max(3, 9, 4), min(3, 9, 4))
print(max([3, 9, 4]), min("b", "a", "c"))
9 3
9 a

sum adds up a collection, and can start from a number other than zero:

print(sum([1, 2, 3]), sum([1, 2, 3], 10), sum([]))
print(sum(range(1, 101)))
6 16 0
5050
  • sum([1, 2, 3], 10) starts at 10, so the total is 16.
  • sum([]) is 0, because there is nothing to add.
  • sum(range(1, 101)) adds the numbers from 1 to 100.

min and max on an empty collection raise a ValueError, unless you give a default:

max([])
ValueError: max() iterable argument is empty
print(max([], default=0))
0

When two values are equal, max and min return the first one: max(2, 2.0) is 2, and max(2.0, 2) is 2.0.

Worked example: summarise some marks

Marks: 72, 85, 64, 91, 78. Find the best, the worst, the average and the range.

marks = [72, 85, 64, 91, 78]
print(max(marks), min(marks))
print(sum(marks) / len(marks))
print(max(marks) - min(marks))
91 64
78.0
27
Step Calculation Result
Best / worst max(marks), min(marks) 91, 64
Total sum(marks) 390
Average 390 / 5 78.0
Range 91 - 64 27

len(marks) counts the items in the list (here 5).

Common mistakes

  • Expecting round(2.5) to be 3. Python rounds ties to the even number: 2.
  • Trusting round for exact money maths. Floats are approximate; use decimal (lesson 3.5).
  • Forgetting that round(x) returns an int while round(x, 1) returns a float.
  • Calling max() or min() on an empty list without a default.
  • Using sum() on text. sum is for numbers; join text with "".join(...) (chapter 4).

Key takeaways

  • abs(x) is the size of a number; abs(a - b) is the distance between two numbers.
  • round(x, n) rounds to n places; ties go to the even number, so round(2.5) is 2.
  • divmod(a, b) gives (a // b, a % b) together.
  • pow(a, b, m) is (a ** b) % m, computed efficiently.
  • min, max and sum work on several values or a list; empty input needs a default (or gives 0 for sum).

Practice

1. What do abs(-12) and abs(4.5) give?

Show answer

12 and 4.5.

2. What do round(7.5) and round(8.5) give? Why?

Show answer

8 and 8. Both are exact ties, and Python picks the even neighbour: 8 in each case.

3. Write one line using divmod to get the days and leftover hours from 100 hours.

Show answer

days, hours = divmod(100, 24) gives days = 4 and hours = 4.

4. What does sum([4, 5, 6], 100) give?

Show answer

115. The sum starts at 100, then adds 15.

5. What do max(3, 8, 5) and min([3, 8, 5]) give?

Show answer

8 and 3.

6. Write the code that returns 0 instead of an error when the list scores might be empty and you want the highest score.

Show answer

max(scores, default=0).