简体   繁体   English

为什么我的 IF 语句和 OR 运算符没有给我预期的输出?

[英]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.从技术上讲,我想要它做的是,如果我写下字典中的“0”(可能更多,取决于它有多少项目)或“N”,它将停止。 But it doesn't work.但它不起作用。 It always run the if instead of the else.它总是运行 if 而不是 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()

You need and operator.你需要and运营商。 An or operator checks if either of the condition is True. or运算符检查其中一个条件是否为真。 When we put N , of course it is not in mapear , and if decision not in mapear evaluates to True .当我们放置N ,当然它不在mapearif decision not in mapear评估为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.由于它是一个逻辑or运算符,并且 1 条件已评估为 True,因此它不会中断,而是会执行if语句中的块。

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

Here is a flowchart of and and or这是andor的流程图在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM