Python 3 reference · Built-in Functions
Python complex() Function
Create a complex number from a real and an imaginary part, or parse one from a string such as '1+2j'.
Python 3 Since 3.0
Syntax
complex(real=0, imag=0)
complex(string)
Parameters
| Parameter | Description |
|---|---|
real optional |
The real part, a number or a string. Default: 0 |
imag optional |
The imaginary part. Default: 0 |
Return value
A complex number.
Examples
z = complex(3, 4)
print(z, z.real, z.imag)
print(abs(z))
Output
(3+4j) 3.0 4.0 5.0
print(complex("1+2j"))
print((1 + 2j) * (3 - 1j))
print((1 + 2j).conjugate())
Output
(1+2j) (5+5j) (1-2j)
Good to know
- Python writes the imaginary unit as
j:2 + 3j. - Strings must have no spaces:
complex("1+2j")works,complex("1 + 2j")raisesValueError. - For complex maths functions (
sqrtof negatives,exp,phase) use thecmathmodule.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
abs()· Return the absolute value of a number: its distance from zero, so negative numbers become positive.float()· Convert a number or numeric string to a floating-point number. Also understands 'inf', '-inf' and 'nan'.int()· Convert a number or string to an integer. Floats are truncated toward zero, and strings can be in any base from 2 to 36.- Python Numbers · tutorial