The Python complex() is a built-in function that returns a complex number with real and imaginary values (eg. real + imag*j). It converts a string or a number into a complex number.

python complex() function

Python complex() Function Syntax

complex([real[,imag]])

As you can see in the syntax above, the complex() function takes two parameters:

  • real: It is the real part of the complex number if omitted defaults to 0.
  • imag: It is the imaginary part which also defaults to 0 if omitted.

If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string.

How to create a complex number in Python using complex() function?

>>> complex()
0j
>>> complex(2)
2+0j
>>> complex(2,3)
2+3j
>>> complex('2)  #passing string
2+0j
>>> complex('1+2j')
1+2j
>>> complex(1+1j,2+2j)
3+3j