Understanding Complex Data Type in Python

A complex number has two parts, real part and imaginary part. Complex numbers are represented as A+Bi or A+Bj, where A is real part and B is imaginary part.

Python supports complex data type as built-in feature which means we can directly perform different operations on complex number in python.

First thing first, python uses A+Bj notation to represent complex number meaning python will recognize 3+4j as a valid number but 3+4i is not valid. Let's try it out in python console:


>>> a=3+4j
>>> b=3+4i
SyntaxError: invalid syntax

Creating Complex Data Type Using complex()

We can create complex number from two real numbers. Syntax for doing this is:

c = complex(a,b)

Where, a & b are of real data types and c will be of complex data types.

Let's try it out in python console:


>>> a=5
>>> b=7
>>> c=complex(a,b)
>>> print(c)
(5+7j)

Accessing Real and Imaginary Part From Complex Number

After creating complex data type, we can access real and imaginary part using built-in data descriptors real and imag. Let's try it out in python console:


>>> a = 5+6j
>>> a.real
5.0
>>> a.imag
6.0

Reading Complex Number From User

We can read complex number directly from user using built-in function input(). Since function input() returns STRING we must convert result to complex using function complex(). Try following example:


a = complex(input('Enter complex number:'))
print('Given complex number is:',a)

Output

Enter complex number:2+3j
Given complex number is: (2+3j)

Finding Conjugate of Complex Number

Complex data type has built-in method called conjugate() to find conjugate of complex number. Let's try it out in python console:


>>> a=10-6j
>>> a.conjugate()
(10+6j)

Addition, Subtraction, Multiplication & Division on Complex Number

Python supports direct addition, subtraction, multiplication and division using operator +, -, *, /. Let's try it out in python console:


>>> a=1+2j
>>> b=3+4j
>>> a+b
(4+6j)
>>> a-b
(-2-2j)
>>> a*b
(-5+10j)
>>> a/b
(0.44+0.08j)