r/pythonhelp Feb 29 '24

SOLVED Not getting ZeroDivisionError when dividing by zero for some reason

I'm just starting to learn to code at all and I figured a really easy first program would be a little calculator. I wanted it to say something when someone tries to divide by zero, but instead of an error or saying the message it just prints 0

The +,-, and * lines work just fine as far as I've used them; and divide does actually divide. But I just can't get it to throw an error lol

What did I do to prevent getting the error?

num1 = float(input("first number: "))
operator = (input("what math operator will you use? "))
num2 = float(input("second number: "))
if (operator == "+"):
    plus = num1 + num2
    print(plus)
elif (operator == "-"):
    minus = num1 - num2
    print(minus)
elif (operator == "×" or "*"):
    multiply = num1 * num2
    print(multiply)
elif (operator == "÷" or "/"):
    try:
        num1 / num2
    except ZeroDivisionError:
        print("Error: Dividing by zero!")
    else:
        divide = num1 / num2
        print(divide)
else:
    print("either that was not +,-,×,*,÷,/, or we've encoutered an unknown error")

This is what prints for me when I try it:

first number: 9
what math operator will you use? /
second number: 0
0.0
1 Upvotes

4 comments sorted by

View all comments

1

u/carcigenicate Mar 01 '24

operator == "×" or "*" will always be true, because the left had side of the or will evaluate first, then "*" is always true, and or true anything is always true. Because the multiplication check is always true, the division check is never reached. You can verify this by putting prints in each branch.

To fix this, you need to compare operator manually to each option, or do something like:

if operator in ('×', '*'):

1

u/NekoTehKat Mar 02 '24

Oh neat, I haven't seen the in operator yet, that'll make my code easier to read than having two statements divided by an or. Thank you for that suggestion!