Python 逻辑或运算符的行为不符合预期

Python 逻辑或运算符的行为不符合预期,python,if-statement,logical-or,Python,If Statement,Logical Or,当它说 你。。。 您可以键入寿命、皮卡、外观或库存。 我有很多关于这个程序的代码,我只是给你们看一部分。 但每次我运行它时,它总是显示“生活”部分,即使您键入“皮卡”、“外观”或“库存”。 请帮忙! 谢谢 约翰 编辑: 我认为这只是一个间距问题,但我不确定它之前是否运行良好…您误解了或表达式。改用这个: def Forest(Health,Hunger): print'You wake up in the middle of the forest' Inventory = 'In

当它说 你。。。 您可以键入寿命、皮卡、外观或库存。 我有很多关于这个程序的代码,我只是给你们看一部分。 但每次我运行它时,它总是显示“生活”部分,即使您键入“皮卡”、“外观”或“库存”。 请帮忙! 谢谢 约翰

编辑:
我认为这只是一个间距问题,但我不确定它之前是否运行良好…

您误解了
表达式。改用这个:

def Forest(Health,Hunger):
    print'You wake up in the middle of the forest'
    Inventory = 'Inventory: '
    Squirrel =  'Squirrel'
    while True:
        Choice1 = raw_input('You...\n')
        if Choice1 == 'Life' or 'life':
            print('Health: '+str(Health))
            print('Hunger: '+str(Hunger))
        elif Choice1 == 'Look' or 'look':
            print 'You see many trees, and what looks like an edible dead Squirrel, \na waterfall to the north and a village to the south.'
        elif Choice1 == 'Pickup' or 'pickup':
            p1 = raw_input('Pickup what?\n')
            if p1 == Squirrel:
                if Inventory == 'Inventory: ':
                    print'You picked up a Squirrel!'
                    Inventory = Inventory + Squirrel + ', '
                elif Inventory == 'Inventory: Squirrel, ':
                        print'You already picked that up!'
            else:
                print"You can't find a "+str(p1)+"."
        elif Choice1 == 'Inventory' or 'inventory':
            print Inventory
或者,如果必须针对多个选项进行测试,请使用中的

if Choice1.lower() == 'life':
if Choice1 == 'Life' or Choice1 == 'life':
或者,如果必须使用
,则如下所示:

if Choice1 in ('Life', 'life'):
并将其扩展到其他
选项1
测试

Choice1=='Life'或'Life'
被解释为
(Choice1=='Life')或('Life')
,后一部分始终为真。即使它被解释为
Choice1==('Life'或'Life')
,那么后面的部分将只计算为
'Life'
(就布尔测试而言,这是正确的),因此您将测试
Choice1=='Life'
,而将
选项设置为
生命“
将永远不会通过测试。

使用
中的

if Choice1.lower() == 'life':
if Choice1 == 'Life' or Choice1 == 'life':
或者,您可以使用正则表达式:

elif Choice1 in ('Pickup', 'pickup'):
另外,我会为您的库存使用
集合

import re

elif re.match("[Pp]ickup", Choice1):
你有:

Inventory = set()
Squirrel =  'Squirrel'
while True:
...
        if p1 == Squirrel:
            if not Inventory:
                print'You picked up a Squirrel!'
                Inventory.add(Squirrel)
            elif Squirrel in Inventory:
                print'You already picked that up!'
这实际上相当于:

    if Choice1 == 'Life' or 'life':
非空/非零字符串(“life”)将始终被视为true,因此您最终会出现这种情况

您想要:

    if (Choice1 == 'Life') or 'life':
或:


说真的,我想在过去两天里,我已经看过四次完全相同的问题,针对完全不同的问题。你显然有问题:P@DanielRoseman在我不知道为什么之前,它就已经发生在我身上了?@DanielRoseman我已经看到更多了@DanielRoseman我也在Reddit上多次看到它。它仍然有同样的问题。但是我可以开始用这个来代替or。谢谢你真的应该考虑其他答案……克里斯,我还在读所有的答案。LolI刚刚在(‘帮助’、‘帮助’)中把一切都改成了elif Choice1,效果非常好,谢谢!我只是做了一些计时<(b,c)
中的code>a比
a快2到3倍。lower()==c
,比
a==b或a==c
快约30%。(在Python3.3.0上测试)@TimPietzcker很有趣,不过对于自由形式输入,lower()可能更好,因为它可以捕获“LIfe”或类似的变体。为了完整起见,我可能还会添加一个strip(),例如Choice1.strip().lower()