English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
When real and imaginary parts are provided, the complex() method will return a complex number, or convert a string to a complex number.
The syntax of complex() is:
complex([real[, imag]])
Typically, the complex() method takes two parameters:
real -Real part. If omittedrealit is set to 0 by default.
imag-Imaginary part. If omittedimagit is set to 0 by default.
If the first parameter passed to this method is a string, it will be interpreted as a complex number. In this case, no second parameter should be passed.
As the name implies, the complex() method returns a complex number.
If the string passed to this method is not a valid complex number, a ValueError exception will be raised.
Note:The string passed to complex() should be real+imagj or real+imagj format
z = complex(2, -3) print(z) z = complex(1) print(z) z = complex() print(z) z = complex('5-9j') print(z)
When running this program, the output is:
(2-3j) (1+0j) 0j (5-9j)
You can create a complex number without using the complex() method. To do this, you must add 'j' or 'J' to the end of the number.
a = 2+3j print('a =', a) print('The type of a is', type(a)) b = -2j print('b =', b) print('The type of b is', type(b)) c = 0j print('c =', c) print('The type of c is', type(c))
When running this program, the output is:
a = (2+3j) The type of a is <class 'complex'> b = (-0-2j) The type of b is <class 'complex'> c = 0j The type of c is <class 'complex'>