Python Tutorial Python Advanced Python References Python Libraries

Python complex() Function



The Python complex() function returns a complex number with specified real part and imaginary part. It has one required parameter which is used to specify real part of the complex number and one optional parameter which is used to specify imaginary part of the complex number.

Syntax

complex(real, imaginary)

Parameters

real Required. specify real part of complex number.
imaginary Optional. specify imaginary part of complex number.

Example:

In the example below, complex() function is used to create a complex number with specified real and imaginary parts.

MyNumber = complex(2)
print(MyNumber)

MyNumber = complex(2, 3)
print(MyNumber)

The output of the above code will be:

(2+0j)
(2+3j)

The complex() function is also used to convert an integer literal, a float literal and a string literal (provided the string represents a complex number).

Example:

In the example below, complex() function is used to convert an integer literal, a float literal and a string literal into a complex number.

MyInt = 10
MyNumber = complex(MyInt)
print(MyNumber)

MyFloat = 10.5
MyNumber = complex(MyFloat)
print(MyNumber)

MyString = '5'
MyNumber = complex(MyString)
print(MyNumber)

MyString = '5+5j'
MyNumber = complex(MyString)
print(MyNumber)

The output of the above code will be:

(10+0j)
(10.5+0j)
(5+0j)
(5+5j)

❮ Python Built-in Functions