In this tutorial we will discuss about the complex() function in python programming language with the help of examples.
Python complex() function
The built-in python function is used to convert string into complex number or when a real and imaginary parts (i.e., 3+7j) are provided it returns a complex number. The string passed to complex() function should be in form.
Syntax
complex([real[, imag]])
Parameters of complex() function in python
The complex() function in python takes two parameters;
• - numeric type real part. 0 is to be the default value, if real part is omitted.
• - numeric type imaginary part. 0 is to be the default value, if imag part is omitted.
Return value of Python complex() function
In python, when a real and imaginary parts are provided function returns a complex number. It is also used to convert string into complex number. The string passed to complex() function should be in form.
Note - If the passed string is not a valid complex number then it will raise a [ValueError] exception.
Example 1: Creating a complex number in Python
x = complex(7, -2)print(x)
x = complex(5)
print(x)
x = complex()
print(x)
x = complex('6-8j')
print(x)
Output
(7-2j)(5+0j)
0j
(6-8j)
Example 2: Creating complex Number Without Using Python complex() function
a = 5+8jprint('a =',a)
print('Type of a is',type(a))
b = -3j
print('b =',b)
print('Type of b is',type(a))
c = 0j
print('c =',c)
print('Type of c is',type(c))
Output
a = (5+8j)Type of a is <class 'complex'>
b = (-0-3j)
Type of b is <class 'complex'>
c = 0j
Type of c is <class 'complex'>
Example 3: The strings to be used as parameters in python complex() Function
x = complex('5')y = complex('1.7')
print(x)
print(y)
Output
(5+0j)
(1.7+0j)
Example 4: The Python complex() function accepts only one string parameter as the input
x = complex('7','4')
print(x)
Output
TypeError: complex() can't take the second arg if first is a string