JSeal
JSeal

Reputation: 19

Python: Informing user of divide by zero error

I'm writing a program with a number of simple operating functions. Keep in mind I'm fairly new to this. As you can see, if a user types "0" as one of the values, the obvious "Cannot divide by zero" error appears. I would like some advice on how to make a special case that prints "Cannot divide by zero.") as opposed to showing an error message.

def AddTwoNumbers(num1,num2):
    totalAdded= num1 + num2
    return totalAdded

def SubTwoNumbers(num1,num2):
    totalSubtract= num1 - num2
    return totalSubtract

def MultiTwoNumbers(num1,num2):
    totalMultiply= num1 * num2
    return totalMultiply

def DivideTwoNumbers(num1,num2):
    totalDivide= num1 / num2
    return totalDivide

firstNum=int(input("Enter first number:"))
secondNum=int(input("Enter second number:"))

addResult=AddTwoNumbers(firstNum, secondNum)
subResult=SubTwoNumbers(firstNum, secondNum)
multiResult=MultiTwoNumbers(firstNum, secondNum)
diviResult=DivideTwoNumbers(firstNum, secondNum)

print(firstNum, "+", secondNum, "=", addResult)
print(firstNum, "-", secondNum, "=", subResult)
print(firstNum, "x", secondNum, "=", multiResult)
print(firstNum, "/", secondNum, "=", diviResult)

Upvotes: 0

Views: 115

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113978

try:
  result=DivideTwoNumbers(a,b)
except ZeroDivisionError as e:
  print str(e)

or

if num2 == 0: 
   print "you cant divide by zero dummy"
   return None

Upvotes: 1

idjaw
idjaw

Reputation: 26578

You should use a try/except:

So, for your method here:

def DivideTwoNumbers(num1,num2):
    totalDivide= num1 / num2
    return totalDivide

Simply, use a try/except around your totalDivide = num1 / num2 to catch the ZeroDivisionError and then perform whatever operation you want in there.

This is an example:

try:
    5/0
except ZeroDivisionError:
    print("You tried dividing by zero")

Upvotes: 2

Related Questions