尝试并在Python中除外,意外输出

时间:2013-11-15 02:01:06

标签: python try-catch

编辑:更改了条件..谢谢

我正在尝试学习try / exception。我没有得到我应该的输出。它通常是一杯或没有。理想情况下,它应该是9或10.

说明:

创建一个NoCoffee类,然后编写一个名为make_coffee的函数,执行以下操作:使用随机模块以95%的概率通过打印消息创建一壶咖啡并正常返回。有5%的几率,提高NoCoffee错误。

接下来,编写一个函数attempt_make_ten_pots,它使用try块和for循环来尝试通过调用make_coffee来生成10个pot。函数attempt_make_ten_pots必须使用try块处理NoCoffee异常,并且应该为实际生成的pot数返回一个整数。

import random

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

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

    except NoCoffee as e:
        print e.msg

def attempt_make_ten_pots():
    cupsMade = 0

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

    except:
        return cupsMade


print attempt_make_ten_pots()

1 个答案:

答案 0 :(得分:3)

  1. 如果你想允许95%那么条件应该是

    if random.random() <= .95:
    
  2. 现在,为了让您的程序抛出错误并返回所做的咖啡数量,您需要在随机值大于.95时引发异常,并且应该在attempt_make_ten_pots中排除异常函数不在make_coffee本身。

    import random
    
    # First, a custom exception
    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()