【问题标题】:Why my IF statement and OR operator doesn't give me the expected output?为什么我的 IF 语句和 OR 运算符没有给我预期的输出?
【发布时间】:2021-07-01 02:08:09
【问题描述】:

我实际上不确定这里出了什么问题,但是代码并没有给我想要的东西。

从技术上讲,我想要它做的是,如果我写“0”,它将在字典中(可能更多取决于它有多少项目)或“N”,它将停止。但它不起作用。它总是运行 if 而不是 else。

是我看不到的明显东西还是只是一个错误(不太可能)

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()

【问题讨论】:

  • 为什么你需要在你的'if'结尾处'continue'?尝试删除它。

标签: python if-statement logic operators


【解决方案1】:

您需要and 运算符。 or 运算符检查任一条件是否为真。当我们放入N 时,当然它不在mapear 中,而if decision not in mapear 的计算结果为True。因为它是一个逻辑 or 运算符,并且 1 个条件的计算结果为 True,所以它不会中断,而是会执行 if 语句中的块。

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

这是andor的流程图

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2012-02-22
    相关资源
    最近更新 更多