Python作业浮点错误:ValueError:无法将字符串转换为浮点:

2024-09-27 07:28:05 发布

您现在位置:Python中文网/ 问答频道 /正文

在此之前,我绝不是一名程序员,我的大学专业要求学习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

Tags: 文件代码txtreadlineisfloatinventorystrip
3条回答

我认为程序寻找每一行进行转换,这是绝对错误的。如果您知道该值将是浮点值,请尝试以下代码,该代码将忽略错误并在程序中的平均值之前添加一行:

ItemID = ""
ItemDesc = ""
ItemPrice = 0.00
TotalPrice = 0.00
ItemAverage = 0.00
NumberOfItems = 0

while True:
    ItemID = Inventory.readline().strip()
    ItemDesc = Inventory.readline().strip()
    try:
        ItemPrice = float(Inventory.readline().strip())
    except:
        print()
    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 : " + str(ItemAverage))```

float()方法只允许转换看起来像浮点的字符串。这意味着您无法在以下情况下转换值:

A value contains spaces
A value contains a comma
A value contains non-special characters (i.e. “inf” is a special character, but “fd” is not)

如果未能满足上述三个条件中的任何一个,将引发“valueerror:无法将字符串转换为浮点”错误。这是因为Python无法将值转换为浮点值,除非该值以特定方式显示

while True:
    ItemID = Inventory.readline().strip()
    if ItemID == "":
        break
    else:
        ItemDesc = Inventory.readline().strip()
        ItemPrice = float(Inventory.readline().strip())
        TotalPrice += ItemPrice
        NumberOfItems += 1
        ItemAverage = TotalPrice / NumberOfItems
        
        print(ItemID + " is " + ItemDesc + " and is priced at: " + str(ItemPrice))
    
Inventory.close()

print("Average list price is : " + str(ItemAverage))
BP2500 is 3-PERSON TENT and is priced at: 75.0
BP1000 is LOUNGE CHAIR and is priced at: 50.0
BP3000 is PROPANE HEATER and is priced at: 149.0
BP0900 is HIKING BOOTS and is priced at: 120.0
BP0950 is BACKPACK and is priced at: 100.0
BP3050 is GPS TRACKER and is priced at: 130.0
Average list price is : 104.0
[Finished in 0.3s]

相关问题 更多 >

    热门问题