gpt4 book ai didi

Python:类型错误:无法将序列乘以 str 类型的非 int

转载 作者:行者123 更新时间:2023-11-30 23:24:11 27 4
gpt4 key购买 nike

所以,我正在制作一个基于文本的“购物”程序,并且遇到了一个对我来说不太有意义的错误。错误消息是这样的:

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 列表中。不幸的是,然后我得到了错误。看起来应该有效,但事实并非如此。因此,考虑到这一点,非常感谢对我的问题的任何帮助!

最佳答案

如果您仔细阅读该错误,它会告诉您出了什么问题——将序列乘以字符串是没有意义的;必须先将字符串转换为整数。

通过更改行将金额转换为整数:

金额 = raw_input(提示)

金额 = int(raw_input(prompt))

关于Python:类型错误:无法将序列乘以 str 类型的非 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23586449/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com