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