In Python, the complex() function is used to create a complex number object. It can accept two parameters representing the real and imaginary parts of the complex number, or just one parameter, in which case the real part is set to that parameter and the imaginary part is set to 0.
complex() Function Usage Examples
Here are some examples of creating complex numbers using the complex() function:
# Create complex number with integer real and imaginary parts
z1 = complex(2, 3) # z1 = 2 + 3j
# Create complex number with float real and imaginary parts
z2 = complex(1.5, -0.5) # z2 = 1.5 - 0.5j
# Pass only one parameter: real part set to parameter, imaginary part to 0
z3 = complex(4) # z3 = 4 + 0j
# Create complex number from string
z4 = complex('2+3j') # z4 = 2 + 3j
You can use the real and imag attributes to access the real and imaginary parts of a complex number object, and the conjugate() method to obtain the complex conjugate. For example:
z = complex(2, 3)
print(z.real) # Output: 2.0
print(z.imag) # Output: 3.0
print(z.conjugate()) # Output: 2-3j