Python provides native support for complex numbers, which are essential for fields like electrical engineering, quantum mechanics, and signal processing. Unlike many other languages that require external libraries for complex arithmetic, Python includes the complex data type as a built-in primitive.
This guide explains how to properly construct complex numbers and access their real and imaginary components using standard attributes.
Creating Complex Numbers in Python
In mathematics, the imaginary unit is usually denoted by i. However, Python (following engineering conventions) uses the suffix j or J. A complex number takes the form a + bj.
You can define them using literals or the complex() constructor.
z1 = 3 + 2j
z2 = complex(3, 2)
print(f"z1: {z1}")
print(f"Type: {type(z1)}")Output:
z1: (3+2j)
Type: <class 'complex'>Accessing the Real Part
To extract the real component, use the .real attribute. This returns the value as a floating-point number.
z = 10 + 5j
real_part = z.real
print(f"Complex number: {z}")
print(f"Real part: {real_part}")
print(f"Type: {type(real_part)}")Output:
Complex number: (10+5j)
Real part: 10.0
Type: <class 'float'>Accessing the Imaginary Part
To extract the imaginary component, use the .imag attribute. This returns the coefficient of j as a float.
z = 10 - 4j
imag_part = z.imag
print(f"Complex number: {z}")
print(f"Imaginary part: {imag_part}")Output:
Complex number: (10-4j)
Imaginary part: -4.0Common Errors and Pitfalls
When working with complex numbers, developers often encounter errors due to syntax naming conventions or confusion with method calls.
Mistake: Calling Attributes as Methods
The real and imag properties are attributes, not methods. You should not use parentheses ().
z = 3 + 2j
try:
print(z.real())
except TypeError as e:
print(f"Error: {e}")
print(f"Correct: {z.real}")Output:
Error: 'float' object is not callable
Correct: 3.0Mistake: Using i instead of j
Python strictly requires j for the imaginary suffix.
try:
my_num = 3 + 2i
except SyntaxError:
print("Error: Invalid syntax. Use 'j' instead of 'i'.")Output:
Error: Invalid syntax. Use 'j' instead of 'i'.Mistake: Assuming real() is a built-in function
Unlike abs(), there are no global built-in functions named real() or imag() in standard Python.
z = 3 + 2j
try:
print(real(z))
except NameError as e:
print(f"Error: {e}")Output:
Error: name 'real' is not definedConclusion
Working with complex numbers in Python is straightforward once you understand the syntax:
- Use the suffix
jto define the imaginary part (e.g.,3 + 4j). - Use
z.realto access the real component. - Use
z.imagto access the imaginary component. - Remember that these are attributes (no parentheses) and they always return floats.