Python 内置函数complex详解

yipeiwu_com6年前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)
 

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

相关文章

django实现登录时候输入密码错误5次锁定用户十分钟

django实现登录时候输入密码错误5次锁定用户十分钟

在学习django的时候,想要实现登录失败后,进行用户锁定,切记录锁定时间,在网上找了很多资料,但是都感觉不是那么靠谱,于是乎,我开始了我的设计,其实我一开始想要借助redis呢,但是想...

python中partial()基础用法说明

前言 一个函数可以有多个参数,而在有的情况下有的参数先得到,有的参数需要在后面的情景中才能知道,python 给我们提供了partial函数用于携带部分参数生成一个新函数。 在funct...

如何使用python把ppt转换成pdf

ppt要想完美的转pdf,图片,还是需要在windows下面来操作。 1,安装python3.5.1 下载地址 Windows x86-64 executable installer,w...

在python中画正态分布图像的实例

在python中画正态分布图像的实例

1.正态分布简介 正态分布(normal distribtution)又叫做高斯分布(Gaussian distribution),是一个非常重要也非常常见的连续概率分布。正态分布大家也...

Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)

环境: Python3.7 依赖库: import datetime import random import requests import hashlib import json...