Skip to content

Python complex() Function

How to create complex numbers in Python using the complex() function with real and imaginary parts, or convert strings to complex numbers.

The complex() function returns a complex number by specifying a real number and an imaginary number.

It can also convert a string to a complex number.

Syntax

complex(real,imaginary)

complex() Parameters

Python complex() function parameters:

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.

complex() Return Value

Python complex() function returns a complex number.

Examples

Create complex numbers

You can create a complex number by specifying real and imaginary parts.

x = complex(3, 2)
print(x)            # Output: (3+2j)

x = complex(-3, 2)
print(x)            # Output: (-3+2j)

x = complex(3, -2)
print(x)            # Output: (3-2j)

output

(3+2j)
(-3+2j)
(3-2j)

Create complex numbers by omitting arguments

If you omit one of the arguments, it is assumed to be 0, because the default value of real and imaginary parameters is 0.

x = complex(3)
print(x)            # Output:(3+0j)

x = complex(0, 4)
print(x)            # Output: 4j

x = complex()
print(x)            # Output: 0j

Create complex number without using complex() function

It's possible to create a complex number without using complex() function: you have to put j or J after a number.

a = 2+3j
print('a =',a)
print('Type of a is',type(a))

b = -2j
print('b =',b)
print('Type of b is',type(a))

c = 0j
print('c =',c)
print('Type of c is',type(c))

output

a = (2+3j)
Type of a is <class 'complex'>
b = (-0-2j)
Type of b is <class 'complex'>
c = 0j
Type of c is <class 'complex'>
Navigation