0
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”部分。请帮忙!谢谢,约翰

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

4

3 回答 3

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'),后半部分始终为真。即使它解释为Choice1 == ('Life' or 'life')then 后一部分将评估为'Life'only (就布尔测试而言它是 True ),因此您将Choice1 == 'Life'改为测试 if ,并且设置Choice'life'永远不会使测试通过。

于 2013-03-12T22:01:00.470 回答
3

你有:

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

这实际上相当于:

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

非空/非零字符串('life')将始终被视为 true,因此您最终会出现在此处。

你要么想要:

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

或者:

    if Choice1.lower() == 'life':
于 2013-03-12T22:02:53.313 回答
1

使用in

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

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

import re

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

另外,我将使用 aset作为您的库存:

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!'
于 2013-03-12T22:01:56.207 回答