2013-04-22 91 views
0

我剛剛開始編程,並且正在努力學習Python。 how to think like a computer scientist的第四章練習5的最後部分正在困擾着我。我試圖修改shell腳本,以便用戶可以輸入'a','b'或'c',並根據用戶的選擇打印出正確的響應。這是我迄今爲止所實施的方式,並希望有人能告訴我我在這裏失去了什麼。python raw_input不工作

def dispatch(choice): 
    if choice == 'a': 
     function_a() 
    elif choice == 'b': 
     function_b() 
    elif choice == 'c': 
     function_c() 
    else: 
    print "Invalid choice." 

def function_a(): 
    print "function_a was called ..." 

def function_b(): 
    print "function_b was called ..." 

def function_c(): 
    print "function_c was called ..." 

dispatch1 = raw_input ("Please Enter a Function.") 
print dispatch(choice) 

當我運行這個我得到的名稱選擇沒有定義的錯誤。我試圖讓它回吐function_b被稱爲...當它被輸入到raw_input。

感謝您的幫助,

約翰

+2

你還沒有定義'choice',你叫它'dispatch1'。 – 2013-04-22 19:39:52

+1

請嘗試考慮一個更好的標題 - 是什麼讓你認爲'raw_input'是問題? – Adam 2013-04-22 19:40:35

+1

投票結束,因爲這只是使用錯誤的變量名稱的問題。 – chepner 2013-04-22 19:46:14

回答

5

你把投入和分配它dispatch1,不選擇:

choice = raw_input ("Please Enter a Function.") 
print dispatch(choice) 
+1

謝謝你的幫助,這麼簡單的事情讓我瘋狂。 – John 2013-04-22 20:13:55

0

工作示例..順便說一句,取在python中關注縮進。

def dispatch(choice): 
    if choice == 'a': 
     function_a() 
    elif choice == 'b': 
     function_b() 
    elif choice == 'c': 
     function_c() 
    else: 
     print "Invalid choice." 

def function_a(): 
    print "function_a was called ..." 
def function_b(): 
    print "function_b was called ..." 
def function_c(): 
    print "function_c was called ..." 

choice = raw_input ("Please Enter a Function.") 
dispatch(choice) 
+0

謝謝你的幫助。 – John 2013-04-22 20:16:41

1

James是正確的(正如Lattyware一樣)。既然你還在學習,我認爲這可能有助於提供更多關於你所看到的信息。

調度參數是一個變量。在函數調用本身內部,它被稱爲「選擇」。當您使用raw_input捕獲輸入時,您當前將其保存爲名爲「dispatch1」的變量。在你調用dispatch的時候Choice是未定義的(儘管它在函數定義中被稱爲choice,這有點令人困惑)。它是未定義的事實是你的錯誤的原因。

+0

謝謝你的擴展。 – John 2013-04-22 20:15:37