Complex Numbers in Python 🐍
Most general-purpose programming languages have either no support or limited support for complex numbers. Python is a rare exception because it comes with complex numbers built in.
The quickest way to define a complex number in Python is by typing its literal directly in the source code:
🔗In-depth tutorial on complex numbers by RealPython
#tutorial #complex
Most general-purpose programming languages have either no support or limited support for complex numbers. Python is a rare exception because it comes with complex numbers built in.
The quickest way to define a complex number in Python is by typing its literal directly in the source code:
>>> z1 = 1 + 2j
You can also use a built-in Python function, complex()
. It accepts two numeric parameters. The first one represents the real part, while the second one represents the imaginary part denoted with the letter j in the literal you saw in the example above:>>> z2 = complex(1, 2)To get the real and imaginary parts of a complex number in Python, you can reach for the corresponding
>>> z1 == z2
True
.real
and .imag
attributes:>>> z2.imagNote that both properties are read-only because complex numbers are immutable, so trying to assign a new value to either of them will fail.
2.0
🔗In-depth tutorial on complex numbers by RealPython
#tutorial #complex