I would like to call functions until one returns nonzero, as in the following:
def a():
return 0
def b():
return 1
def c():
return 0
def seq:
if a() != 0:
raise BaseException
if b() != 0:
raise BaseException
if c() != 0:
raise BaseException
seq()
Here, a
and b
are called, but not c
. If c
were before b
, then all three would be called, and if b
were first, then only b
would be called.
I want this to be more concise. It would be easy if b
threw an exception instead of returning a nonzero value, because I could use a try
block. But it doesn't, so I can't.
How do I remove the redundant code here? Is there a block like try
that could handle this?
Because Python supports first-class functions , you can do this with a for
loop.
Python lets you put the functions in a list, then iterate over them like any other value.
def a():
return 0
def b():
return 1
def c():
return 0
for func in [a, b, c]:
if func() != 0:
raise BaseException
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.