编辑:改变条件..谢谢
我正在尝试学习尝试/异常。我没有得到我应该得到的输出。它通常只做一杯或不做。理想情况下,它应该是 9 或 10。
指示:
创建一个 NoCoffee 类,然后编写一个名为 make_coffee 的函数,该函数执行以下操作:使用 random 模块以 95% 的概率通过打印一条消息并正常返回来创建一壶咖啡。有 5% 的机会引发 NoCoffee 错误。
接下来,编写一个函数 attempt_make_ten_pots,它使用一个 try 块和一个 for 循环,通过调用 make_coffee 来尝试制作十个罐子。函数 attempt_make_ten_pots 必须使用 try 块处理 NoCoffee 异常,并且应该返回一个整数来表示实际制作的罐子的数量。
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()