【问题标题】:Could not convert string to float?无法将字符串转换为浮点数?
【发布时间】:2017-05-14 14:54:58
【问题描述】:

我正在编写一个基本上要求用户输入 8 位数字的代码,然后从文本文件中读取它以查看它是否有效,然后询问用户数量。它工作正常,直到需要计算产品的总数(乘以输入的数量)?它会产生这个错误:

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,'

这是我的实际代码:

loop=1
while loop==1:
    print ("The Hardware Store")
    print ("a - Place an order by barcode")
    print ("x - Exit")
    task=input("Please make your selection")
    if task.lower()=="a":
        print("The Hardware Store")
        myfile=open("hardware_store.txt", "r") #this opens the text file
        product_information=myfile.readlines() #reads the file and stores it 
as a variable named variable 'details'
        myfile.close() #closes the file
        while True:
            digits=input("Please enter your GTIN-8 code\n") 
            if len(digits) !=8: #if the digits aren't equal to 8 digits, the 
input not accepted
                print("Please enter a valid GTIN-8 code\n") 
            else:
                break #if the code is the correct length, the loop ends
        for line in product_information:
            if digits in line:
                productline=line 
                myfile=open("receipt.txt", "w") #opens receipt file
                myfile.writelines("\n" + "+")
                quantity=input("How much of the product do you wish to purchase?\n")
                itemsplit=line.split(' ') #seperates into different words
                price=float(itemsplit[2]) #price is
                total=(price)*(quantity) #this works out the price
                myfile.writelines("Your total spent on this product is: " +str("£:,.2f)".format(total)+"\n"))
    if task.lower()=="x":
        print("Thank you for visiting the hardware store, come again!")
        break
    else:
        print("Sorry, please enter a valid input")

这里是文本文件(名为“hardware_store.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

我不明白发生了什么,直到您输入所需数量为止。提前致谢

【问题讨论】:

  • 分隔符是,(comma) 而不是(space) 了解split() 方法。应该有逗号而不是空格

标签: python


【解决方案1】:

您的文件hardware_store.txt 的每行值都用逗号分隔,而不是空格。您应该用',' 分割行,而不是' '

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

【讨论】:

    【解决方案2】:

    在项目拆分列表中你有:

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

    itemsplit[2] 没有任何数字可以转换为浮点数。

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

    【讨论】:

      【解决方案3】:

      我已经更正了你的代码:

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

      12345678 5
      

      task = ""
      while task.lower() != "x":
          print ("The Hardware Store")
          print ("a - Place an order by barcode")
          print ("x - Exit")
          task=input("Please make your selection ")
          if task.lower()=="a":
              print("The Hardware Store")
              myfile=open("hardware_store.txt", "r") #this opens the text file
              product_information=myfile.readlines() #reads the file and stores it as a variable named variable 'details'
              myfile.close() #closes the file
      
              while True:
                  digits=input("Please enter your GTIN-8 code\n")
      
                  if not len(digits) == 8: #if the digits aren't equal to 8 digits, the input not accepted
                      print("Please enter a valid GTIN-8 code\n")
                  else:
                      break #if the code is the correct length, the loop ends
              for line in product_information:
                  if digits in line:
                      #productline=line
                      myfile=open("receipt.txt", "w") #opens receipt file
                      myfile.write("\n" + "+")
                      quantity=input("How much of the product do you wish to purchase?\n")
                      quantity = int(quantity)
      
                      price = line.split(" ")[1]
                      price=float(price) #price is
                      total=(price)*(quantity) #this works out the price
                      myfile.write("Your total spent on this product is: £:({:.2f}){}".format(total, '\n'))
                      myfile.close()
      
                  else:
                      print("Sorry, please enter a valid input")
      else:
          print("Thank you for visiting the hardware store, come again!")
      

      运行代码:

      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)
      

      如果您打开receipt.txt,您将不会在文本编辑器中看到\n,我包含'\n' 只是为了清楚说明开头有一个新行,您只会看到一个编辑器中的空白区域,后跟+Your reset of the text...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多