33
loading...
This website collects cookies to deliver better user experience
complex()
function takes real, imaginary numbers and strings as input and converts them into a complex number. This method takes two optional parameters ( real and imaginary ) and returns a complex number as output.complex()
is:**complex([real[, imaginary]])**
complex()
method can take two parameters, and both are optional.3+5j
‘. If not set anything, it defaults to 0.complex('1+2j')
is fine, but complex('1 + 2j')
raises ValueError.# Code to illustrate complex number
# covert real number to complex
num = complex(5,3)
print(num)
# covert real number to complex
num = complex(5,-4)
print(num)
# Default if no parameter is passed to complex method
num = complex()
print(num)
# In case if you pass only real number, defaults imaginary to 0
num = complex(5)
print(num)
# In case if you pass only real number, defaults imaginary to 0
num = complex(-2)
print(num)
# In case if you pass only float number, defaults imaginary to 0
num = complex(5.6,4)
print(num)
# if string is passed, it will be interpreted as complex number
num = complex('8')
print(num)
# if string is passed, it will be interpreted as complex number
num = complex('1+2j')
print(num)
(5+3j)
(5-4j)
0j
(5+0j)
(-2+0j)
(5.6+4j)
(8+0j)
(1+2j)
# Code to illustrate complex number
# if string is passed with imaginary number
num = complex('8',5)
print(num)
Traceback (most recent call last):
File "c:\Projects\Tryouts\listindexerror.py", line 4, in <module>
num = complex('8',5)
TypeError: complex() can't take second arg if first is a string
# if you give a space in the string
num = complex('1 + 2j')
print(num)
Traceback (most recent call last):
File "c:\Projects\Tryouts\listindexerror.py", line 4, in <module>
num = complex('1 + 2j')
ValueError: complex() arg is a malformed string