Yandex

Python complex() Function – Create Complex Numbers Easily



Python complex() Function

The complex() function in Python is used to create complex numbers. A complex number has a real part and an imaginary part, like 3 + 4j.

This function is useful in math, simulations, electrical engineering, and many scientific applications.

Syntax

complex(real=0, imag=0)

Parameters:

  • real (optional) – The real part (default is 0)
  • imag (optional) – The imaginary part (default is 0)

Returns:

  • A complex number object: real + imag*j

Example 1: Real and Imaginary Parts

z = complex(3, 4)
print(z)
(3+4j)

Example 2: Only Real Part

z = complex(5)
print(z)
(5+0j)

Example 3: Using a String

z = complex("2+3j")
print(z)
(2+3j)

Note: If you use a string, it must be a valid complex number format.

Real-World Use Cases

  • Electrical engineering: representing impedance or current with imaginary components
  • Signal processing and physics simulations
  • Mathematics involving imaginary numbers

Accessing Real and Imaginary Parts

z = complex(3, 4)
print(z.real)   # Output: 3.0
print(z.imag)   # Output: 4.0

Common Mistakes

  • Passing a string with space: complex("2 + 3j") will raise a ValueError.
  • You can’t pass both a string and a second argument: complex("3+4j", 2) is invalid.

Interview Tip

Complex numbers are rarely asked directly in interviews, but you may encounter them in signal processing or competitive math problems. Know how to extract .real and .imag values.

Summary

  • complex() creates a complex number.
  • You can pass real and imaginary parts as numbers or a single valid string.
  • Access components with .real and .imag.

Practice Problem

Write a program that reads two numbers from the user and creates a complex number:

real = float(input("Enter real part: "))
imag = float(input("Enter imaginary part: "))
z = complex(real, imag)
print("The complex number is:", z)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M