2014-06-25 79 views
-5

我在這裏有一個示例程序,當我運行它並選擇一個選項但返回以下錯誤時,我看不到問題。Python類型錯誤不支持的操作數

TypeError: unsupported operand type(s) for -: 'str' and 'int'

#Exception Handling 

#If you haven't seen them before, you're not trying hard enough. What are they? Errors. Exceptions. Problems. Know what I'm talking about? I got it with this program: 

#Code Example 1 - buggy program 
def menu(list, question): 
    for entry in list: 
     print (1 + list.index(entry),) 
     print (")" + entry) 

    return input(question) -1 

answer = menu(['A','B','C','D','E','F','H','I'],\ 
'Which letter is your favourite?') 

print ('You picked answer ' + (answer + 1)) 
+0

您可能使用的是錯誤版本的Python。在2.7中,如果用戶輸入一個整數,'input'將返回一個整數;在3.x中,它將返回一個字符串。 – Kevin

+0

你想輸入什麼?字母或數字? –

+2

我猜你試圖關注[this](http://www.sthurlow.com/python/lesson11/)教程。直言不諱,我建議找一個新的教程;這一個沒有被編輯得很好。第一個代碼示例使用'input',但他聲稱生成的堆棧跟蹤是指'raw_input'。那裏有奇怪的事情發生。而且他建議下載Python 2.4並不令人鼓舞。 – Kevin

回答

1

如果使用Python3然後input(question)返回字符串'1''2',等等。你必須把它轉換成數字int(input(question))

+0

嗨!這是我嘗試的第一件事,但我得到了相同的錯誤 – Xivilai

+0

Traceback(最近一次調用最後一次): 文件「C:\ Users \ Administrator \ Google Drive \ Knowledge Base Ned \ Learn \ IT \ Python \ Scripts \ sthurlow \ exceptionHandling .py「,第14行,在 '你最喜歡哪一個字母?') 文件」C:\ Users \ Administrator \ Google Drive \ Knowledge Base Ned \ Learn \ IT \ Python \ Scripts \ sthurlow \ exceptionHandling.py「 ,第11行,在菜單中返回int(輸入(問題)-1) TypeError:不支持的操作數類型爲 - :'str'和'int' – Xivilai

+0

它已經指出我應該尋找一個更高達日期教程,所以我可能會這樣做。我能夠得到所有其他的例子,除了一個 – Xivilai

相關問題