首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我如何在python中遍历所有这些in?

我如何在python中遍历所有这些in?
EN

Stack Overflow用户
提问于 2020-07-03 10:54:56
回答 1查看 32关注 0票数 1

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

代码语言:javascript
运行
复制
    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
EN

回答 1

Stack Overflow用户

发布于 2020-07-03 11:50:33

你不应该在每个if之后都在else中使用return。这将使函数在第一个if失败后关闭。我将用一个例子进一步解释它。

使用此函数检查一个数字是否为偶数。

代码语言:javascript
运行
复制
def foo_bar(n):
    if n%2==0:
        print("Even")
    else:
        return

    print("I have been reached")

如果传递的是偶数,您将看到以下输出

代码语言:javascript
运行
复制
>>> foo_bar(10)
Even
I have been reached

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

现在,如果函数中有多个if

代码语言:javascript
运行
复制
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

希望这能回答你的问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62707821

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档