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

Joh*_*ith 0 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
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*ers 9

你误解了这个or表达方式.请改用:

if Choice1.lower() == 'life':
Run Code Online (Sandbox Code Playgroud)

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

if Choice1 in ('Life', 'life'):
Run Code Online (Sandbox Code Playgroud)

或者,如果你必须使用or然后像这样使用它:

if Choice1 == 'Life' or Choice1 == 'life':
Run Code Online (Sandbox Code Playgroud)

并将其扩展到您的其他Choice1测试.

Choice1 == 'Life' or 'life'被解释为(Choice1 == 'Life') or ('life'),后者总是为真.即使它解释为Choice1 == ('Life' or 'life')然后后者将'Life'仅评估(对于布尔测试而言它是真的),所以你要测试是否Choice1 == 'Life'相反,并且设置Choice'life'永远不会使测试通过.