python-2.7 - Python 中的条件“或”运算符未正确验证
问题描述
status= None
if 'Up' or 101 in status:
print "Inside If statement"
else:
print "Inside Else Statement"
代码流进入“If”循环并打印“Inside If Statement”。状态实际上是 None 并且通过阅读代码它应该打印“Inside Else Statement”。我可以修改验证部分并使其在 else 语句中执行。但我想知道这种情况下如何返回“真”
if 'Up' or 101 in status:
解决方案
Python 中的字符串是假的,也就是说一个空字符串 ( ''
) 等价于False
,而其他的则是True
。
您的条件被评估为(括号仅用于解释目的)
if ('Up') or (101 in status):
而且因为'Up'
总是True
它总是会进入if
块内。
你可以改为写:
if 'Up' in status or 101 in status:
或者更通用的方法any
是:
if any(x in status for x in ('Up', 101)):
您可以在此问题中找到更多答案
推荐阅读
- javascript - 每次在 vue 中挂载时,从 vue 组件中的 js 文件执行一个函数
- java - Excel单元格颜色不使用java程序设置实际颜色
- microsoft-graph-api - 如何使用 Microsoft Graph .NET SDK 创建和获取 Outlook 事件打开扩展数据
- jwt - 如何像 Discord 一样让 JWT 更小?
- salesforce - visualforce 页面显示未知方法错误
- javascript - 在 D3.js V5 中,带箭头的路径向后方向未正确显示
- python-3.x - 如何使用python将txt文件的行拆分为带有变量的列表
- c++ - 纹理未正确加载 OpenGL
- ubuntu - Ubuntu 上的这些 Redis 启动启动命令有什么区别?
- java - 向左/右通知交换添加事件