The complex() function is used to convert numbers or strings into a complex number. The first parameter corresponds to the real part. The second, which is optional, specifies the imaginary part of that complex number.
Complex([real[,imaginary]])
real: It is the first argument that is a numerical parameter.imaginary(Optional): It is the second argument that is also a numerical value.Both values are zero by default.
If the first parameter passed to this method is a string or a character array, it will be interpreted as a complex number. In that case, passing the second parameter would throw an error.
The complex() method returns a complex number. It can also accept and return double-precision floating point values.
If a string that is not a valid complex number is passed as an argument, it returns a ValueError exception error.
Here are a few examples of complex() to get to know how to use it:
complex() function. We are passing only integer type arguments here.TypeError: complex() can't take second arg if first is a string(a+bj) where a,b ∈ ℝ.ValueError: complex() arg is a malformed stringCheck out the following example:
# Python complex() function example# Calling functionx = complex(4) # Passing single parametery = complex(2,5) # Passing both parameters# Displaying resultprint(x)print(y)