Python complex() Function
Last Updated :
15 Nov, 2023
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.
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
z = complex()
print("complex() with no parameters:", z)
complex_num1 = complex(5)
print("Int: first parameter only", complex_num1)
complex_num2 = complex(7, 2)
print("Int: both parameters", complex_num2)
complex_num3 = complex(3.6)
print("Float: first parameter only", complex_num3)
complex_num4 = complex(3.6, 8.1)
print("Float: both parameters", complex_num4)
print()
print(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'>
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
z1 = complex("7")
print(z1)
print()
z2 = complex("2", "3")
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
z1 = complex("7+17j")
print(z1)
print()
z2 = complex("7 + 17j")
print(z2)
|
Output

Please Login to comment...