Search code examples
pythonif-statementlogicoperators

Why my IF statement and OR operator doesn't give me the expected output?


I'm actually not sure what is wrong here, but the code just doesn't give me what I want.

Technically, what I want it to do is if I write '0' which will be in the dictionary (can be more depending how many items it has) or 'N', it will stop. But it doesn't work. It always run the if instead of the else.

Is it something obvious that I can't see or just a bug (unlikely)

from time import sleep

inventory = {}
character = {'Energy': 180}
inventory['Red Mushroom'] = {'Quantity': 1,
                                   'Description': 'It looks good for the Energy, but also a tasteful snack...',
                                   'Effect': 35}

def show_inve():
    sleep(1)
    mapear = {}
    if inventory == {}:
        print('Its empty...\n')
    else:
        for i, pos in enumerate(inventory):
            print(f'[{i}] {pos:<10}: {inventory[pos]["Quantity"]:>0}')
            mapear[str(i)] = pos

        while True:
            sleep(1)
            decision = input('Type the number of the item or N to leave: ').strip()
            if decision not in mapear or decision != 'N':
                sleep(1)
                print('Not an option.')
                continue
            else:
                break


show_inve()

Solution

  • You need and operator. An or operator checks if either of the condition is True. When we put N, of course it is not in mapear, and if decision not in mapear evaluates to True. Since, it is a logical or operator and 1 condition has evaluated to True, it will not break, instead it will execute the block inside if statement.

    if decision not in mapear and decision != 'N':
        sleep(1)
        print('Not an option.')
                    
    else:
        break
    

    Here is a flowchart of and and or enter image description here