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

You... と表示されたら、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')、後者の部分は常にTrueです。そのよう解釈されたとしてChoice1 == ('Life' or 'life')も、後者の部分は'Life'(ブールテストが進む限りTrueである)と評価されるだけなので、Choice1 == 'Life'代わりにテストすることになり、に設定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):

これとは別に、私は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!'
于 2013-03-12T22:01:56.207 に答える