mahdi86
mahdi86

Reputation: 15

if my condition false how to do a statement one time only in python

is there any way to make this logic:

I need to make a statement one time only if the condition is false as below:

while 1:
    statement1
    statement2
    if condition:                --condition is true here
          statement3
    else                         --condition is false here
          statement3            --I need to do this "statement3" one time only
    if another condition:
          break

what I mean that I need to send my data if speed > 3 else send my data only one time.

any help, please

I solved it. I just need to add extra "neverdone = True" to the solution of "Alex Martelli"

 neverdone = True
 while 1:
    statement1
    statement2
    if condition:
         statement3
         neverdone = True
    elif neverdone:
         neverdone = False
         statement3
    if anothercondition:
        break

many thanks to Alex Martelli.

Upvotes: 0

Views: 1930

Answers (4)

Jochen Ritzel
Jochen Ritzel

Reputation: 107648

If you want to do something once don't put it in a infinite loop (duh)

def dostuff():
    statement1
    statement2
    if condition:
        statement3

dostuff()

if not contition:
    statement3

while True:
    dostuff()
    if another condition:
        break

Upvotes: 0

Oren
Oren

Reputation: 2807

you can use a flag, or write something like:

while 1:
  state1()
  state2()
  state3()
  if not condition:
     state3 = lambda : None
  if another_condition:
     break

Thise will destroy the state3 when the condition is false.

Upvotes: 0

Alex Martelli
Alex Martelli

Reputation: 881873

add a boolean variable:

neverdone = True
while 1:
    statement1
    statement2
    if condition:
          statement3
    elif neverdone:
          neverdone = False
          statement3
    if anothercondition:
          break

Upvotes: 3

avpx
avpx

Reputation: 1922

Couldn't you just put a break statement after statement3? That would mean that it would run once and then the while loop would exit.

Upvotes: 0

Related Questions