Python complex() method

The complex() method returns a complex number for the provided real value and imaginary*1j value, or converts a string or number to a complex number.

Syntax:

complex(real, imaginary)
complex(string)

Parameters:

  1. real: (Optional) A number. Default is 0.
  2. imaginary: (Optional) A number that will be multiply with 1j. Default is 0.
  3. string: (Optional) If the string is passed as arguement, the string is converted to the complex number.

Return Value:

Returns a complex number.

The following example converts the real numbers and imaginary numbers into complex numbers.

Example: complex()
cnum = complex()
print(cnum)
print(type(cnum)) # complex

cnum = complex(2, 5)
print(cnum)

cnum = complex(5)
print(cnum)

cnum = complex(-5)
print(cnum)

Output
0j
<class 'complex'>
(2+5j)
(5+0j)
(-5+0j)

Note that the type of return value is 'complex'.

The following converts strings into complex numbers using the complex() method.

Example:
cnum = complex('5-3j')
print(cnum)

cnum = complex('3+j')
print(cnum)

complex('3')
print(cnum)

complex('+j')
print(cnum)

complex('-j')
print(cnum)

Output
(5-3j)
(3+1j)
(3+0j)
1j
-1j