# Python Program to add two Complex Numbers using Class (2 Ways)

In this program, we will learn how to add two complex numbers using the Python programming language.

### What is a complex number?

Complex numbers are numbers that are expressed as a+bi where i is an imaginary number and a and b are real numbers. Some examples are −

6 + 4i

8 – 7i

## Python Programming Code to add two Complex Numbers

We will be discussing two ways to write code for it.

- Using the in-built complex Class
- Using the User-defined Complex Class

### Using the in-built complex Class

### Code:-

print("Format for writing complex number: a+bj.\n") c1 = complex(input("Enter First Complex Number: ")) c2 = complex(input("Enter second Complex Number: ")) print("Sum of both the Complex number is", c1 + c2)

### Output:-

Enter First Complex Number: 7+3j

Enter second Complex Number: 8+6j

Sum of both the Complex number is (15+9j)

### Using the User-defined Complex Class

To make this program, we will use classes.

We will declare a class **Complex** which will store the real and imaginary part of the complex number. This class will have three methods also.

The first method is **initComplex()**, which will help in initializing them. In this method, it will ask for the real part and imaginary part of the complex number.

The second method is** display()**, which will allow displaying them on the output screen.

And the third method is **sum()**, which will help to add two complex numbers passed in the arguments.

### Code:-

class Complex (): def initComplex(self): self.realPart = int(input("Enter the Real Part: ")) self.imgPart = int(input("Enter the Imaginary Part: ")) def display(self): print(self.realPart,"+",self.imgPart,"i", sep="") def sum(self, c1, c2): self.realPart = c1.realPart + c2.realPart self.imgPart = c1.imgPart + c2.imgPart c1 = Complex() c2 = Complex() c3 = Complex() print("Enter first complex number") c1.initComplex() print("First Complex Number: ", end="") c1.display() print("Enter second complex number") c2.initComplex() print("Second Complex Number: ", end="") c2.display() print("Sum of two complex numbers is ", end="") c3.sum(c1,c2) c3.display()

### Output:-

Enter the Real Part: 8

Enter the Imaginary Part: 4

First Complex Number: 8+4i

Enter second complex number

Enter the Real Part: 9

Enter the Imaginary Part: 7

Second Complex Number: 9+7i

Sum of two complex numbers is 17+11i

#### You can learn about many other Python Programs Here.

#### Best Books for learning Python with Data Structure, Algorithms, Machine learning and Data Science.

#### Amit Rawat

#### Latest posts by Amit Rawat (see all)

- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019