Python built in function complex

  • 2020-05-12 02:52:44
  • OfStack

English documents:

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.

Description:

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

2. Returns the complex number 0j when neither parameter is provided.


>>> complex()
0j
 

3. When the first parameter is a string, the second parameter cannot be provided when calling. In this case, the string parameter should be a string that can represent a complex number, and the plus or minus sign cannot appear Spaces.


>>> complex('1+2j',2) # The first 1 The number of arguments is a string 2 A parameter 
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') # You can't have Spaces 
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 should also be int or float.


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

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: