我想让main((重复,直到它不能再重复,因为function_one((上的"找不到文件"。当我执行代码时,它从function_one到function_three并停止在那里。如何循环 main(( 以便它再次重复函数序列?
def main():
(f,r) = function_one()
(x,z) = function_two(f,r)
function_three(x,z)
使用 while
循环:
def main():
while True:
try:
(f, r) = function_one()
(x, z) = function_two(f, r)
function_three(x, z)
except WhateverErrors:
break
正如已经建议的那样,带有 try/except 的 while 循环会很好用,但要小心你捕获的内容。尽可能具体。这篇文章中提供了更多信息。
如果您的函数并非都以异常结尾,还可以通过手动引发异常来让它们返回成功或失败。
def main():
c = float(1.00)
# Uncomment the following line to see an unplanned exception / bug.
# c = float(0.00)
# That's is why it's important to only catch exceptions you are
# expexting.
# If you catch everything you won't see your own mistakes.
while True:
c += 2
print('Main loop')
try:
(f, r) = function_one(c)
(x, z) = function_two(f, r)
function_three(x, z)
except IOError:
print('Controlled end, due to an IOError')
break
except ValueError as e:
print('Intentionally stopped: %s' % e)
break
print("Program end")
# Will cause IOERROR if "thestar.txt" does not exist,
# Will continue on if you create the file.
def function_one(c):
print('function_one')
with open('thestar.txt', 'r') as bf:
f = bf.read()
# Doing work on the data ...
r = 100 - c
return (f, r)
# If the file does not contain the text "Cleese",
# this will hand-raise an exception to stop the loop.
def function_two(f, r):
print('function_two')
if 'cleese' in f.lower():
x = 100 / r
z = 'John ' + f
else:
raise ValueError('The parrot is just sleeping')
return (x, z)
# you need to write "Cleese" to thestar.txt to get this far and keep
# the main loop going.
def function_three(x, z):
print('function_three')
# This is what decides when we are finished looping
if x > 1:
print('%s:%s' % (x, z))
else:
# Another diliberately raised exception to break the loop
raise ValueError('The parrot is dead!')
if __name__ == '__main__':
main()
使用变量而不是异常来做到这一点是完全可以的,但这种方式更容易,并且被认为是非常pythonic的。
使用 while True:
循环。当任何函数中引发异常时,它将自动退出。