首页 > 解决方案 > 在 Python 中使用 if/else 语句返回 True 和 False 的更优雅的方法是什么?

问题描述

我不断收到错误消息,说“返回”后出现不必要的“其他”

它试图告诉我什么,以及对这个逻辑进行编码的更优雅的方式是什么?

for selected_node in NODES:
    if pm.nodeType(selected_node) == 'file':
        msg = 'correct type of nodes selected'
        LOGGER_TEXTURE_SWAP.debug(msg)
        return True
    else:
        msg = 'incorrect type of nodes selected'
        LOGGER_TEXTURE_SWAP.debug(msg)
        return False

标签: python

解决方案


我尝试重新创建您的代码片段的逻辑,并使用最新的 python 3.8.3

nodes = ['file', 'folder', 'directory']

for node in nodes:
    if node == 'file':
        print(node)
        return True
    else:
        print('something else')
        return False

我得到 SyntaxError: 'return' 外部函数。这是可以理解的,因为 return 应该是函数的输出。

所以,然后我把它作为一个函数,如下所示。

nodes = ['file', 'folder', 'directory']

def myprogram():
    for node in nodes:
        if node == 'file':
            print(node)
            return True
        else:
            print('something else')
            return False
myprogram()

现在我打印了“文件”和“真”输出。因此,python 按预期工作。


推荐阅读