如何使用print来格式化以下内容?

时间:2018-04-21 15:56:15

标签: python python-3.x

我有一个家庭作业,我创建了一个代表复数的类。我已完成任务,但有一部分对我不满意。

在给出的示例中:

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

我使用下面的重载除法函数并得到以下结果(据说如果出现除零,函数不应该使用return,它应该在除法函数内打印):

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

如果可能的话,我该如何做呢?如果还包含特定代码,它也会有所帮助,但只有在您需要时才会有用。

1 个答案:

答案 0 :(得分:1)

我第一次误解了这个问题。 如果你想让它看起来完全像:

C1/C2 = None; Divide by Zero Error!

可以拥有它:

return 'None; Divide by Zero Error!'

但我不建议这样做,而是推荐我的原始答案:

如果python方法没有返回return语句,则它总是返回None。

如果您根本不希望它返回,您可以让它引发异常:

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"))

这与int类型的行为相同。