-2

Ok so I am completely new to coding, I was making a simple calculator and I came across an error called ZeroDivisionError and I tried really hard to handle it as an exception but I couldn't. It would be really nice if someone could help me with this. Thanks! Here is the code:

def multiply(first_number, second_number):
    print("The Number = ", int(first_number) * int(second_number))


def divide(first_number, second_number):
    print("The Number = ", int(first_number) / int(second_number))


def add(first_number, second_number):
    print("The Number = ", int(first_number) + int(second_number))


def sub(first_number, second_number):
    print("The Number = ", int(first_number) - int(second_number))
    
    
def start():
    first_number = input("Insert first number: ")
    second_number = input("Insert second number: ")
    type = input("You wanna (+)Add, (-)Subtract, (/)Divide or (x)Multiply? ")

    if type == "+":
        add(first_number, second_number)
    elif type == "-":
        sub(first_number, second_number)
    elif type == "/":
        divide(first_number, second_number)
    elif type == "x":
        multiply(first_number, second_number)
    else:
        print("There is no such thing as", type, "!")
        start()

    confirm = input("Do you want to exit the program? (Y)es/(N)o? ")
    if confirm == "N":
        start()
    elif confirm == "Y":
        print("You quit the program.")

    else:
        print("There is no such thing as", confirm, "!")



start()
2
  • 4
    The standard way to handle this is to use a try/except block. But your code sample does not show one.
    – paisanco
    Dec 29, 2020 at 1:30
  • what inputs did you use?, you cant divide a number by zero btw Dec 29, 2020 at 1:30

3 Answers 3

0

Change the divide function to this

def divide(first_number, second_number):
    try:   
        print("The Number = ", int(first_number) / int(second_number))
    except
        print("You cant divide a number by 0")

0
0

Try this:

def dev(x, y ):
    try:
        return x/y
    except ZeroDivisionError:
        return x
    
print(dev(1, 0.1))
0

Like you already encountered you can't divide by zero. If you want to handle the ZeroDivisionError exception you need to use a try except construction. For example:

try:
    divide(first_number, second_number)
except ZeroDivisionError:
    print("Oops, you can't divide by 0")

Not the answer you're looking for? Browse other questions tagged or ask your own question.