Home > OS >  ZeroDivisionError: float division by zero even though i had a specific elif statement for that case
ZeroDivisionError: float division by zero even though i had a specific elif statement for that case

Time:12-09

def main():
    num1 = input("Write a number: ")
    op = input("* or / or   or -: ")
    num2 = input("Write another number: ")
    result = None

    if op == " ":
        result = float(num1)   float(num2)
        print(result)
    elif op == "-":
        result = float(num1) - float(num2)
        print(result)
    elif op == "*":
        result = float(num1) * float(num2)
        print(result)
    elif op == "/" and num2 == 0:
        result = None
        print("You can't divide by zero")
        main()
    elif op == "/" and num2 != 0:
        result = float(num1) / float(num2)
        print(result)


while True:
    main()
    ans = input("Would you like to do another equation: ")
    if ans == "yes":
        main()
        ans = input("Would you like to do another equation: ")
    elif ans == "no":
        exit()

I get this error even though i already had an elif statement for that case

File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 26, in main() File "d:\Visual Studio Code\Projects\HelloWorld python\Calculator.py", line 21, in main
result = float(num1) / float(num2) ZeroDivisionError: float division by zero

CodePudding user response:

The reason you're not catching the zero case is that num hasn't been converted to a float. Consider using try/except instead -- that way you don't need to try to predict whether the operation will fail, you can just let the operation itself tell you. This will also let you catch things like inputs that aren't valid numbers, or operations that aren't one of the valid options.

You can also save time by doing the float conversion as soon as possible -- if you use try/except, this lets you immediately re-prompt the user for valid input. If you return the answer (and let the caller print it) rather than assigning it to a result which you then print, you can easily break the loop once the function succeeds while also making each if block a single concise line.

Note that explicitly re-calling main() isn't necessary as long as it's in a while loop that continues until it's time to break.

def main() -> float:
    while True:
        try:
            num1 = float(input("Write a number: "))
            op = input("* or / or   or -: ")
            num2 = float(input("Write another number: "))

            if op == " ":
                return num1   num2
            elif op == "-":
                return num1 - num2
            elif op == "*":
                return num1 * num2
            elif op == "/":
                return num1 / num2
            else:
                raise ValueError(f"Invalid operation {op}")
        except ZeroDivisionError:
            print("You can't divide by zero")    
        except ValueError as e:
            print(e)


while True:
    print(main())
    ans = input("Would you like to do another equation: ")
    if ans == "no":
        break

CodePudding user response:

Convert num2 to a float, either before you test it or when you test it:

### ...
    elif op == "/" and float(num2) == 0.0:
        result = None
        print("You can't divide by zero")
        main()
    elif op == "/" and float(num2) != 0.0:
        result = float(num1) / float(num2)
        print(result)
  • Related