What is the complex() function in Python?

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.

Signature

Complex([real[,imaginary]])

Parameters

  • 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.

Return

The complex() method returns a complex number. It can also accept and return double-precision floating point values.

Exception Handling

If a string that is not a valid complex number is passed as an argument, it returns a ValueError exception error.

Code

Here are a few examples of complex() to get to know how to use it:

  • Case #1: This one is a simple example in which we use complex() function. We are passing only integer type arguments here.
  • Case #2: We are passing arguments of float type here and the output that is generated by the function is also a float type.
  • Case #3: This method allows a string parameter to be passed provided it is a string representation of a numeric value. The numeric value can be either an integer or a floating-point value. It is important to note that if we are passing a string as the first argument, the function will not accept the second argument. Passing a second value would give an error.
  • Case #4: It permits only one string parameter. If the first argument is a string type, then it does not allow passing the second argument. It will generate an error if we pass the second parameter. TypeError: complex() can't take second arg if first is a string
  • Case #5: It allows passing a complex number as a parameter formatted like (a+bj) where a,b ∈ ℝ.
  • Case #6: Although this method allows passing the first argument as a string value, it only allows strings that contain numeric values. It will generate the above error. ValueError: complex() arg is a malformed string

Check out the following example:

# Python complex() function example
# Calling function
x = complex(4) # Passing single parameter
y = complex(2,5) # Passing both parameters
# Displaying result
print(x)
print(y)

Free Resources