Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试并在Python中除外,意外输出_Python_Try Catch - Fatal编程技术网

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

尝试并在Python中除外,意外输出,python,try-catch,Python,Try Catch,编辑:已更改条件。。谢谢 我正在努力学习try/例外。我没有得到应有的产出。它通常是一杯或一杯都没有。理想情况下,它应该是9或10 说明: 创建一个NoCoffee类,然后编写一个名为make_coffee的函数,该函数执行以下操作:使用random模块以95%的概率通过打印消息并正常返回来创建一壶咖啡。有5%的几率,提高NoOffee错误 接下来,编写一个函数,使用try块和for循环通过调用make_coffee来尝试制作十个壶。函数trument\u make\u ten\u pots必须

编辑:已更改条件。。谢谢

我正在努力学习try/例外。我没有得到应有的产出。它通常是一杯或一杯都没有。理想情况下,它应该是9或10

说明:

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

接下来,编写一个函数,使用try块和for循环通过调用make_coffee来尝试制作十个壶。函数trument\u make\u ten\u pots必须使用try块处理NoCoffee异常,并应返回实际生成的pots数的整数

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()
随机导入
#首先,自定义异常
无报价类(例外):
定义初始化(自):
超级(NoCoffee,self)。\uuuu init\uuuuu()
self.msg=“没有咖啡!”
def煮咖啡():
尝试:
if random.random()
  • 如果您希望允许95%,则条件应为

    if random.random() <= .95:
    
  • 如果您希望允许95%,则条件应为

    if random.random() <= .95:
    

  • 即使所有尝试都成功,也不要忘记返回
    cupsMade
    。@user2357112谢谢:)现在已修复。即使所有尝试都成功,也不要忘记返回
    cupsMade
    。@user2357112谢谢:)现在已修复