2016-02-11 29 views
0

我正在写一段代码来完成滚动。我努力在文本文件中获取价格并将其乘以用户输入的数量。我不知道如何解决。努力从文本文件中乘以一个数字(Python)

这就是我迄今为止所做的;

的代码部分也是如此,下面

def receipt(): 
    food = input("Enter the product code for the item you want.") 

    fi = open("data.txt","r") 
    info = fi.readlines() 
    fi.close() 
    item = False 
    for li in info: 
     if(li.split(":")[0].lower() == food): 
      print(li.split(":")[1]) 
      item = True 
      quantity = input("How many do you want?")   
      print("£" + quantity) 
receipt() 

的文本文件:

12345670:Burgers, £1:1.30 
19203123:Cheese, £2.50:2.50 
98981236:Crisps, 0.55p:0.55 
56756777:Alphabetti Spaghetti, £1.45:1.45 
90673412:Sausages, £2.30:2.30 
84734952:Lemonade, 0.99p:0.99 
18979832:Ice Cream, £1.50:1.50 
45353456:6 Pack of Beer, £5:5.00 
98374500:Gum, 0.35p:0.35 
85739011:Apples, 0.70p:0.70 

我想我必须使用.append或名单,但我不知道他们是如何工作的我还没有学到他们。

+2

有什么麻烦?什么是错误?预期产出是多少? – timgeb

+1

为什么每一行的价格是两倍? – timgeb

+0

你的代码试图进行乘法运算的地方在哪里?如果你不发布代码,我们应该如何向你展示你做错了什么? – Barmar

回答

0

你只需要提取的文件中的行价,并将其转换成一个浮点数:

price = float(li.split(":")[2]) 

会给你项目的价格上给定线路。这会将行尾的价格转换为浮点数或十进制数,然后您可以使用它。

0

要获得总价格,您需要获取用户输入的数量并将其转换为整数(浮点数实际上没有意义)。您可以通过li.rsplit(':',1)[-1]获得价格。不要忘记将其转换为浮动。

演示:

>>> quantity = int(input('how many do you want? ')) # make int out of input string 
how many do you want? 10 
>>> li = '90673412:Sausages, £2.30:2.30' # example line 
>>> quantity * float(li.rsplit(':', 1)[-1]) 
23.0 

应该让你开始那。

0

我建议更新for循环,像这样的线分割成各自的部分,那么你可以操纵的部分,你需要像id.lower()float(price)

for li in info: 
    id,desc,price = li.split(':') 
    if id.lower() == food: 
     item = True 
     quantity = int(input("How many do you want? ")) 
     print("£" + str(quantity*float(price))) 
0

@狼:请尝试下面的代码,它应该工作。由于从 txt文件检索到的数据是ASCII格式,因此if条件似乎失败。

import chardet 

def receipt(): 
    food = input("Enter the product code for the item you want.") 
    fi = open("data.txt","r") 
    info = fi.readlines() 
    fi.close() 
    item = False 
    for li in info: 
     a = li.split(":")[0].lower() 
     encoding = chardet.detect(a) 
     #print encoding 
     #int(a) 
     #print int(a) 
     if int(a) == food: 
      #print "pass" 
      print(li.split(":")[1]) 
      #print item 
      item = True 
      quantity = input("How many do you want?") 
      print(quantity) 
receipt() 
+0

我试过这个,但它没有工作,它告诉我,有'没有模块命名chardet' – Wolf

+0

@Wolf:chardet是一个点子包,请尝试下载它。 – Bangi

相关问题