2017-05-13 1 views
1

나는 기본적으로 8 자리 숫자의 사용자 입력을 요구하는 코드를 작성하고,이 코드는 텍스트 파일에서 읽혀 유효한지 확인한 다음 사용자에게 수량을 묻습니다. 그것은 제품의 합계 (입력 된 수량 곱한) 계산해야 할 때까지 잘 작동합니까? 텍스트 파일 (명 "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 

그렇게하지 여기

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") 

그리고있다 :

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

내 실제 코드이다 : 그것은이 오류가 발생합니다 무슨 일이 일어나고 있는지 이해하고, 원하는 양을 입력 할 때까지 작동합니다. 미리 감사드립니다.

+4

구분 기호는'split()'메소드에 대한'(공백)'이 아니라', (쉼표)'입니다. 공간 대신 ​​쉼표가 있어야합니다. –

답변

-1

파일 hardware_store.txt은 공백이 아닌 쉼표로 각 행에 값을 구분합니다. 너는 ','이 아니라, ' '으로 줄을 나눠야합니다.

파이썬에서 CSV module을보고 파일을 읽을 수도 있습니다. itemsplit에서

-1

당신이 가진 목록 :

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

itemsplit[2]는 플로트 캐스팅 임의의 숫자를 가지고 않았습니다.

목록 항목에 숫자가 없을 때 예외를 catch하려면 try ... except ...을 사용해야합니다.

-1

나는 당신의 코드를 수정했습니다

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! 
:

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!") 

코드를 실행 : 그래서 우리는이 말을

을 포함하는


receipt.txt :

\n 
+Your total spent on this product is: £:(25.00) 
열려 receipt.txt, 나는 '\n'을 포함 한 경우 당신은 단지 새로운 라인 거기에 분명히 있음을 확인하기 위해 텍스트 편집기에서 \n를 볼 수 없습니다

처음에는 편집기에서 빈 공간을 보게 될 것입니다. +Your reset of the text...

관련 문제