无法将字符串转换为浮点值?

2024-05-23 18:29:41 发布

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

我问用户输入的数字是不是一个数字,然后我问用户输入的数字是不是一个有效的数字。在需要计算产品总数(乘以输入的数量)之前,它的工作正常吗?它会产生以下错误:

Traceback (most recent call last):
  File "C:\Users\User\Desktop\A453 Task 2.py", line 25, in <module>
    price=float(itemsplit[2]) #price is
ValueError: could not convert string to float: 'magent,'

这是我的实际代码:

^{pr2}$

这是一个文本文件(名为“hardware_存储.txt“)

16923577,Hammer,3.00,
78451698,32 lrg nails,2,
17825269,32 med nails,2.00,
58246375,32 sml nails,2.00,
21963780,Drill Bits set,7.00,
75124816,Lrg Brush,2.00,
78469518,Sml Brush,1.00,         
58423790,Dust Pan,1.00,
88562247,32 lrg screws,2.00,
98557639,32 med screws,2.00,
37592271,32 sml screws,2.00,
50966394,screwdriver set,7.00,
75533458,wall bracket,0.70,
12345678, neodymium magent, 9.99
10101010, screws 12x50mm Pack 50, 2.79

我不明白发生了什么,直到你输入所需的数量。提前谢谢


Tags: 用户数量产品med数字floatpriceset
3条回答

文件hardware_store.txt的每一行都有逗号分隔的值,而不是空格。您应该按','拆分行,而不是按' '拆分。在

您还可以查看python中的CSV module来读取文件。在

我已经更正了你的密码:

假设我们有一个hardware_store.txtfile,它包含:

12345678 5

^{pr2}$

运行代码:

The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection a
The Hardware Store
Please enter your GTIN-8 code
12345678
How much of the product do you wish to purchase?
5
The Hardware Store
a - Place an order by barcode
x - Exit
Please make your selection x
Thank you for visiting the hardware store, come again!

在收据.txt以下内容:

\n   
+Your total spent on this product is: £:(25.00)

如果打开,则在文本编辑器中看不到\n收据.txt,我添加了'\n'只是为了清楚地表明在开头有一个新行,您只会在编辑器中看到一个空白,后面跟着+Your reset of the text...

在itemsplit列表中,您有:

itemsplit[0] = "12345678,"
itemsplit[1] = "neodymium"
itemsplit[2] = "magent,"
itemsplit[3] = "9.99"

itemsplit[2]没有任何要转换浮点的数字。在

当列表项中没有数字时,必须使用try ... except ...来捕获异常。在

相关问题 更多 >