TypeError:不支持的操作数类型 - :'str'和'int'“ - 如何阻止它?

时间:2017-04-03 14:36:13

标签: python

由于我是初学者,我目前正在使用基本语言编写图书借阅系统。所以,我有一个单独的文件(见下文),其中有一个代表每本库存书籍的数字,以及每本书的库存和目标库存号。用户输入书籍以及他们想要借出的数量。我想要的是程序然后找出剩余的库存数量,并让他们知道现在需要订购多少份才能达到所需的库存水平。这是我的代码:

BookNumber=input("Enter the 2 digit number on the back of the book that you'd like to loan\n")
NumberToLoan=input("How many copies of this book would you like to loan?\n")

x = open("BookStockFile.txt", "r+")

found = 0
for line in x.readlines():
    t = line.split(" ")
    if(t[0]==BookNumber):
        found = 1
        CurrentStockOfBook = int(t[1]) #Number of this book in stock
        PreferredStockNumber = str([2]) #Target for the number of copies of this book to be in stock
        NewStockOfBook =(CurrentStockOfBook) - int(NumberToLoan) #Stock of the book after this order
        RestockNumber = PreferredStockNumber - NewStockOfBook #How much they now need to restock after this person loans the book in order to reach the preferred stock number

当我运行代码时,会出现:

RestockNumber= PreferredStockNumber - NewStockOfBook 

TypeError: unsupported operand type(s) for -: 'str' and 'int'

我试图改变每个变量的数据类型,但同样的事情即将出现。请帮忙!

BTW,我的BookStockFile看起来像这样(第一栏= 2位数的书号,第二栏=本书的当前库存,第三栏=目标/首选库存号):

12 5 12

16 8 8

13 12 19

19 2 3

18 7 9

这些空格将书号,当前库存水平和所需库存水平相互分开。提前致谢

2 个答案:

答案 0 :(得分:1)

在这一行: PreferredStockNumber = str([2])

您正在将PreferredStockNumber转换为字符串,然后尝试在两行之后减去intNewStockOfBook。不仅类型不匹配,而且减号运算符一般不会对字符串起作用。

我认为你真的不希望你的任何数字表现为字符串,我会坚持使用整数。

如下面的评论所述,还有一个拼写错误。你有str([2])而不是str(t [2])。

答案 1 :(得分:0)

请检查以下代码:

BookNumber=input("Enter the 2 digit number on the back of the book that you'd like to loan\n")
NumberToLoan=input("How many copies of this book would you like to loan?\n")

x = open("BookStockFile.txt", "r+")

found = 0
for line in x.readlines():
    t = line.split(" ")
    if(int(t[0])==int(BookNumber)):
        found = 1

        CurrentStockOfBook = int(t[1]) #Number of this book in stock
        PreferredStockNumber = int(t[2]) #Target for the number of copies of this book to be in stock
        NewStockOfBook = CurrentStockOfBook - int(NumberToLoan) #Stock of the book after this order
        print "New Stock of Books: " + str(NewStockOfBook)
        RestockNumber = PreferredStockNumber - NewStockOfBook #How much they now need to restock after this person loans the book in order to reach the preferred stock number
        print "New Restock Number: " + str(RestockNumber)

由于您的错误是由于PreferredStockNumber = str([2])的错误转换,您需要将其转换为int。 另外我假设你想要t [2]值。

我建议你用这个角色分割线条";"在.txt文件中