Contents
To convert int to complex in python, you can use complex() class with the int passed as an argument to it or add imaginary part to the integer so that the variable would typecast implicitly to complex datatype.
Example 1: Typecasting Int value to Complex
In this example, we will take an int, print it and its type, convert it to complex type and the print the result.
Python Program
a = 5
print(a,'is of type:',type(a))
a = complex(a)
print(a,'is of type:',type(a))
Run Output
5 is of type: <class 'int'>
(5+0j) is of type: <class 'complex'>
Example 2: Another way to cast Int variable to Complex datatype
There is another way. You can always add a 0 imaginary part and python promotes the variable to the higher type, which in this case from int to complex.
Python Program
a = 5
print(a,'is of type:',type(a))
a = a + 0j
print(a,'is of type:',type(a))
Run Output
5 is of type: <class 'int'>
(5+0j) is of type: <class 'complex'>
Summary
In this tutorial of Python Examples, we converted variable of int datatype to variable of complex datatype, with the help of well detailed example programs.