-1

Could someone please help me with this?

This is all happening in a loop, so Input1 is always being called. When Input1 switches to True I would like Output1 to turn on, and then off, like a light switch, so for an ms. This on, then off I would like to only happen once while the Input1 is still being called. So later on if Input1 goes back to False and then True after that, it wont affect Output1 which has had its 'switch' - (on then off), happen once already. I hope that helps?

#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

I thought I could do something like this:

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

2 回答 2

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
于 2013-05-01T09:35:42.023 回答
-1

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

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

通过这样做,一旦 Output1 将获得 True 值,它将保持不变。它会破坏语句并且不会进行另一次迭代。

于 2013-05-01T07:13:04.897 回答