Python:告知用户除零错误

时间:2015-11-16 20:49:56

标签: python function zero divide divide-by-zero

我正在编写一个具有许多简单操作功能的程序。请记住,我对此很新。如您所见,如果用户键入" 0"作为价值之一,显而易见的"不能除以零"出现错误。我想要一些关于如何创建一个打印"不能除以零的特殊情况的建议。")而不是显示错误信息。

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)

2 个答案:

答案 0 :(得分:2)

您应该使用documentation

所以,对于你的方法:

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

只需在totalDivide = num1 / num2周围使用try / except来捕捉ZeroDivisionError,然后在那里执行您想要的任何操作。

这是一个例子:

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

答案 1 :(得分:1)

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

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