到目前为止,这是我的代码:
with open("products.txt", "r") as productsFile:
GTIN8 = input("Enter your GTIN-8 product code: ")
productsFileReader = csv.reader(productsFile)
for row in productsFileReader:
for field in row:
if field == GTIN8:
print (row) #displays the product details
price1= (row[4])
quantity= (int(input("how many of these would you like to purchase?:")))
totalprice= quantity * price1 #multiplies quantity by price
print (totalprice)
我目前正在尝试将'price1'的变量乘以将由用户输入的'quantity'。 price1来自我创建的csv txt.file中的一行。
每次我运行程序时,乘以的价格(例如,如果是2.50英镑)显示为“£2.50£2.50£2.50”。
如何将我的python代码多个变量组合在一起?
感谢
productsFileReader = csv.reader(productsFile)
for row in productsFileReader:
for field in row:
if field == GTIN8:
item1= print (row)#displays the product details
price1= (row[4])
quantity= (int(input("how many of these would you like to purchase?:")))
totalprice= quantity * float(price1.replace("£", "")) #multiplies quantity by price
print (totalprice)
print("Thankyou, your item will cost: "+totalprice)
现在,当我尝试在程序结束时显示价格时出现错误:
TypeError:无法将'float'对象隐式转换为str
根据我的理解,我需要将float(我之前更改过的)变成一个整数,以便我的代码可以显示价格。但是怎么样? 再次感谢
答案 0 :(得分:1)
您正在尝试将字符串(price
)与整数(quantity
)相乘。这就是为什么你得到这样的输出。您需要转换正在从文件中获取的数据。
price1 = float(row[4].lstrip('£'))
答案 1 :(得分:1)
price1是一个字符串,你将它乘以一个int,这只会导致字符串被连接n次。
>>> animal = "cat"
>>> animal*4
'catcatcatcat'
您需要将price1转换为浮点数,然后才能将其乘以int以获得预期结果。这是通过float函数完成的。但是,如果你在价格字符串上调用float,你会因为£符号而得到一个ValueError,所以你必须先使用str.replace删除它,如下所示:
>>> price = "£2.50"
>>> price = price.replace("£", "")
>>> float(price)
2.5
将其整合到您的代码中:
price1 = row[4]
quantity = int(input("how many of these would you like to purchase?:"))
totalprice = quantity * float(price1.replace("£", "")) # multiplies quantity by price