Home  >  Article  >  Backend Development  >  Detailed explanation of Python built-in function complex

Detailed explanation of Python built-in function complex

WBOY
WBOYOriginal
2016-12-05 13:27:131761browse

English document:

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.

Instructions:

 1. Function function, returns a complex number. There are two optional parameters.

 2. When neither parameter is provided, the complex number 0j is returned.

>>> complex()
0j
 

 3. When the first parameter is a string, the second parameter cannot be provided when calling. At this time, the string parameter must be a string that can represent a plural number, and there must be no spaces around the plus or minus sign.

>>> 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. When the first parameter is int or float, the second parameter can be empty, indicating that the imaginary part is 0; if the second parameter is provided, the second parameter must also be int or float.

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

Thanks for reading, I hope it can help you, thank you for your support of this site!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn