How to Add Complex Numbers in Python

Complex numbers are used in many fields like engineering, physics, and mathematics. Despite this, many programming languages do not handle complex numbers straight out of the box.

Luckily, Python does! In this tutorial, we’ll be learning how to add complex numbers in Python.

Step 1: Understanding Complex Numbers in Python

In Python, complex numbers are represented in the form of x + yj, where x represents the real part and y represents the imaginary part. The ‘j’ is like ‘i’ in mathematics, denoting the square root of -1. Python provides a built-in complex data type for handling these numbers.

Step 2: Writing Addition Code

To add complex numbers, we just need to add real parts together and imaginary parts together separately. Here’s the code:

In the script above, we created two complex numbers cn1 and cn2, and added them together. We stored the result in the sum variable and printed out the result.

Step 3: Understanding the Output

The output of our script will be:

The sum is : (4+6j)

The real parts (3 and 1) have been added together to form 4, and the imaginary parts (4 and 2) have been added together to form 6.

Step 4: Handling Input from User

What if you want to allow the user to input their own complex numbers? Let’s refine our code to accept input from the user:

Full Code

Here’s the full Python code you can use to add complex numbers, either hardcoded or entered by a user:

Conclusion

Adding complex numbers in Python is straightforward thanks to Python’s built-in complex data type. You can either specify your own complex numbers within the script or allow the user to input their own. Now you should be able to use Python to make calculations using complex numbers.