Python3.6内置函数(13)——complex()

浏览: 1444

英文文档

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 int and float. If both arguments are omitted, returns 0j.

Note:When converting from a string, the string must not contain whitespace around the central + or – operator. For example, complex(‘1+2j’) is fine, but complex(‘1 + 2j’) raises ValueError.

complex()

1、函数功能,返回一个复数。有两个可选参数。

2、当两个参数都不提供时,返回复数 0j。

>>> complex
<class 'complex'>
>>> complex()
0j


3、当第一个参数为字符串时,调用时不能提供第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加号或者减号左右不能出现空格。

>>> complex('1+2j',2) #第一个参数为字符串,不能接受第二个参数
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    complex('1+2j',2) #第一个参数为字符串,不能接受第二个参数
TypeError: complex() can't take second arg if first is a string
>>> complex('1 + 2j') #不能有空格
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    complex('1 + 2j') #不能有空格
ValueError: complex() arg is a malformed string


4、当第一个参数为int或者float时,第二个参数可为空,表示虚部为0;如果提供第二个参数,第二个参数也需为int或者float。

>>> complex(2)
(2+0j)
>>> complex(2.1, -1.9)
(2.1-1.9j)

小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,希望你留言和我进行交流、讨论。

欢迎关注微信公众号,访问更多精彩:数据之魅

如需转载,请联系授权,谢谢合作。

火狐截图_2019-06-29T07-07-45.688Z.png

推荐 0
本文由 Airy 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册