Introduction to Python standard library built in functions complex

  • 2020-04-02 14:23:27
  • OfStack

This function can create a complex number with the parameter real + imag*j. You can also convert the number of a string to a complex number; Or convert a number to a complex number. If the first argument is a string and the second argument is left blank, the string is interpreted and the complex number is returned. However, the second parameter cannot be entered in string mode, otherwise an error will occur. The real and imag parameters can be entered as Numbers, and if the imag parameter is not entered, it is zero by default, which is the function equivalent of int() or float(). If the real and imag arguments are both zero, this function returns 0j. With this function, you can easily transform a list into a complex number.

Note: when converting complex Numbers from the complex form of a string, it is important to note that there are no Spaces in the middle of the string, such as complex(' 1+2j') instead of complex(1 +2j'), otherwise a ValueError exception will be returned.

Example:


#complex() print(complex(1))
print(complex('2+1j'))
print(complex(2, 5)) l = [1, 3, 4, 5]
for i in l:
 print(complex(i, 5))

The output is as follows:


(1+0j) (2+1j) (2+5j) (1+5j) (3+5j) (4+5j) (5+5j)


Related articles: