【问题标题】:Python - 'Can't multiply sequence by non-int of type 'str'' error? [duplicate]Python - '不能将序列乘以'str'类型的非整数'错误? [复制]
【发布时间】:2017-09-02 03:35:08
【问题描述】:

所以我正在开发一个代码,让用户输入产品的 GTIN-8 代码,输入他们想要的金额,然后提供收据。但是,当我到达代码的最后一部分时,我试图将产品的数量和价格相乘,我得到了“不能将序列乘以非 int 类型的‘str’错误。 以下是部分代码:

while IfFinished != "Yes":
    ProductsWanted=input("Please enter the GTIN-8 Code of the product: ")
    AmountOfProducts=input("How many do you want? ")

    with open("Productsfile.txt") as f:
        for line in f:
                if ProductsWanted in line:
                    Receipt=open("ReceiptFile.txt","a")
                    Receipt.write("%r, %r, \n" % (line, AmountOfProducts))
                    Receipt.close()

    if ProductsWanted not in ["23456945","12376988","76543111","92674769","43125999"]:
        print("Product not found")

    else:
        print("Product found")

    IfFinished=input("Are you done? If so, type 'Yes' ")
    if IfFinished == "Yes":
        print("Thank you for shopping with us!")
    else:
        print("Please continue")

Receipt=open("ReceiptFile.txt","r")
print(Receipt.read())
Receipt.close()

with open("ReceiptFile.txt","r") as file:
    for line in file:
        currentline=line.split(",")
quantity=currentline[3]
ItemPrice=currentline[2]
Totalprice=quantity*ItemPrice
price="0"
Total=price + Totalprice

print(Total)

【问题讨论】:

  • 请逐字发布您从 Python 获得的确切错误。
  • 您假设quantityItemPrice 是整数,但它们不是。
  • 检查quantityItemPrice;它们长什么样子,有哪些类型?

标签: python


【解决方案1】:

这里,当你从文件中获取值时,它们是字符串类型的:

quantity=currentline[3]
ItemPrice=currentline[2]

在相乘之前需要将它们转换为int,例如:

quantity=int(currentline[3])

【讨论】:

  • How to Answer 中所述,请避免回答不清楚、过于宽泛、错字、基于意见、无法重现或重复的问题。编写我的代码请求和省力的家庭作业问题对于Stack Overflow 来说是题外话,更适合专业的编码/辅导服务。好的问题坚持How to Ask,包括minimal reproducible example,有研究工作,并且有可能对未来的访问者有用。回答不恰当的问题会使网站更难导航并鼓励进一步提出此类问题,从而损害网站,这可能会赶走其他自愿提供时间和专业知识的用户。
猜你喜欢
  • 1970-01-01
  • 2019-04-12
  • 2013-07-03
  • 1970-01-01
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 2019-09-07
相关资源
最近更新 更多