I don't understand why the "or" operator is not working as intended in this case.
Here is the code:
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()}!') Input:
Gas 25 Output: Invalid fuel
The output should be You have enough gas.
When I change the operator to "and", the code works fine.
if fuel != 'Gas' and fuel != 'Diesel' and fuel != 'Gasoline': print('Invalid fuel!') Could someone please explain why is this happening?
or, only one of the operands needs to beTruefor the entire expression to evaluate toTrue. So,fuel != 'Gas'will beFalse, butfuel != 'Diesel'will beTrue. The conditionfuel != 'Gasoline'will also beTrue, but it doesn't need to be evaluated due to short-circuiting, since we've already found something that'sTrue. In any case, the whole expression will always beTrue. In order for it to beFalse,fuelwould have to be equal to'Gas','Diesel'and'Gasoline'all at the same time, which of course can never be the case.