Python Complex Numbers

What is a Complex Number?

A complex number is a number that has two parts: a real part and an imaginary part. In Python, complex numbers are represented by complex type and written as real + imaginary j, where j is the imaginary unit.

Creating Complex Numbers

You can create complex numbers directly by writing them as literals or by using the complex() constructor.

# Using literals
z1 = 3 + 4j
z2 = 5 - 2j

# Using constructor
z3 = complex(3, 4)  # same as 3+4j
z4 = complex(5, -2)

Accessing Real and Imaginary Parts

Use the .real and .imag attributes to access components.

print(z1.real)  # Output: 3.0
print(z1.imag)  # Output: 4.0

Operations with Complex Numbers

Python supports arithmetic operations on complex numbers:

z1 = 3 + 4j
z2 = 1 - 1j

print(z1 + z2)  # Output: (4+3j)
print(z1 - z2)  # Output: (2+5j)
print(z1 * z2)  # Output: (7+1j)
print(z1 / z2)  # Output: (0.5+3.5j)

Built-in Functions

z = 3 + 4j
print(abs(z))          # Output: 5.0 (magnitude)
print(z.conjugate())   # Output: (3-4j)

Use Cases of Complex Numbers

Best Practices

Example: Calculating Magnitude and Conjugate

def print_complex_info(z):
    print(f"Complex number: {z}")
    print(f"Real part: {z.real}")
    print(f"Imaginary part: {z.imag}")
    print(f"Magnitude: {abs(z)}")
    print(f"Conjugate: {z.conjugate()}")

z = complex(6, 8)
print_complex_info(z)