在此之前,我绝不是一名程序员,我的大学专业要求学习1种代码语言。我们在Thonny中使用Pyhthon
我的任务是编写代码“将从名为ABC_inventory.txt的文件中处理库存。该文件包含存储在文件中单独一行的项目ID、说明和标价。该程序应显示每条记录的内容,然后计算并显示平均标价。”
我编写了以下代码:
Inventory = open('ABC_Inventory.txt', 'r')
ItemID = ""
ItemDesc = ""
ItemPrice = 0.00
TotalPrice = 0.00
ItemAverage = 0.00
NumberOfItems = 0
while True:
ItemID = Inventory.readline().strip()
ItemDesc = Inventory.readline().strip()
ItemPrice = float(Inventory.readline().strip())
TotalPrice += ItemPrice
NumberOfItems += 1
ItemAverage = TotalPrice / NumberOfItems
if ItemID == "":
break
print(ItemID + " is " + ItemDesc + " and is priced at: " + str(ItemPrice))
Inventory.close()
print("Average list price is : " + ItemAverage)
我得到一个错误:
Traceback (most recent call last):
ItemPrice = float(Inventory.readline().strip())
ValueError: could not convert string to float:
我做错了什么?任何帮助都将不胜感激
这是库存文件,如果有必要的话:
BP2500
3-PERSON TENT
75.0
BP1000
LOUNGE CHAIR
50.0
BP3000
PROPANE HEATER
149.0
BP0900
HIKING BOOTS
120.0
BP0950
BACKPACK
100.0
BP3050
GPS TRACKER
130.0
我认为程序寻找每一行进行转换,这是绝对错误的。如果您知道该值将是浮点值,请尝试以下代码,该代码将忽略错误并在程序中的平均值之前添加一行:
float()方法只允许转换看起来像浮点的字符串。这意味着您无法在以下情况下转换值:
如果未能满足上述三个条件中的任何一个,将引发“valueerror:无法将字符串转换为浮点”错误。这是因为Python无法将值转换为浮点值,除非该值以特定方式显示
相关问题 更多 >
编程相关推荐