python - Python中的逻辑运算符'OR'没有按预期工作?
问题描述
我不明白为什么“或”运算符在这种情况下没有按预期工作。
这是代码:
fuel = input()
liters = float(input())
if fuel != 'Gas' or fuel != 'Diesel' or fuel != 'Gasoline':
print('Invalid fuel!')
else:
if liters >= 25:
if fuel == 'Gas' or fuel == 'Diesel' or fuel == 'Gasoline':
print(f'You have enough {fuel.lower()}.')
elif liters < 25:
if fuel == 'Gas' or fuel == 'Diesel' or fuel == 'Gasoline':
print(f'Fill your tank with {fuel.lower()}!')
输入:
Gas
25
输出:
Invalid fuel
输出应该是You have enough gas.
当我将运算符更改为“and”时,代码工作正常。
if fuel != 'Gas' and fuel != 'Diesel' and fuel != 'Gasoline':
print('Invalid fuel!')
有人可以解释为什么会这样吗?
解决方案
那不是or
运营商的地方,你应该and
在这种情况下使用。
通过在此处使用or
运算符,您是说只要fuel
不是Diesel
,Gas
或之一Gasoline
,它就应该输出Invalid fuel
。既然fuel
是Gas
,那么它不可能是Diesel
,或者Gasoline
,因此 if 语句将产生True
并打印 Invalid fuel
。
推荐阅读
- xslt-1.0 - 使用 xslt 和 xsd 从字符串中获取枚举值
- csv - 是否可以在 AWS Athena CSV 文件中设置标头?
- hive - 根据不在查找表中的值从单个记录中选择
- javascript - 控制台中的“ERR_ABORTED 404(未找到)”和“其 MIME 类型('text/html')不可执行,并且启用了严格的 MIME 类型检查”
- sql - 如何在查询中添加制表符
- perl - 如何根据列名过滤 CSV 文件中的列
- javascript - 防止 Safari 自动滚动到焦点元素(回滚技术在 Safari 12 中停止工作)
- c++ - 尝试生成随机数时 C++ 警告弹出帮助?
- javascript - 未捕获的 SyntaxError:导入 Rails 应用程序时出现意外标识符
- c++ - 如何在 C++ 中的 cudaDeviceReset() 之后重用 tensorflow?