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的request.POST获取不到内容的问题

我通过如下的一段程序发送post请求: import urllib3 pool = urllib3.connection_from_url('http://127.0.0.1:809...

Python简单操作sqlite3的方法示例

本文实例讲述了Python简单操作sqlite3的方法。分享给大家供大家参考,具体如下: import sqlite3 def Test1(): #con =sqlite3.co...

Python+OpenCV让电脑帮你玩微信跳一跳

Python+OpenCV让电脑帮你玩微信跳一跳

前言 最近微信小游戏跳一跳大热,自己也是中毒颇久,无奈手残最高分只拿到200分。无意间看到教你用Python来玩微信跳一跳一文,在电脑上利用adb驱动工具操作手机,详细的介绍以及如何安装...

Python搭建APNS苹果推送通知推送服务的相关模块使用指南

APNS 是苹果为IOS设备提供的推送服务,全称是(Apple Push Notification service)。 如果你有接触移动互联网相关的开发的话,应该对它很熟悉。 接下来我会...

python 将print输出的内容保存到txt文件中

具体代码如下所示: import sys import os class Logger(object): def __init__(self, filename="Default...