Michael Ung
Michael Ung

Reputation: 1

How to use print to format the following?

I have a homework assignment where I create a class that represents a complex number. I've completed the task, but one part isn't satisfactory for me.

In the example that is given:

Enter the real value of the first complex number: 5    # Inputs
Enter the imaginary value of the first complex number: 5
Enter the real value of the second complex number: 0
Enter the imaginary value of the second complex number: 0
C1 = 5.0+5.0i
C2 = 0
C1+C2 = 5.0+5.0i
C1-C2 = 5.0+5.0i
C1*C2 = 0
C1/C2 = None; Divide by Zero Error!    # This is how I want it to appear

I use the following overloaded division function and get the following results (it was stated that the function should not use a return if division by zero occurs and it should print inside the division function):

def __truediv__(self, other):   # Overrides division function
        denom = other.real ** 2 + other.img ** 2
        tempComp = Complex(other.real, -1 * other.img)
        if denom != 0:
            tempComp = self * tempComp
            return Complex(tempComp.real / denom, tempComp.img / denom)
        print("Error: Cannot divide by zero")

Enter the real part of the first complex number: 5
Enter the imaginary part of the first complex number: 5
Enter the real part of the second complex number: 0
Enter the imaginary part of the second complex number: 0
C1 = 5.0 + 5.0i
C2 = 0
C1 + C2 = 5.0 + 5.0i
C1 - C2 = 5.0 + 5.0i
C1 * C2 = 0
Error: Cannot divide by zero
C1 / C2 = None

How should I go about doing this, if possible? It would also help if specific code is also included, but only if you want.

Upvotes: 0

Views: 53

Answers (1)

JayMech
JayMech

Reputation: 11

I misread the question the first time. If you want it to look exactly like:

C1/C2 = None; Divide by Zero Error!

You could have it:

return 'None; Divide by Zero Error!'

But I would not recommend this and instead would recommend my original answer below:

A python method always returns None if it doesn't hit a return statement.

If you don't want it to return at all, you could have it raise an exception:

def __truediv__(self, other):   # Overrides division function
        denom = other.real ** 2 + other.img ** 2
        tempComp = Complex(other.real, -1 * other.img)
        if denom != 0:
            tempComp = self * tempComp
            return Complex(tempComp.real / denom, tempComp.img / denom)
        else:
            raise(ZeroDivisionError("Error: Cannot divide by zero"))

This is the same behavior as the int type.

Upvotes: 1

Related Questions