1

テキストベースのゲーム用にこのコードを作成しましたが、次のエラーが表示されます

 line 1, in <module>
userInput = input("Please enter a direction in which to travel: ")
 File "<string>", line 1, in <module>
NameError: name 'north' is not defined

これが私のコードです

userInput = input("Please enter a direction in which to travel: ")
Map = {
    'north':'that way leads to the kitchen', 
    'south':'that way leads to the dining room', 
    'east':'that way leads to the entry', 
    'west':'that way leads to the living room'
}
if userInput == north:
    print Map['north']
elif userInput == south:
    print Map['south']
elif userInput == east:
    print Map['east']
elif userInput == West:
    print Map['west']
elif userInput == '':
    print "Please specify a various direction."
else:
    quit

助けてくれてありがとう

4

2 に答える 2

0

Python 2 を使用する場合は、常に を使用raw_input()してユーザーからの入力を取得する必要があります。

input()と同等eval(raw_input())です。したがって、コードは、入力時に「north」という変数を見つけようとしています。

ただし、Python 3 では、 Python 2input()と同じように動作しraw_input()ます。


また、作成した変数ではなく、入力を文字列と比較する必要があります。たとえば、 でif userInput == northある必要がありますif userInput == 'north'。これ'north'で文字列ができます。

コードを次のように要約できます。

print Map.get(userInput, 'Please specify a various direction')
于 2013-09-26T22:54:31.870 に答える