In Python, functions complex() Returns a complex number when the user provides real and imaginary parts, or turns a string into a complex number. Function syntax complex() How, what parameters does it have and how to use it? We invite readers to follow along.
Complex() function syntax in Python
complex([phanthuc[, phanao]])
Parameters of the complex() function
complex. complex has two parameters:
- phanthuc: real part of the returned complex number. If this parameter is left blank, Python defaults the value to 0.
- phanao: imaginary part of the returned complex number. If this parameter is left blank, Python defaults the value to 0.
If the first parameter is passed in complex. complex is a string, it will be interpreted as a complex number. In this case you should not pass in the second parameter.
Return value from complex()
Jaw complex() returns a complex number.
If the string passed into the function is not a complex number, an exception will occur. ValueError.
Attention: The string passed must be of the form phanthuc+phanaoj or phanthuc+phanaoJ.
Example 1: How to create complex numbers in Python
z = complex(2, -3)
print(z)
z = complex(1)
print(z)
z = complex()
print(z)
z = complex('5-9j')
print(z)
Run the program, the returned results are:
(2-3j)
(1+0j)
0j
(5-9j)
Example 2: Creating complex numbers without using the complex() function
In Python, you can create a complex number without using a function complex()
To do that, you must place 'j' or 'J' after a number for Python to recognize.
a = 2+3j
print('a=",a)
b = -2j
print("b =',b)
c = 0j
print('c=",c)
The output returned is:
a = (2+3j)
b = (-0-2j)
c = 0j
See more:
Previous lesson: Classmethod() function in Python
Next lesson: Compile() function in Python