python - Python 语句中的 if-else 子句

标签 python if-statement while-loop

我正在尝试检查几个函数的输出,如果没有错误,我将转到下一个函数。 所以我添加了一个 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

这是避免 if,else 的更好方法吗?我如何为此目的重新设计代码?

最佳答案

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

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,您还可以使用 the warn function in the warnings module .

关于python - Python 语句中的 if-else 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28725367/

相关文章:

python - Perl 到 Python 哈希表的翻译

python - 将列中的列表分隔符分为行和交叉点的多个标签

jquery - if() else() 语句问题...:/

java - 在 Java 中将整数添加到数组中

python - 使用不同的循环结构时会有不同的答案

javascript - for 循环内的 while 循环串联

python - 循环 python openpyxl。如何在单元格中添加循环

python - 用python读取一个简单的.txt文件,为什么这段简单的代码会输出每一行? python 如何知道它应该这样做?

python - 迭代循环以更改条件语句,python

python - 如何在 while 循环中构造此计时代码以更快地运行?