繁体   English   中英

Python语句中的if-else子句

[英]If-else clause in Python Statement

我正在尝试检查几个函数的输出,如果没有错误,请转到下一个函数。 因此,我添加了一个while循环和一些if语句来处理错误:

success = True
    while success:
        err, msg = function1()
        if not err:
            err, msg = function2()
            if not err:
                err, msg = function3()
                if not err:
                    err, msg = function4()
                else:
                    print msg
                    success = False
            else:
                print "function2 fails"
                sucess = False
        else:
            print "function1 fails"
            success = False

是否可以避免这种情况的更好方法,我该如何重新设计代码?

一个相对简单的方法是创建函数列表并对其进行迭代:

functions = [function1, function2, function3, function4]
success = True
while success:
    for f in functions:
        err, msg = f()
        # If there's an error, print the message, print that the
        # function failed (f.__name__ returns the name of the function
        # as a string), set success to False (to break out of the while
        # loop), and break out of the for loop.
        if err:
            print msg
            print "{} failed".format(f.__name__)
            success = False
            break

我敢肯定,您可能会花哨得多,并创建一个自定义的迭代器,等等,等等,等等(如果您的实际需求更加复杂,这可能是一个更好的解决方案)。 但这也应该起作用。

如果您担心要打印到STDERR而不是STDOUT,则还可以使用warnings模块中的warn功能

您可以尝试以下方法:

while True:
    for f in (function1, function2, function3, function4):
        err, msg = f()
        if err:
            print("%s failed, msg is %s" % (f.func_name, msg))
            break
    else:
        break

它按顺序执行每个功能。 如果其中之一失败,则将输出msg和函数名称,然后中断for语句。 当我们中断for时, else不执行。 因此,以上循环又重复了一次。

如果每个函数都成功运行,那么我们就不会中断, forelse将被执行。 while True中断,程序正常继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM