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

时间:2013-03-12 21:59:26

标签: python if-statement logical-or

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

我试图在它说的时候这样做 您... 您可以键入Life,Pickup,Look或Inventory。 我在这个程序上有更多的代码我只是向你展示一部分。 但每次运行它时,即使您键入“Pickup”或“Look”或“Inventory”,它也始终显示“Life”部分。 请帮忙! 谢谢, 约翰

编辑: 我认为这只是一个间距问题,但我不确定它早先运行良好......

3 个答案:

答案 0 :(得分:9)

您误解了or表达式。请改用:

if Choice1.lower() == 'life':

或者,如果您必须针对多个选项进行测试,请使用in

if Choice1 in ('Life', 'life'):

或者,如果您必须使用or,请按照以下方式使用它:

if Choice1 == 'Life' or Choice1 == 'life':

并将其展开到其他Choice1测试。

Choice1 == 'Life' or 'life'被解释为(Choice1 == 'Life') or ('life'),后一部分始终为True。即使它解释为Choice1 == ('Life' or 'life'),那么后一部分只会评估为'Life'(就布尔测试而言它是真的),所以你要测试是否相反,Choice1 == 'Life',将Choice设置为'life'将永远不会通过测试。

答案 1 :(得分:3)

你有:

    if Choice1 == 'Life' or 'life':

实际上相当于:

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

非空/非零字符串('生命')将始终被视为真,因此您最终会在那里结束。

你要么:

    if Choice1 == 'Life' or Choice1 == 'life':

或:

    if Choice1.lower() == 'life':

答案 2 :(得分:1)

使用in

elif Choice1 in ('Pickup', 'pickup'):

或者,您可以使用正则表达式:

import re

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

另外,我会为您的广告资源使用set

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!'
相关问题