Convert Int to Complex in Python - Examples


Convert Int to Complex Number

To convert int to complex in python, call complex() builtin function with the given int value passed as argument. Or else, we can add imaginary part to the integer, so that the Python Interpreter would typecast it implicitly to complex datatype.

In this tutorial, we will learn how to convert int to complex numbers, with the above said two methods.

1. Convert Int to Complex using complex() built-in function

In this example, we will take an int value in variable a, convert it to complex type value and store it in output.

Python Program

#take an intger
a = 5
print('Input', a, type(a), sep='\n')

#convert int to complex
output = complex(a)
print('\nOutput', output, type(output), sep='\n')

Output

Input
5
<class 'int'>

Output
(5+0j)
<class 'complex'>

2. Implicit casting of int to complex

We can add 0 imaginary part and Python implicitly promotes the datatype to the higher type, which in this case from integer to complex.

Python Program

#take an intger
a = 5
print('Input', a, type(a), sep='\n')

#convert int to complex implicitly
output = a + 0j
print('\nOutput', output, type(output), sep='\n')

Output

Input
5
<class 'int'>

Output
(5+0j)
<class 'complex'>

Summary

In this tutorial of Python Examples, we learned how to convert value of int datatype to value of complex datatype, with the help of well detailed example programs.