Advanced Number Systems - Python Programming Exercise

In this exercise, you will develop a Python program to represent complex numbers, which consist of a real part and an imaginary part. This exercise is perfect for practicing class definition, method implementation, and object-oriented programming in Python. By implementing this class, you will gain hands-on experience in handling class definitions, method implementation, 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

Advanced Number Systems

 Objective

Develop a Python program to represent complex numbers, which consist of a real part and an imaginary part. For a complex number like \( a + bi \) (such as 2 - 3i), \( a \) is the real part and \( b \) is the imaginary part.

1. Create a class called `ComplexNumber` that includes:
- A constructor to initialize the real and imaginary parts.
- Setters and getters for both the real and imaginary parts.
- A method `__str__()` that returns the complex number as a string in the format "(a, b)".
- A method `get_magnitude()` that calculates and returns the magnitude of the complex number using the formula \( \sqrt{a^2 + b^2} \).
- A method `add()` to add two complex numbers together, adding their real and imaginary parts separately.

2. Then, create a test program to verify the functionality of the `ComplexNumber` class by creating instances of the class, testing the methods toString, get_magnitude, and add, and displaying the results.

 Example Python Exercise

 Copy Python Code
import math

class ComplexNumber:
    def __init__(self, real, imaginary):
        """
        Constructor that initializes the real and imaginary parts of the complex number.
        """
        self.real = real
        self.imaginary = imaginary

    # Setters and getters for the real part
    def set_real(self, real):
        self.real = real

    def get_real(self):
        return self.real

    # Setters and getters for the imaginary part
    def set_imaginary(self, imaginary):
        self.imaginary = imaginary

    def get_imaginary(self):
        return self.imaginary

    # __str__() method to represent the complex number as a string
    def __str__(self):
        return f"({self.real}, {self.imaginary})"
    
    # Method to calculate and return the magnitude of the complex number
    def get_magnitude(self):
        return math.sqrt(self.real**2 + self.imaginary**2)
    
    # Method to add two complex numbers
    def add(self, other):
        real_sum = self.real + other.get_real()
        imaginary_sum = self.imaginary + other.get_imaginary()
        return ComplexNumber(real_sum, imaginary_sum)

# Test program
if __name__ == "__main__":
    # Create two complex numbers
    c1 = ComplexNumber(2, -3)  # Complex number 2 - 3i
    c2 = ComplexNumber(1, 4)   # Complex number 1 + 4i

    # Display the complex numbers as strings
    print(f"Complex Number 1: {c1}")
    print(f"Complex Number 2: {c2}")

    # Display the magnitude of the complex numbers
    print(f"Magnitude of Complex Number 1: {c1.get_magnitude()}")
    print(f"Magnitude of Complex Number 2: {c2.get_magnitude()}")

    # Add the two complex numbers
    sum_result = c1.add(c2)
    print(f"Sum of Complex Number 1 and 2: {sum_result}")

 Output

Complex Number 1: (2, -3)
Complex Number 2: (1, 4)
Magnitude of Complex Number 1: 3.605551275463989
Magnitude of Complex Number 2: 4.123105625617661
Sum of Complex Number 1 and 2: (3, 1)

 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.

  •  Table, Coffee Table, and Legs

    In this exercise, you will develop a Python project based on the tables and coffee tables example, but now introduce a new class named "Leg". This exercise is ...

  •  Catalog

    In this exercise, you will develop a Python class diagram for a catalog utility that stores details about music files, movies, and computer programs. This exercise...

  •  Random Value Generation

    In this exercise, you will develop a Python project with a class RandomNumber that includes three static methods. This exercise is perfect for practicing class...

  •  Converting Text to HTML

    In this exercise, you will develop and program a Python class "TextToHTML" that can convert multiple texts entered by the user into a sequence of HTML lines. This ...

  •  Text on Screen Class

    In this exercise, you will develop a Python class called "DisplayText" that allows you to show text at specific coordinates on the screen. This exercise is per...

  •  Improved ComplexNumber Class

    In this exercise, you will develop a Python program to enhance the "ComplexNumber" class by overloading the addition (+) and subtraction (-) operators. This exerci...