如果我的条件为false,如何在python中只执行一次语句

2024-05-23 23:02:56 发布

您现在位置: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

我的意思是,如果speed>;3或者只发送一次数据,我需要发送数据。在

有什么帮助吗

我解决了。我只需要在“Alex Martelli”的解中添加额外的“neverdone=True”

^{pr2}$

非常感谢Alex Martelli。在


Tags: trueifhereis逻辑condition条件else
3条回答

添加布尔变量:

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

你不能在statement3后面加一个break语句吗?这意味着它将运行一次,然后while循环将退出。在

您可以使用标志,或写下以下内容:

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

当条件为false时,这将破坏state3。在

相关问题 更多 >