2013-09-26 57 views
1

定義我爲我的基於文本的遊戲的代碼和我收到一個錯誤說Python的NameError:名字「北」不是文字遊戲

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 

感謝您的幫助

+0

如果這實際上是你的代碼,你承擔責任後,你收到了很多IndentationErrors'的'在你的指示周圍放置一些引號,使它們成爲字符串。 – roippi

+0

問題在於你的if語句,但你也可以大大簡化。在下面檢查我的答案。我提供了工作代碼。 –

+1

另外,python中沒有'quit'關鍵字。 – SethMMorton

回答

0

當使用Python 2時,您應始終使用raw_input()來獲取來自用戶的輸入。

input()相當於eval(raw_input());因此,你的代碼試圖找到一個名爲「北」,當你鍵入它的變量。

然而,在Python 3,input()的作用一樣raw_input()做在Python 2


你也應該將您的輸入與字符串進行比較,而不是您創建的變量。例如,if userInput == north應該是if userInput == 'north'。這使得'north'成爲一個字符串。

你可以只總結一下你的代碼:

print Map.get(userInput, 'Please specify a various direction') 
+0

噢好吧,所以更改userInput = input(「請輸入旅行的方向:」)到userInput = raw_input(「請輸入旅行的方向:」) – TheEvanElement

+0

@TheEvanElement Yep! – TerryA

+0

謝謝!很好的幫助! – TheEvanElement

2

此行

if userInput == north: 
    ... 

是要求命名userInput變量是否是一樣的變量north

但是您尚未定義名爲north的變量。該行應該與這樣的字符串'north'進行比較。

if userInput == 'north': 
    ... 

但是,您可以在像這樣的字典鍵中測試用戶輸入。我已將你的常數改爲全部大寫。

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' 
} 
userInput = raw_input("Please enter a direction in which to travel: ") 
if userInput in MAP.keys(): 
    print MAP[userInput] 

此外,正如在另一個答案中提到的,raw_input比輸入更安全。

另一種方法是像這樣捕獲KeyError。

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' 
} 
userInput = raw_input("Please enter a direction in which to travel: ") 
try: 
    print MAP[userInput] 
except KeyError: 
    print 'What?' 

或重複,直到有效的輸入提供這樣的(並使其不區分大小寫):

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' 
} 
while True: 
    userInput = raw_input("Please enter a direction in which to travel: ").lower() 
    try: 
     print MAP[userInput] 
     break 
    except KeyError: 
     print '%s is not an option' % userInput 
+1

我不知道爲什麼我得到了投票。任何人都可以給我一個線索(或投票)嗎? –

+0

對我來說很合適。 Upvoted。 –