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 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.

说明:

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

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

>>> complex()
0j
  1. 当第一个参数为字符串时,调用时不能提供第二个参数。此时字符串参数,需是一个能表示复数的字符串,而且加号或者减号左右不能出现空格。
>>> complex('1+2j',2) #第一个参数为字符串,不能接受第二个参数
Traceback (most recent call last): 
    File "<pyshell#2>", 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#3>", line 1, in <module> 
      complex('1 + 2j')
ValueError: complex() arg is a malformed string
  1. 当第一个参数为int或者float时,第二个参数可为空,表示虚部为0;如果提供第二个参数,第二个参数也需为int或者float。
>>> complex(2)
(2+0j)
>>> complex(2.1,-3.4)
(2.1-3.4j)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • 致求职者:公司为什么会录用你?//www.greatytc.com/p/ab13cfbd50c7 1, 做...
    阶梯阅读 1,243评论 0 1
  • 夏至已至,春日已远,离你而去,该是怎样的情形。 曾无数次想过,毕业会是怎样的一番情景。 曾无数次提笔,为过往或多或...
    对木阅读 3,624评论 1 3
  • 今天上午我得了一朵小红花,因为我的坐姿比要端正,今天下午六得了一朵小红花,因为作业写得比较工整,谢谢老师我会一直保...
    王云汉1阅读 1,126评论 0 0

友情链接更多精彩内容