首页 > 解决方案 > 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!')

有人可以解释为什么会这样吗?

标签: pythonlogical-operatorslogical-or

解决方案


那不是or运营商的地方,你应该and在这种情况下使用。

通过在此处使用or运算符,您是说只要fuel不是Diesel,Gas或之一Gasoline,它就应该输出Invalid fuel。既然fuelGas,那么它不可能是Diesel,或者Gasoline,因此 if 语句将产生True并打印 Invalid fuel


推荐阅读