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
这是避免 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。
您可以尝试以下方法:
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
它按顺序执行每个函数。如果其中之一失败,则打印消息和函数名称,然后我们中断 for
语句。当我们中断 for 时,else
不会被执行。于是又重复了一遍上面的循环
如果每个函数都成功运行,那么我们不会中断并执行 for
的 else
。这从 while True
中断,程序正常继续。
我正在尝试检查几个函数的输出,如果没有错误,我将转到下一个函数。 所以我添加了一个 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。
您可以尝试以下方法:
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
它按顺序执行每个函数。如果其中之一失败,则打印消息和函数名称,然后我们中断 for
语句。当我们中断 for 时,else
不会被执行。于是又重复了一遍上面的循环
如果每个函数都成功运行,那么我们不会中断并执行 for
的 else
。这从 while True
中断,程序正常继续。