2015-04-07 39 views
0

程序應該是:我想通了這個計劃的一部分,但我不能讓過去創建分類彙總

<Program> Welcome to the checkout counter! How many items are you purchasing today? 
    <User> 3 (user presses Enter key) 
    <Program> Please enter the name of product 1: 
    <User> chicken (user presses Enter key) 
    <Program> And how much does chicken cost? 
    <User> 3.50 (user presses Enter key) 
    <Program> Please enter the name of product 2: 
    <User> chips (user presses Enter key) 
    <Program> And how much does chips cost? 
    <User> 1.25 (user presses Enter key) 
    <Program> Please enter the name of product 3: 
    <User> gum (user presses Enter key) 
    <Program> And how much does gum cost? 
    <User> .99 (user presses Enter key) 
    <Program> 
    Your order was: 
    chicken $3.50 
    chips $1.25 
    gum $.99 
    Your subtotal comes to $5.74. With 9% sales tax, your total is $6.19. 
    Please enter cash amount: 
    <User> 20.00 (user presses Enter key) 
    <Program> 
    I owe you back $13.81. 
    Thank you for shopping with us! 

提示:你將需要爲這個分配兩個單獨的列表。

我到目前爲止有:

numitems = int(input("Welcome to the checkout counter! How many items are you purchasing today?")) 
    products = [] 
    prices = [] 
    for item in range(1, numitems + 1): 
     product = raw_input ("Please enter the name of product %u:" %item) 
     products.insert(item,product) 
     price = (raw_input("And how much does %s cost?" %product)) 
     Price = str(float(price)) 
     prices.insert(item,Price) 
    print "Your order was" 
    for i in range (len(products)): 
     print products[i], "$" + prices[i] 

我不能讓過去的小計輸入,因爲它不會讓我總結的目錄價格。

+2

您將價格存儲爲字符串 - 這就是爲什麼您無法將它們加總。分配'Price'時刪除'str()',你應該能夠將它們相加。您還需要將您的電話更新爲'print':'print products [i],「$」+ str(prices [i])'...... –

+0

謝謝!這顯然非常有幫助! – Maddie

回答

0

這裏是我的解決方案:

def input_num(s, f=float): 
    while True: 
     try: 
      return f(raw_input(s)) 
     except ValueError: 
      print "Input must be a {}.".format(f.__name__) 

items = {} 
for n in xrange(input_num("Welcome to the checkout counter! How many items are you purchasing today? ", int)): 
    product = raw_input("Please enter the name of product {}: ".format(n+1)) 
    items[product] = input_num("And how much does {} cost? ".format(product)) 
subtotal = sum(items.values()) 
total = subtotal*1.09 

print "Your order was: " 
print "\n".join("{} ${}".format(i[0], i[1]) for i in items.items()) 
print "Your subtotal comes to ${}. With 9% sales tax, your total is ${}.".format(subtotal, total) 
print "I owe you back {}.\nThank you for shopping with us!".format(input_num("Please enter cash amount: ") - total) 

希望這有助於!如果您對如何/爲什麼我做了什麼有任何疑問,請詢問。

相關問題