Python complex() Function
Python complex() function is a built-in function in python. This method 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.
Syntax:
complex ([real[, imaginary]])
Parameter:
- real : numeric type (including complex).It defaults to zero.
- imaginary : numeric type (including complex) .It defaults to zero.
Return:
- A complex number in the form of ( real + imaginary) example (5+2j)
- type : complex
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.
Example 1:
Python3
# numeric type# nothing is passedz = complex()print("Nothing is passed", 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)) |
Output
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:
Python3
# 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:
Python3
# string# only first parameter is passedz1 = complex("7+17j")print(z1) print()z2 = complex("7 + 17j") # This will raise Valueerrorprint(z2) |
Output:





