python重新执行条件_python - 如何实现满足指定条件后续的代码不再执行?

问 题

假设现在有5个函数:

def one():

return 1

def two():

return 0

def three():

return 2

def four():

return 1

def five():

return 0

现在将其组合在1个main函数中:

def main():

result = []

val = one()

result.append(val)

val =two()

result.append(val)

val = three()

result.append(val)

val = four()

result.append(val)

val = five()

result.append(val)

return result

现在希望某些函数的返回值满足一定条件后,后续的代码不再执行,比如one函数返回值大于0,那么后面的two到five函数不再被执行。而在这个过程中,存在three函数其返回值也大于0的情况,那么后续的four和five函数不再被执行。

在这个过程中,main函数中可能不止5个函数,有可能是10个或15个类似这样的不同名称的函数,但是操作是类似的。如何用1种简便的方式来实现这样的写法,而不是每个都if...else的方式来进行判断?

解决方案

#!/usr/bin/env python

# coding: utf8

def one():

return 1

def two():

return 0

def three():

return 2

def four():

return 1

def five():

return 0

func_list = [one, two, three, four, five] # 将你相加的函数, 按顺序添加

result = []

while func_list:

func = func_list.pop(0)

value = func()

if value > 0:

result.append(value)

break

print result

扫一扫关注IT屋

微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值