Numbers

There’s nothing magical about numbers in Python, and we’ve already discovered how we perform operations on them.

[1]:
(2 * (1 + 3) - 5) / 0.5
[1]:
6.0
[2]:
11 % 4
[2]:
3

Python also lets you manipulate complex numbers, using j to represent the complex term.

[3]:
a = 1 + 4j
b = 4 - 1j
a - b
[3]:
(-3+5j)

Complex numbers are objects, of course, and have some useful functions and properties attached to them.

[4]:
a.conjugate()
[4]:
(1-4j)
[5]:
a.imag
[5]:
4.0
[6]:
a.real
[6]:
1.0

Somewhat confusingly, computing the magnitude of a complex number can be done with the abs method, which is available globally.

[7]:
abs(a)
[7]:
4.123105625617661
[8]:
(a.real**2 + a.imag**2)
[8]:
17.0
[9]:
(a.real**2 + a.imag**2) ** 0.5
[9]:
4.123105625617661

This also demonstrates the ** operator, which for real numbers corresponds to exponentiation.

Each type of number can be created literally, like we’ve been doing, by just typing the number into your shell or source code, and by using the correspond methods.

[10]:
int()
[10]:
0
[11]:
float()
[11]:
0.0
[12]:
complex()
[12]:
0j
[ ]: