What you’ll get
On Linux a server’s uptime lives in /proc/uptime, in seconds. Convert it into days, hours and minutes:
# uptime.py
uptime = 1_234_567 # seconds
days = uptime // 86400
hours = uptime % 86400 // 3600
minutes = uptime % 3600 // 60
print(days, "d", hours, "h", minutes, "min")
python uptime.py
# 14 d 6 h 56 min
// is division without a remainder, % the remainder. There are 86,400 seconds in a day: 14 whole days, and the same
trick pulls hours and minutes out of the remainder. The underscores in 1_234_567 are for the eye; Python skips them.
How it works: integers are exact, fractions aren’t
An int takes as much memory as it needs, so its length is unlimited and arithmetic is exact:
>>> 2 ** 100
1267650600228229401496703205376
A float is 64 bits in binary: about 16 significant digits and a limit of about 1.8e308. Most decimal fractions are
infinite in binary, like ⅓ in decimal, so the nearest value is stored:
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 == 0.3
False
>>> 10 / 3
3.3333333333333335
For measurements — sizes, times, speeds — an error in the 16th digit doesn’t show. It shows in two places: comparing
with ==, and money, where cents add up by the thousand. Compare with math.isclose, and count money with the
decimal module or in whole cents:
import math
from decimal import Decimal
print(math.isclose(0.1 + 0.2, 0.3)) # True
print(Decimal("0.1") + Decimal("0.2")) # 0.3
import math loads the math module — it’s in the standard library, nothing to install (Running Python). After
that, write its functions with a dot: math.isclose, math.ceil. from decimal import Decimal takes a single name
from a module, and you write it without a prefix. Put the import lines at the top of the file.
Division, remainder and powers
| Code | Result | What it does |
|---|---|---|
7 / 2 |
3.5 |
division; the answer is always a float, even 6 / 2 is 3.0 |
7 // 2 |
3 |
division without a remainder, rounding down: -7 // 2 is -4 |
7 % 2 |
1 |
the remainder: an even number has n % 2 == 0 |
2 ** 10 |
1024 |
a power; 2 ** 0.5 is a square root, 1.4142135623730951 |
abs(-5) |
5 |
absolute value |
max(3, 7, 1), min(…) |
7, 1 |
the largest and the smallest |
round(2.675, 2) |
2.67 |
to two places; 2.675 is stored slightly lower, so it isn’t 2.68 |
math.ceil(4.1) |
5 |
up to an integer: how many disks you need for 4.1 TB |
math.floor(4.9) |
4 |
down to an integer |
An integer with a fraction gives a fraction: 3 * 0.5 is 1.5. An integer from a string is int("100"), from a
fraction int(4.7), with the tail dropped: that’s covered in Variables and types.
Where 69 GB went: decimal and binary prefixes
Windows shows a 1 TB disk as 931 GB. The manufacturer counts a kilobyte as 1000 bytes; Windows counts 1024:
>>> 1_000_000_000_000 / 1000 ** 3
1000.0
>>> 1_000_000_000_000 / 1024 ** 3
931.3225746154785
The bytes are the same; the units differ. In the standard the binary ones are KiB, MiB, GiB; Windows writes “GB” and means GiB. ISPs, like disk makers, count in decimal — which is why Variables and types divided by 1000.
Hexadecimal, octal, binary
In configs numbers aren’t always decimal: the color #ff8800, a MAC address, chmod 755 permissions. Python writes them
with a prefix and converts both ways:
| Code | Result | Where you see it |
|---|---|---|
0xff, int("ff", 16) |
255 |
colors, MACs, bytes in a dump |
0o755, int("755", 8) |
493 |
file permissions on Linux |
0b1010 |
10 |
bits, masks |
hex(255), oct(493), bin(10) |
'0xff', '0o755', '0b1010' |
back into a string |
int("0x1f") without a base is a ValueError: read a string with a prefix using the base, int("0x1f", 16), or
without the prefix.
Take it further
Divide the volume by the disk size and round up — math.ceil. Load the module on the first line: import math.
import math
print(math.ceil(10.5 / 4))
# 3644 — to a number and back to octalint with base 8 reads a string of digits; oct returns the form with the 0o prefix.
mode = int("644", 8)
print(mode, oct(mode))
# 420 0o644An even number’s remainder when divided by 2 is 0. The == comparison gives True or False, which you can print right away.
print(10 % 2 == 0) # True
print(2026 % 4 == 0) # FalseIf it doesn’t work
0.1 + 0.2 == 0.3 gives False
- Cause
- A fraction is stored in binary, and
0.1can’t be written exactly in it: the sum comes out as0.30000000000000004. - Fix
- Don’t compare fractions with
==: usemath.isclose(0.1 + 0.2, 0.3)orround(…, 2) == 0.3. For money,decimal.Decimal("0.1")or counting in whole cents.
round(2.5) gives 2, and round(3.5) gives 4
- Cause
- Python rounds halves to even — that way less error accumulates when many numbers are rounded in a row.
- Fix
- If you need “half up” for positive numbers, use
math.floor(x + 0.5). For display you don’t need rounding at all:f"{x:.1f}".
ZeroDivisionError: division by zero
- Cause
- Dividing by zero:
/,//and%alike. Usually the zero came from the data — an empty file, a zero counter. - Fix
- Check the divisor before dividing — conditions are in the Conditions chapter.
OverflowError: (34, 'Result too large')
- Cause
- A fraction went past the
floatlimit of about1.8e308:10.0 ** 400. Integers have no limit; fractions do. - Fix
- Compute in integers if you can:
10 ** 400works. For a huge fraction, thedecimalmodule.
ValueError: Exceeds the limit (4300 digits) for integer string conversion
- Cause
- An integer longer than 4300 digits is being converted to a string —
print,str(), an f-string. The limit protects against slow conversion of giant numbers. - Fix
- Raise the limit:
import sys, thensys.set_int_max_str_digits(0)— no limit.