try / except和assert有什么区别?

时间:2017-08-14 10:20:32

标签: python-3.x

try:
def function_addition(x,y):
    assert (y!=0)
    total= x/y
    return total
num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
result=function_addition(num1,num2)
assert (num2 !=0)
print (result)

除了AssertionError:     打印(“错误!检查您的输入”)

我写了上面的代码,但我不知道为什么我这样做的结果相同:except ZeroDivisionError: So can I delete assert and replace it by except ZeroDivisionError ? `

1 个答案:

答案 0 :(得分:1)

assert仅检查条件是否为真并抛出异常。 try/except块可以运行一些语句,并检查是否有任何语句抛出异常,以便您可以在except部分处理它。例子:

assert(1 == 2)

会给你一个AsertionError

try:
    # some statements
    # ...
except OSError as err:
    #If an OSerror exception is thrown, you can process it here. For example:
    print("OS error: {0}".format(err))

您的代码如下所示:

def function_addition(x,y):
    try:
        assert (y!=0)
    except:
        raise ValueError('y is 0.')
    total= x/y
    return total


num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
try:
    result=function_addition(num1,num2)
except ValueError as ve:
    print(ve)
else:
    print(result)

如果您将其保存在 fun.py 文件中并运行它,您将获得此输出:

Write a number :1
Write a second number:2
0.5
# Run it again.
Write a number :0
Write a second number:0
y is 0.