2014-06-25 57 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

相关问题