How can I understand using of complex() function?
In python documentation it is wrote for built-in function complex([real[imag]]):
..or convert a string or number to a complex number.
But when I try:
>>开发者_运维问答;> complex('string')
I get:
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: complex() arg is a malformed string
I don't understand something. I will be glad if someone tells me what is about? Sorry if this question is simple, but i just start to learn python.
complex
is a data type for complex numbers.
http://en.wikipedia.org/wiki/Complex_number
Examples on constructing them:
>>> complex(1, 2)
(1+2j)
>>> complex('1+2j')
(1+2j)
>>> complex(0)
0j
>>> complex(1)
(1+0j)
>>> complex(1) + complex(0, 1)
(1+1j)
If you aren't familiar with complex or imaginary numbers, you can probably just move on and not worry about any of this. =)
The complex
function is used for working with complex numbers (http://en.wikipedia.org/wiki/Complex_number), of the form a+bj. So you can use it like this:
>>> a = complex("1+2j")
>>> a
(1+2j)
>>> a*a
(-3+4j)
"string" isn't a complex number. The proper usage is as follows:
>>> a = complex('3j')
>>> a
3j
>>> b = 4 + a
>>> b
(4+3j)
'string' is not a number. It's not anything like a number.
How can you compute a complex value of string
? It's not a number
Try using numbers or string representations of numbers
complex(2)
complex('3')
精彩评论