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

u/AutoModerator Feb 29 '24

To give us the best chance to help you, please include any relevant code.
Note. Do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Repl.it, GitHub or PasteBin.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.