python - 在 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 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 按预期工作。
推荐阅读
- html - 如何制作响应式框尺寸
- c# - 当我调用例程打开 Excel 工作簿时,它将复制 form1 上的所有控件,并打开工作簿
- php - PHP 文件不会在 nginx 中自动加载
- javascript - React-quil nextjs 使用问题参考不起作用
- ansible - 安西布尔。重新连接 playbook 连接
- javascript - 如何使用 Javascript 中的单击事件反复更改 div 的背景样式?
- git - 仅将最后 n 次提交移动到其他分支
- amazon-web-services - 有没有办法在 AWS SQS 中的消息之间添加计时器?
- docker - 无法在 kafka connect docker 映像中运行 kafka connect datagen
- spring-boot - 使用 JWT 进行身份验证如何在 Spring Boot 中工作