Python complex() Function
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 a TypeError. The string must not contain whitespace around the + or – operator else it will raise ValueError in Python.
complex() Function in Python
In this example, we will see how to create a complex number in Python using complex() function.
Python3
print(complex(1, 2)) |
Output:
(1+2j)
complex() With Integer and Float Type Parameters
In this example, we are using complex() to create a complex number in Python with integer and float type parameters.
Python3
# 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'>
complex() With String Type Parameters of the Numeric Form
In this example, we are using complex() to create a complex number in Python with String Type Parameters of the Numeric Form.
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

complex() with String Type Parameters of Complex Number Form
In this example, we are using complex() to create a complex number in Python with string type parameters of Complex Number form.
Python3
# 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


