Python 内置函数complex详解

yipeiwu_com5年前Python基础

英文文档:

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
 

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

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

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

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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

python批量下载网站马拉松照片的完整步骤

python批量下载网站马拉松照片的完整步骤

前言 目前学习python几个月了,由于自己比较喜欢跑马拉松,已经跑过了很多场比赛,前些天就写了个简单的爬虫爬取了网上三千多场马拉松比赛的报名信息。 今年5月27日,我又参加了巴图鲁...

python xlsxwriter库生成图表的应用示例

python xlsxwriter库生成图表的应用示例

xlsxwriter可能用过的人并不是很多,不过使用后就会感觉,他的功能让你叹服,除了可以按要求生成你所需要的excel外 还可以加上很形象的各种图,比如柱状图、饼图、折线图等。 xls...

Python设计模式之MVC模式简单示例

Python设计模式之MVC模式简单示例

本文实例讲述了Python设计模式之MVC模式。分享给大家供大家参考,具体如下: 一.简单介绍 mvc模式  the  model-view-controller p...

Python将图片转换为字符画的方法

Python将图片转换为字符画的方法

最近在学习Python,看到网上用Python将图片转换成字符画便来学习一下 题目意思是,程序读入一个图片,以txt格式输出图片对应的字符画,如图所示: 以下是Python代码:...

Python数据类型之List列表实例详解

本文实例讲述了Python数据类型之List列表。分享给大家供大家参考,具体如下: list列表 1.概述: 通过之前的学习,我们知道变量可以存储数据,但是一个变量只能存储一个数据,现...