Python 中的 Try 和 Except 语句:Unexpected 输出分析

134 阅读2分钟

在 Python 中,我们经常使用 try-except 语句来处理代码中的潜在错误。通过 try 语句,我们可以尝试执行一段代码,如果出现异常,则通过 except 语句捕获该异常并进行相应的处理。然而,有时我们可能会在使用 try-except 语句时遇到 unexpected 输出,也就是与预期不一致的输出结果。

为了解决这个问题,我们需要仔细分析代码逻辑,找出造成 unexpected 输出的原因。在本例中,我们希望创建一个 NoCoffee 异常和一个函数 make_coffee(),该函数使用随机模块来判断是否有 5% 的几率引发 NoCoffee 异常,并尝试冲泡 10 杯咖啡。

2. 解决方案

第一步:修复 make_coffee() 函数

在初始代码中,make_coffee() 函数中存在一个问题,导致 unexpected 输出。具体来说,if random.random() <= .95: 条件的判断逻辑不正确。

def make_coffee():
    if random.random() <= .95:
        print "A pot of coffee has been made"

如果我们需要让函数在 95% 的概率下正常冲泡咖啡,那么条件判断应该是 if random.random() <= .95:。然而,在初始代码中,条件判断是 if random.random() > .95:。这导致函数在 95% 的概率下引发 NoCoffee 异常,而不是正常冲泡咖啡。

因此,我们需要将条件判断修改为如下形式:

def make_coffee():
    if random.random() <= .95:
        print "A pot of coffee has been made"
    else:
        raise NoCoffee

第二步:修复 attempt_make_ten_pots() 函数

在初始代码中,attempt_make_ten_pots() 函数也存在一个问题,导致 unexpected 输出。具体来说,异常处理语句的位置不正确。

def attempt_make_ten_pots():
    cupsMade = 0

    for x in range(10):
        make_coffee()
        cupsMade += 1

    try:
        return cupsMade
    except:
        return cupsMade

在初始代码中,异常处理语句位于 for 循环之后。这意味着,如果在 for 循环中引发 NoCoffee 异常,该异常不会被捕获和处理,从而导致 unexpected 输出。

为了修复这个问题,我们需要将异常处理语句移动到 for 循环内部。这样,当在 for 循环中引发 NoCoffee 异常时,该异常会被捕获和处理,从而返回正确的输出结果。

def attempt_make_ten_pots():
    cupsMade = 0

    try:
        for x in range(10):
            make_coffee()
            cupsMade += 1
    except NoCoffee as e:
        print e.msg
    return cupsMade

最终解决方案

最终,完整的修复代码如下:

class NoCoffee(Exception):
    def __init__(self):
        super(NoCoffee, self).__init__()
        self.msg = "There is no coffee!"

def make_coffee():
    if random.random() <= .95:
        print "A pot of coffee has been made"
    else:
        raise NoCoffee

def attempt_make_ten_pots():
    cupsMade = 0

    try:
        for x in range(10):
            make_coffee()
            cupsMade += 1
    except NoCoffee as e:
        print e.msg
    return cupsMade

print attempt_make_ten_pots()

代码例子

class NoCoffee(Exception):
    def __init__(self):
        super(NoCoffee, self).__init__()
        self.msg = "There is no coffee!"

def make_coffee():
    if random.random() <= .95:
        print "A pot of coffee has been made"
    else:
        raise NoCoffee

def attempt_make_ten_pots():
    cupsMade = 0

    try:
        for x in range(10):
            make_coffee()
            cupsMade += 1
    except NoCoffee as e:
        print e.msg
    return cupsMade

print attempt_make_ten_pots()