Introduction to Python Programming
9. Define a function which takes TWO objects representing complex numbers and
returns new complex number with a addition of two complex numbers. Define a suitable
class ‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.
#[Link]
class Complex:
def __init__(self, real, imaginary):
[Link] = real
[Link] = imaginary
def __add__(self, other):
return Complex([Link] + [Link], [Link] + [Link])
def __str__(self):
return f"{[Link]} + {[Link]}i"
def read_complex_numbers(n):
complex_numbers = []
for i in range(n):
real = float(input(f"Enter the real part of complex number {i + 1}: "))
imaginary = float(input(f"Enter the imaginary part of complex number {i + 1}: "))
complex_numbers.append(Complex(real, imaginary))
return complex_numbers
def sum_complex_numbers(complex_numbers):
total = Complex(0, 0)
for cn in complex_numbers:
total += cn
return total
Prof. Nomitha Chawla - BIET
Introduction to Python Programming
# Main program
try:
n = int(input("Enter the number of complex numbers (N >= 2): "))
if n < 2:
print("N must be at least 2.")
exit()
complex_numbers = read_complex_numbers(n)
total = sum_complex_numbers(complex_numbers)
print("The sum of the complex numbers is:", total)
except ValueError:
print("Please enter valid numbers.")
OUTPUT 1
OUTPUT 2
Prof. Nomitha Chawla - BIET
Introduction to Python Programming
Brief Explanation:
1. Class Design:
o The Complex class has attributes real and imaginary.
o The __add__ method allows addition of two Complex objects.
o The __str__ method provides a string representation of the complex number.
2. Reading Input:
o The read_complex_numbers function collects a list of Complex objects.
3. Summation:
o The sum_complex_numbers function adds all the complex numbers in the list.
4. Validation:
o The program ensures that at least 2 complex numbers are entered, handling
invalid inputs gracefully.
Prof. Nomitha Chawla - BIET