2016-04-14 48 views
1

想象一下,我有这样的事情。 x每秒计算一次,并且每秒都有不同的值。基于x的值,我想要做的事,以不同的x一旦进入状态,怎样才能摆脱困境?

if 10 > x > 0: 
    print "It's temporary" 
    do_something(x) 
elif x < 0: 
    print "It gets activated but stay activated" 
    do_something_else(x) 

如果x的首要条件,它不进入条件的两个,但我感兴趣的是,一旦X去第二个条件,即使x返回并变为正数,它也不会进入第一个条件,但会停留在第二个条件中。

是否有任何刻板算法来做这样的事情?

+3

什么,如果x回来,并成为positive_你的意思_even?你在递归吗? – miradulo

+0

x每秒计算一次,并且每秒有不同的值。基于x的价值,我想做一些与x不同的事情。 – auryndb

+3

让我重新描述一下我想问你的问题 - 你想在迭代次数上评估x,然后只要x不符合你的第一个条件,你就想不断的执行你的'elif'语句中的内容x的未来价值? – miradulo

回答

1

基于在评论你的澄清,它出现在下面的递归功能可用于你的目的

def do_something(x, stayActivated = False): 
    if not stayActivated and (10 > x > 0): 
     print "It's temporary" 
     # make an adjustment with said external function 
     do_something(x) 
    elif not stayActivated and x < 0: 
     print "It gets activated but stays activated" 
     do_something_else(x, stayActivated = True) 
    elif x < 0: 
     # x has already been activated and other handling can be applied until any final 
     # condition is met 
2

假设您可以将它适应于x不是静态值的环境,则类似这样的情况将会奏效。

while 10 > x > 0: 
    print "It's temporary" 
    do_something(x) 
while True: # or something that has a chance of being false 
    if x < 0: 
     print "It gets activated but stay activated" 
     do_something_else(x) 
相关问题