【问题标题】:How can I run through all these ifs in python?如何在 python 中运行所有这些 if?
【发布时间】:2020-07-03 02:54:55
【问题描述】:

当我运行程序时,它只会运行第一个 If 并进行那些特定的更改。当我切换它们时注意到了,只有第一个给了我想要的东西......谢谢你的帮助。

    if SW1 != r['SW1']: #check the received value of SW1 & change it on the App if there is a mismatch
        print("Changing SW1 status to the value in the database.")
        if self.sw1.active == True:
            self.sw1.active = False
        else:
            self.sw1.active = True
    else:
        return

    if LED1 != r['LED1']: #check the received value of led1 & change it on the App if there is a mismatch
        print("Changing LED1 status to the value in the database.")
        if self.led1.active == True:
            self.led1.active = False
        else:
            self.led1.active = True
    else:
        return
    
    if LED2 != r['LED2']: #check the received value of led2 & change it on the App if there is a mismatch
        print("Changing LED2 status to the value in the database.")
        if self.led2.active == True:
            self.led2.active = False
        else:
            self.led2.active = True
        
    else:
        
    
    if LED3 != r['LED3']: #check the received value of led3 & change it on the App if there is a mismatch
        print("Changing LED3 status to the value in the database.")
        if self.led3.active == True:
            self.led3.active = False
        else:
            self.led3.active = True
    else:
        return

【问题讨论】:

  • 你能分享你的代码吗?
  • @Mendelg 抱歉,不允许发布 sn-p。刚刚添加了代码。谢谢。
  • return 放入else 子句时会发生什么?您确定要在其中一个失败后使该功能短路吗?
  • 如果条件总是检查 TRUE 如果是,那么它不会执行 else 语句。但是,如果您想检查多个语句是否为 TRUE,请使用多个 'if'。
  • 请指定您希望在哪个部分检查多个语句为真。

标签: json python-3.x if-statement


【解决方案1】:

您不应该在每个if 之后在elsereturn。这将使函数在第一个 if 失败后关闭。我将通过一个例子进一步解释。

使用这个检查数字是否为偶数的函数。

def foo_bar(n):
    if n%2==0:
        print("Even")
    else:
        return

    print("I have been reached")

如果是偶数,你会看到下面的输出

>>> foo_bar(10)
Even
I have been reached

如果通过了奇数,您将看不到任何输出,因为函数返回 None 并在 else 中终止。

现在如果你在函数中有多个ifs,

def foo_bar(n):
    if n%2==0:
        print("Even")
    else:
        return
    if n%3==0:
        print("Divisible by 3")
    

    print("I have been reached")

如果您将9 作为参数传递,则上述函数不会打印任何内容。这是因为在检查了一个条件后,您将返回 None 从而终止函数。

希望这能回答你的问题。

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多