Home > Back-end >  create a calculator division
create a calculator division

Time:12-11

I have the below code and when I type calculate(2, 0, "/") I would like to print "Division with zero" than just the output, when I divide with 0. Any suggestions?

def calculate(num1, num2, operator):
    if operator == "/" or operator == 'divide':
        output = float(num1) / float(num2) if float(num2) else 0
        return output 

CodePudding user response:

I'd suggest allowing calculate to raise ZeroDivisionError and having the caller print the error:

def calculate(num1, num2, operator):
    if operator == "/" or operator == 'divide':
        return num1 / num2

try:
    print(calculate(2, 0, "/"))
except ZeroDivisionError:
    print("Division with zero")

That way you aren't having one function either return or print depending on the situation -- calculate always computes a result (which might include a ZeroDivisionError) without printing it, and the calling code is always in charge of printing it out.

CodePudding user response:

You can simply add an additional condition handling the case you mentioned. Example:

def calculate(num1, num2, operator):
    if num2 == 0 :
        print("Division with zero")
        return 0
    if operator == "/" or operator == 'divide':
        output = float(num1) / float(num2)
        return output 

def main():
    calculate(4, 2, "/") # 2
    calculate(2, 0, "/") # 0

if __name__ == "__main__":
    main()
  • Related