0

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?

prsnr
  • 83
  • 7
  • Remember, when using `or`, only one of the operands needs to be `True` for the entire expression to evaluate to `True`. So, `fuel != 'Gas'` will be `False`, but `fuel != 'Diesel'` will be `True`. The condition `fuel != 'Gasoline'` will also be `True`, but it doesn't need to be evaluated due to short-circuiting, since we've already found something that's `True`. In any case, the whole expression will always be `True`. In order for it to be `False`, `fuel` would have to be equal to `'Gas'`, `'Diesel'` and `'Gasoline'` all at the same time, which of course can never be the case. – Paul M. Mar 15 '21 at 17:18
  • Thank you @PaulM. I was so concentrated in only the first part of the statement that I completely ignored the rest of it. Great explanation! – prsnr Mar 15 '21 at 19:43

2 Answers2

2

That is not the place for the or operator, you should be using and in that case.

By using the or operator there, you are saying that as long as fuel is not one of Diesel, Gas or Gasoline, it should output Invalid fuel. Since fuel is Gas, then it cannot be Diesel, or Gasoline, therefore the if statement will yield True and will print Invalid fuel.

lnogueir
  • 1,859
  • 2
  • 10
  • 21
2

With fuel = 'Gas', this:

if fuel != 'Gas' or fuel != 'Diesel' or fuel != 'Gasoline':

evaluates to:

if False or True or True:

which is the same as:

if True:

What you need is in fact and, as you have discovered:

if fuel != 'Gas' and fuel != 'Diesel' and fuel != 'Gasoline':

or, better, use sets for speed of lookups and brevity, assigning it to a variable to avoid repeating yourself:

allowed_fuels = set(['Gas', 'Diesel', 'Gasoline'])
if fuel not in allowed_fuels:
    print(f'Invalid fuel: {fuel}')
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • Thank you very much for the explanation! I totally ignored the fact that when fuel is gas is not equal to diesel or gasoline, then this is a True statement. – prsnr Mar 15 '21 at 19:40