Python complex() Function (original) (raw)
Last Updated : 01 Mar, 2025
Python provides a built-in function called complex() to handle complex numbers. A complex number consists of a real part and an imaginary part, represented in the form:
a + bj
Where,
- a is the real part
- b is the imaginary part
- j is the imaginary unit, which is equal to the square root of -1
python uses ‘j’ instead of ‘i’ (used in mathematics) to represent imaginary numbers.
We can access the real and imaginary parts of the complex numbers using .real and .imag methods respectively.
**Example:
Python `
Creating complex numbers
c1 = complex(3, 4)
c2 = complex(5)
c3 = complex()
print(c1) print(c2) print(c3) print(c1.real) print(c1.imag)
`
Output
(3+4j) (5+0j) 0j 3.0 4.0
Let’s explore complex() function in detail:
Table of Content
- Syntax of complex() function
- complex() with Int and Float Parameters
- complex() with String inputs
- Arithmetic of Complex Numbers
Syntax of complex() function
- **Without any arguments: complex() returns 0j.
- **With one argument: complex(x) returns x + 0j.
- **With two arguments: complex(x, y) returns x + yj.
- **With a string argument: complex(string) interprets the string as a complex number.
- **real: The real part of the complex number(default is 0).
- **imaginary: The imaginary part of the complex number(default is 0).
complex()
with Int and Float Parameters
When we pass integer or float parameters to the complex()
function, it creates a complex number with the given real and imaginary parts.
**Example:
Python `
c1 = complex(3, 4) print(c1)
c2 = complex(2.5, 3.7)
print(c2)
`
complex() with String inputs
We can also pass a string to the complex()
function, provided that the string represents a valid complex number or a real number. The string can be in the form of "a+bj"
or simply "a"
where a
and b
are real numbers.
Python `
c1 = complex("5.5")
print(c1)
c2 = complex("-2")
print(c2)
c3 = complex("3+4j")
print(c3)
`
Output
(5.5+0j) (-2+0j) (3+4j)
**Explanation:
- If the string contains only a real number, **complex() treats it as having an imaginary part of zero (0j).
- If the string contains both a real and imaginary part, Python correctly interprets it as a complex number.
Note: spaces around operators are not allowed and hence, passing such example will throw an error. For example, if we did complex(” 2.3 + 4.5j “), it will throw “**ValueError: complex() arg is a malformed string”**
Arithmetic of Complex Numbers
Python `
c1 = complex(4, 3) c2 = complex(2, -5)
print(c1+c2) # adds c1 and c2 print(c1-c2) # subtracts c1 and c2 print(c1*c2) # multiplies c1 and c2 print(c1/c2) # divides c1 and c2
Accessing real and imaginary parts
print(c1.real) print(c1.imag)
`
Output
(6-2j) (2+8j) (23-14j) (-0.24137931034482757+0.896551724137931j) 4.0 3.0