【问题标题】:Python: TypeError: can't multiply sequence by non-int of type str [duplicate]Python:TypeError:不能将序列乘以 str 类型的非整数 [重复]
【发布时间】:2014-05-10 21:22:09
【问题描述】:

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

TypeError: can't multiply sequence by non-int of type str

这是我认为错误所在位置的代码 sn-p(在我认为错误所在的行上方注释):

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 给出一个字符串,不是一个数字
  • 你为什么要把一个项目乘以一个数量。 "carrot" * amount 没有意义。您是否尝试添加字符串?
  • @jonrsharpe 哎呀,int(raw_input())
  • 又一次因为一个简单的错误搞砸了。叹息....
  • 错误不止一个!

标签: python


【解决方案1】:

如果你仔细阅读错误,它会告诉你哪里出了问题——将一个序列乘以一个字符串是荒谬的;字符串必须先转换为整数。

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

amount = raw_input(prompt)

amount = int(raw_input(prompt))

【讨论】:

  • 也可以使用浮点数吗? amount = float(raw_input(prompt))
猜你喜欢
  • 2012-09-16
  • 2013-07-03
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-07
  • 2019-04-12
  • 1970-01-01
相关资源
最近更新 更多