Python: TypeError:无法用非整数类型的字符串相乘
我在做一个基于文本的“购物”程序时,遇到了一个让我有点困惑的错误。错误信息是这样的:
TypeError: can't multiply sequence by non-int of type str
这是我认为错误所在的代码片段(我在出错的行上方加了注释):
def buy():
print "\nType in a store item to buy."
find_item = raw_input(prompt)
if find_item in store_items:
print "Amount?"
amount = raw_input(prompt)
if amount:
#Error in next line?
store_rec.append(store_items[find_item] * amount)
get_buy()
如果你在想,store_items 是一个字典,里面包含了商店的商品,像这样:
store_items = {
"carrot": "carrot",
"apple": "apple",
"pear": "pear",
"taco": "taco",
"banana": "banana",
"tomato": "tomato",
"cranberry": "cranberry",
"orange": "orange",
}
然后store_rec 是一个空列表,像这样:
store_rec = []
这个列表用来给用户推荐下次该买什么,但我觉得错误不在这里。我在出错的那一行想做的是,把用户指定的商品数量添加到空的store_rec 列表里。不幸的是,我遇到了错误。看起来应该可以正常工作,但实际上却不行。所以,考虑到这一点,任何对我问题的帮助都非常感谢!
1 个回答
3
如果你仔细看这个错误信息,它其实在告诉你哪里出问题了——把一个序列(比如列表)和一个字符串相乘是没有意义的;你必须先把这个字符串转换成整数。
要把这个金额转换成整数,可以把这一行代码:
amount = raw_input(prompt)
改成:
amount = int(raw_input(prompt))