Improved ComplexNumber Class - Python Programming Exercise

In this exercise, you will develop a Python program to enhance the "ComplexNumber" class by overloading the addition (+) and subtraction (-) operators. This exercise is perfect for practicing class definition, operator overloading, and object-oriented programming in Python. By implementing this class, you will gain hands-on experience in handling class definitions, operator overloading, and object-oriented programming in Python. This exercise not only reinforces your understanding of object-oriented programming but also helps you develop efficient coding practices for managing user interactions.

 Category

Mastering Python Classes in OOP

 Exercise

Improved Complexnumber Class

 Objective

Develop a Python program to enhance the "ComplexNumber" class by overloading the addition (+) and subtraction (-) operators. The overloaded operators should allow you to add and subtract complex numbers directly.

 Example Python Exercise

 Copy Python Code
import math

class ComplexNumber:
    def __init__(self, real, imaginary):
        """
        Initializes a ComplexNumber object with real and imaginary parts.

        Parameters:
            real (float): The real part of the complex number.
            imaginary (float): The imaginary part of the complex number.
        """
        self.real = real
        self.imaginary = imaginary

    # Getter for the real part
    def get_real(self):
        return self.real

    # Setter for the real part
    def set_real(self, real):
        self.real = real

    # Getter for the imaginary part
    def get_imaginary(self):
        return self.imaginary

    # Setter for the imaginary part
    def set_imaginary(self, imaginary):
        self.imaginary = imaginary

    def __str__(self):
        """
        Returns the complex number in the format (a, b).
        """
        return f"({self.real}, {self.imaginary})"

    def get_magnitude(self):
        """
        Returns the magnitude of the complex number using the formula: sqrt(a^2 + b^2).
        """
        return math.sqrt(self.real ** 2 + self.imaginary ** 2)

    def add(self, other):
        """
        Adds two complex numbers together.

        Parameters:
            other (ComplexNumber): The other complex number to add.

        Returns:
            ComplexNumber: A new complex number that is the sum of the two.
        """
        real_part = self.real + other.real
        imaginary_part = self.imaginary + other.imaginary
        return ComplexNumber(real_part, imaginary_part)

    def subtract(self, other):
        """
        Subtracts another complex number from this one.

        Parameters:
            other (ComplexNumber): The complex number to subtract.

        Returns:
            ComplexNumber: A new complex number that is the result of the subtraction.
        """
        real_part = self.real - other.real
        imaginary_part = self.imaginary - other.imaginary
        return ComplexNumber(real_part, imaginary_part)

    # Overloading the addition operator (+)
    def __add__(self, other):
        """
        Overloads the + operator to add two complex numbers.
        """
        return self.add(other)

    # Overloading the subtraction operator (-)
    def __sub__(self, other):
        """
        Overloads the - operator to subtract two complex numbers.
        """
        return self.subtract(other)


# Test program to demonstrate the functionality of the overloaded operators
def main():
    # Create two complex numbers
    complex1 = ComplexNumber(2, 3)  # 2 + 3i
    complex2 = ComplexNumber(1, 1)  # 1 + 1i

    # Display the complex numbers
    print(f"Complex 1: {complex1}")
    print(f"Complex 2: {complex2}")

    # Add the two complex numbers using the overloaded + operator
    result_add = complex1 + complex2
    print(f"Addition Result: {result_add}")

    # Subtract the two complex numbers using the overloaded - operator
    result_subtract = complex1 - complex2
    print(f"Subtraction Result: {result_subtract}")

    # Display magnitudes
    print(f"Magnitude of Complex 1: {complex1.get_magnitude()}")
    print(f"Magnitude of Complex 2: {complex2.get_magnitude()}")


# Run the test program
if __name__ == "__main__":
    main()

 Output

Complex 1: (2, 3)
Complex 2: (1, 1)
Addition Result: (3, 4)
Subtraction Result: (1, 2)
Magnitude of Complex 1: 3.605551275463989
Magnitude of Complex 2: 1.4142135623730951

 Share this Python Exercise

 More Python Programming Exercises of Mastering Python Classes in OOP

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  3D Coordinates

    In this exercise, you will develop a Python class "Point3D" that will represent a point in three-dimensional space with coordinates X, Y, and Z. This exercise ...

  •  Catalog & Navigation

    In this exercise, you will develop a Python program to enhance the Catalog application, where the "Main" function displays a menu that allows users to input new data ...

  •  Object array: tables

    In this exercise, you will develop a Python class called "Table". The class should include a constructor to initialize the width and height of the table. It should al...

  •  House

    In this exercise, you will develop a Python program with the following classes: House: Create a class called "House" with an attribute for "area". Include a construc...

  •  Array of Tables and Coffee Tables

    In this exercise, you will develop a Python project called "Tables2," extending the "Tables" project. In this project, define a class called "CoffeeTable" that inheri...

  •  Encryptor & Decryptor

    In this exercise, you will develop a Python class called "Encryptor" for text encryption and decryption. This exercise is perfect for practicing class definiti...