这是我的数据库代码,我使用了一个文本文件并将其插入到代码中,但是当它到达第27行时,它会出现错误
Traceback (most recent call last):
File "N:\computing\databse\task 2.py", line 27, in <module>
print("you bought", + products[i][1], "at a cost of", +str(products_total))
TypeError: bad operand type for unary +: 'str'
我已经尝试过查看很多不同的网站,但我无法弄清楚如何解决它或代码有什么问题以及为什么它不起作用!其他一切看起来都很好,如果有人可以帮我一点点,我会非常感激:
products = []
with open('StockFile.txt','r') as i:
for line in i:
line = line[:-1]
row = line.split(',')
products.append(row)
print(products)
total = 0
items = []
answer = "yes"
while answer == "yes":
GTIN = input ("Please input GTIN:")
found = False
for i in range (0,len(products)):
if GTIN == products[i][0]:
found = True
items.append(GTIN)
items.append(products[i][1])
items.append(products[i][2])
quantity = input("How many would you like?")
items.append(quantity)
product_total = int(quantity) * float (products[i][2])
items.append(product_total)
print("you bought", + products[i][1], "at a cost of", +str(products_total))
total = total + products_total
if found == False:
print("Sorry not a valid number try again")
print("DO you want another item?")
answer = input()
for i in range(0,len(items),5):
print(items[i], items[i+1], items[i+2], items[i+3], items[i+4])
print("total cost of the order is £" +str(total))
这是我正在使用的文本文件:
13245627,螺母和螺栓,0.5 34512340,简单括号,1 56756777,100mm螺栓,2.5 90673412,L形支架,0.7
答案 0 :(得分:0)
您的代码行中有一个错误:
print("you bought", + products[i][1], "at a cost of", +str(products_total))
尝试删除+
,使其看起来像:
print("you bought", str(products[i][1]), "at a cost of", str(products_total))
答案 1 :(得分:0)
您似乎混合了两种打印一系列对象的方法:通过用逗号分隔每个对象作为单独的参数,并使用+
运算符连接字符串。结果,您最终得到了一个参数+str(products_total)
。 str
班级不知道如何处理之前的+
符号。
要么坚持用逗号分隔所有的args:
print("you bought", products[i][1], "at a cost of", products_total)
或连接字符串(在这种情况下,您还需要将products[i][1]
转换为str
):
print("you bought" + str(products[i][1]) + "at a cost of" + str(products_total))
更好的是,使用string formatting,您也不需要这样做:
print("you bought {0} at a cost of {1}".format(products[i][1], products_total))