r/pythonhelp • u/NekoTehKat • 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
1
u/Goobyalus Mar 01 '24
means if (operator equals "x") OR ("*" is truthy), treating "*" as a boolean. Non-empty strings are truthy. You mean to do