Python complex() function returns a complex number ( real + imaginary) example (5+2j) when real and imaginary parts are passed, or it also converts a string to a complex number.
Python complex() Function Syntax
Syntax: complex ([real[, imaginary]])
- real [optional]: numeric type (including complex). It defaults to zero.
- imaginary [optional]: numeric type (including complex) .It defaults to zero.
Return: Returns a complex number in the form of (real + imaginary) example (5+2j)
Note: If the first parameter that passed is a string then the second parameter shouldn’t be passed else will raise TypeError. The string must not contain whitespace around + or – operator else it will raise ValueError in Python.
Python complex() Function Example
print(complex(1, 2))
|
Output:
(1+2j)
Example 1:
Using complex() with Integer and Float type parameters.
# numeric type# nothing is passedz = complex()
print("complex() with no parameters:", z)
# integer type# passing first parameter onlycomplex_num1 = complex(5)
print("Int: first parameter only", complex_num1)
# passing both parameterscomplex_num2 = complex(7, 2)
print("Int: both parameters", complex_num2)
# float type# passing first parameter onlycomplex_num3 = complex(3.6)
print("Float: first parameter only", complex_num3)
# passing both parameterscomplex_num4 = complex(3.6, 8.1)
print("Float: both parameters", complex_num4)
print()
# typeprint(type(complex_num1))
|
Nothing is passed 0j Int: first parameter only (5+0j) Int: both parameters (7+2j) Float: first parameter only (3.6+0j) Float: both parameters (3.6+8.1j) <class 'complex'>
Example 2:
Using complex() with string type parameters of the numeric form.
# string# only first parameter is to be passedz1 = complex("7")
print(z1)
print()
z2 = complex("2", "3")
# This will raise TypeError"print(z2)
|
Output:
Example 3:
Using complex() with string type parameters of Complex Number form.
# string# only first parameter is passedz1 = complex("7+17j")
print(z1)
print()
z2 = complex("7 + 17j")
# This will raise Valueerror# due to spaces around operatorprint(z2)
|
Output:

