Python complex() function


The complex() function in Python is used to create a complex number, which is a number that has a real part and an imaginary part. Complex numbers are represented as a + bj, where a is the real part and b is the imaginary part (with j denoting the imaginary unit).

Syntax

complex([real[, imag]])
  • real (optional): The real part of the complex number. This can be an integer or a float.
  • imag (optional): The imaginary part of the complex number. This can also be an integer or a float. If omitted, it defaults to 0.

Return Value

  • Returns a complex number represented as a + bj.

Examples

  1. Creating a complex number with both real and imaginary parts:

    z1 = complex(2, 3) print(z1) # Output: (2+3j)
  2. Creating a complex number with only the real part: If you provide only one argument, it will be treated as the real part, and the imaginary part defaults to 0.

    z2 = complex(5) print(z2) # Output: (5+0j)
  3. Creating a complex number with a negative imaginary part: You can also specify negative values for the imaginary part.

    z3 = complex(4, -2) print(z3) # Output: (4-2j)
  4. Creating a complex number from a string: You can also create a complex number by passing a string representation of a complex number.

    z4 = complex("1+2j") print(z4) # Output: (1+2j)
  5. Using float values for both parts: You can use floating-point numbers for both the real and imaginary parts.

    z5 = complex(3.5, 2.5) print(z5) # Output: (3.5+2.5j)
  6. Using the real and imag attributes: Once you have a complex number, you can access its real and imaginary parts using the .real and .imag attributes.

    print(z1.real) # Output: 2.0 print(z1.imag) # Output: 3.0
  7. Complex conjugate: You can get the complex conjugate of a complex number using the conjugate() method.

    print(z1.conjugate()) # Output: (2-3j)

Summary

  • The complex() function creates a complex number in Python, represented as a + bj.
  • You can specify both the real and imaginary parts, or just the real part.
  • It can accept string representations of complex numbers.
  • Complex numbers have properties like accessing their real and imaginary parts and obtaining their conjugate.