Converts a string or number to a complex number
Usage
The complex()
function creates a complex number when real and imaginary parts are specified.
It can also convert a string to a complex number.
The complex number is returned in the form of real + imaginary, where the imaginary part is followed by a j.
Syntax
complex(real,imaginary)
Parameter | Condition | Description |
real | Optional | The real part of the complex number. Default is 0. |
imaginary | Optional | The imaginary part of the complex number. Default is 0. |
Creating Complex Numbers
You can create a complex number by specifying real and imaginary parts.
x = complex(3, 2)
print(x)
# Prints (3+2j)
x = complex(-3, 2)
print(x)
# Prints (-3+2j)
x = complex(3, -2)
print(x)
# Prints (3-2j)
If you omit one of the arguments, it is assumed as 0; because the default value of real and imaginary parameters is 0.
# omit imaginary part
x = complex(3)
print(x)
# Prints (3+0j)
# omit real part
x = complex(0, 4)
print(x)
# Prints 4j
# omit both
x = complex()
print(x)
# Prints 0j
Convert a String to a Complex Number
You can convert a string to a complex number by specifying the first parameter as a string like '3+4j'
. In this case the second parameter should be omitted.
# Convert a string '3+4j' to a complex number
x = complex('3+4j')
print(x)
# Prints (3+4j)
When converting from a string, the string must not contain whitespace around the central + or – operator. Otherwise, the function raises ValueError
.
# Triggers ValueError: complex() arg is a malformed string
x = complex('3 + 4j')
print(x)