Python内置函数(13)-complex
官方文档
class complex([real[, imag]])
-
Return a complex number with the value real + imag*1j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the constructor serves as a numeric conversion like
intandfloat. If both arguments are omitted, returns0j.Note
When converting from a string, the string must not contain whitespace around the central
+or-operator. For example,complex('1+2j')is fine, butcomplex('1 + 2j')raisesValueError.The complex type is described in Numeric Types — int, float, complex.
Changed in version 3.6: Grouping digits with underscores as in code literals is allowed.
说明:1.函数功能,返回一个复数,有2个可选参数
2.当两个参数都不提供时,返回复数0j
>>> complex() 0j3.当第一参数为字符串时,调用时不能传第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加减号左右不能有空格
#第一个参数为字符串时,调用不能传第二个参数
>>> complex('1+2j',2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: complex() can't take second arg if first is a string
#加减号左右不能有空格
>>> complex('1 + 2j')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: complex() arg is a malformed string
>>> complex('1+2j')
(1+2j)4.当第一个参数为int或者float时,第二个参数可为空,表示虚部为0。如果提供第二个参数,则第二个参数也需要为int或者float
ret = complex(123) print(ret) #输出 (123+0j) ret = complex(2.14,-3.16) print(ret) #输出 (2.14-3.16j)


浙公网安备 33010602011771号