如果条件为假,如何在Python中只执行一次语句
有没有办法实现这个逻辑:
我需要在条件为假的时候只执行一次下面的语句:
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
我的意思是,如果速度大于3,就发送我的数据;否则,只发送一次我的数据。
请帮帮我。
我解决了这个问题。我只需要在“Alex Martelli”的解决方案中添加一个额外的“neverdone = True”。
neverdone = True
while 1:
statement1
statement2
if condition:
statement3
neverdone = True
elif neverdone:
neverdone = False
statement3
if anothercondition:
break
非常感谢Alex Martelli。
4 个回答
0
如果你只想做一件事情一次,那就不要把它放在一个无限循环里(这很明显)
def dostuff():
statement1
statement2
if condition:
statement3
dostuff()
if not contition:
statement3
while True:
dostuff()
if another condition:
break
0
你难道不可以在 statement3
后面加一个 break
语句吗?这样的话,它就只会执行一次,然后 while
循环就会结束。
3
添加一个布尔变量:
neverdone = True
while 1:
statement1
statement2
if condition:
statement3
elif neverdone:
neverdone = False
statement3
if anothercondition:
break