Numbers Related Tips

Learn how numbers can be stored in Python data types.

Explore how int() supports other bases

It’s well known that the built-in function, int(x), attempts to convert x to an integer number. Usually, x is a floating-point number or a string, bytes, or byte-array with a decimal (base ten) representation of an integer number. It’s less commonly known that int() may take the second optional parameter, base. The base must be an integer number ranging from two to 36 (inclusive), or zero.

If the base is a positive number, then the string must contain digits between zero and base-1, or the first base-10 letter of the English alphabet. The letter case doesn’t matter:

Press + to interact
print(int('1010', 8), int('CAFE', 16), int(b'CAFE', 16), int('xyz0', 36))

If the base is zero, then the string must represent a number in the C-style notation that supports only binary, octal, and hexadecimal number systems:

Press + to interact
print(int('0b0101', 0), int('0o1010', 0), int('0xCAFE', 0))

Unfortunately, converting a number to a string is possible only for the binary, octal, decimal, and hexadecimal number systems:

Press + to interact
n = 1234
print(f'{n:b} {n:o} {n:d} {n:x} {n:X}')

With all other number systems, we’re on our own.

Discover complex numbers

Complex numbers are rare in everyday computer programming. What’s great is that Python natively supports them.

A complex number consists of a real and an imaginary part, where the imaginary part is multiplied by an imaginary unit, iota, iota, ii. An imaginary unit is the square root of -1. It’s denoted as i in mathematics and as j in Python. The square of an imaginary unit is -1:

Press + to interact
print(1j * 1j)

The multiplication result is a complex number consisting of -1 (the real part) and 0j (the imaginary part, 0) Note that there’s no multiplication sign between 0 and j. The parentheses emphasize that ...

Get hands-on with 1400+ tech skills courses.