如果== True,则在循环中使其成为真

时间:2013-05-01 07:04:22

标签: python

有人可以帮帮我吗?

这一切都发生在循环中,因此始终会调用Input1。当Input1切换到True时,我希望Output1打开,然后关闭,就像一个灯开关,所以对于一个ms。这个开,然后关闭我想只发生一次,而Input1仍然被调用。所以稍后如果Input1回到False然后在那之后返回True,它将不会影响已经有'switch'的Output1 - (然后关闭),已经发生过一次。我希望有帮助吗?

#Input1 is a boolean
on = True
off = False
if Input1 == True:
    Output1 = on
    #Only turn on for one moment
    #then turn off right away even while Input1 continues to be True
else:
    Output1 = off

我以为我可以这样做:

#Input1 is a boolean
on = True
off = False
count = 0
if Input1 == True and count == 0:
    Output1 = on
    count = 1
else:
    Output1 = off

2 个答案:

答案 0 :(得分:1)

如果我理解正确,你想在循环的第一次迭代中执行一段代码,这段代码在后续循环中没有被激活。下面是你对Input1 / Output1的看法,虽然我建议比较count而不是Output1(因为它是多余的)。

count = 0
Input1 = True
while True:
    if Input1:
        print("Doing Input1 stuff...")
        count = count + 1
        if count == 1: #if the count is 1 it is the FIRST iteration of the loop so we switch on!
            Output1 = True
            print("Output 1 switched ON")
    if Output1: 
        print("Out-putted")
        Output1 = False #switch if OFF, and since count will never = 1 again, this code block won't activate again.
        print("Output 2 switched OFF")
    #break the loop sometime (this is just for demonstration)
    if count == 4:
        print("I've done 4 iterations")
        break;

可生产

>>> 
Doing Input1 stuff...
Output 1 switched ON
Out-putted
Output 2 switched OFF
Doing Input1 stuff...
Doing Input1 stuff...
Doing Input1 stuff...
I've done 4 iterations

答案 1 :(得分:-1)

你也可以使用这样的break语句:

on = True
off = False
if Input1 == True:
    Output1 = on
    break
else:
    Output1 = off

通过执行此操作,一旦Output1将获得True值,它将保持不变。它将破坏该陈述,不会再进行另一次迭代。