如何允许用户购买多件商品?

时间:2016-02-09 02:09:05

标签: python

我试图编写一个更复杂的程序代码程序版本,你是否已经编写了python课程计划的一部分。最初,您可以创建一个" shopping_list"在运行compute_bill()函数时用作参数。该功能本身会增加您选择的项目的价格,以便为您提供总额。但是,您无法选择任何项目中多个项目的数量。这就是我试图让程序能够做到的。

这是原始代码:

shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}

prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!

def compute_bill(food):
    total = 0 
    for x in food:
        if stock[x] > 0:
            total += prices[x]
            stock[x] -= 1
    return total

print compute_bill(shopping_list)

这将返回" 5.5"因为它增加了香蕉,橙子和苹果的价格。

这是我尝试编写的代码,询问用户他们想要的项目以及每个项目的数量:

import sys

print "use q as an input for any question to leave the program"

stock = {"orange": 15, "apple": 20, "pear": 14, "cigarettes": 18}

price = {"orange": 2.50, "apple": 2.65, "pear": 2.80, "cigarettes": 100}

for x in price:
    print [str(x)]
    print "Costs %r." % price[x]
    print "We have %r in stock." % stock[x]
    print "\n"*1



def run():
    q = "q"
    while True: #Asking the user what they want.
        try:
            items = raw_input("Enter what you'd like to buy >").split(", ") 
            if items == "q" or ['q']:
                return

            if isinstance(items,(int, long, float, complex))== True or \
            isinstance(items,stock[x])== False:
                print """Looks like you've entered an invalid format.
                Type the items you wish in list
                form: ["1","2","3",] naming products from the store"""

            if isinstance(items,stock[x])== True:
                items = food
                print "Great, now for the quantity!"
                break
            else:
                print "That's not a valid choice."
                continue
        except TypeError:
            print "Looks like you've entered an invalid format."        
            continue

    while True: #asking how much of the items
        try:
            quantity = raw_input("How many of each item do you want to buy?>").split(", ")
            if quanity == "q" or ['q']:
                return
            elif isinstance(quantity, str)== True:
                print "Looks like you've entered an invalid format."
                continue
            elif isinstance(quantity,str)== False and stock[x]== True:
                quantity = number
                print "Great, let's calculate your purchase now."
                break           
            else:
                print "That's not a valid choice."
                continue
        except TypeError:
            print "Looks like you've entered an invalid format."
            continue

if __name__ == "__main__":
    run()

def compute_bill(food,number): #calculate the bill
    total = 0
    for x in food:
        if isinstance(food, basestring)== True and stock[x] > 0 and number == 1:
            total = total+ price[x]
            stock[x] = stock[x]-1                       
            return total
        elif ValueError:
            print "Use a number for number!"    
        elif TypeError:
            print "Use a number for number!"

    for y in number:
        if isinstance(number, int)== True and stock[x] > 0 and number > 1:
            total+= number[y]*price[x]
            stock[x] = stock[x]-number[y]
            return total    
        elif stock[x] == 0:
            print "Sorry, sold out"
        else:
            print "Invalid choice. Please try again."

print "\n"*2

当我运行程序时,它会说"输入您想要购买的>",我输入" apple,cigarettes"没有引用,它只是退出程序。这是我第一次尝试编写程序,或者至少添加一个程序,因此它非常错误。有一次,我让它问下一个问题,但我可以说它没有做任何我想要的输入,因为程序无法给我任何数字答案。

2 个答案:

答案 0 :(得分:0)

首先从拆分项中删除所有空格。

同时使用terms.lower().split()确保大写字母不会导致错误。

此行中有错误

if isinstance(items,(int, long, float, complex))== True or \
        isinstance(items,stock[x])== False:

请注意,在函数运行中,您不定义x。当您尝试执行

时,这将导致失败
isinstance(items,stock[x])== False:

您不需要检查类型,尤其是因为items是从raw_input构建的,并且是字符串列表。您可以使用下面的代码测试项目的每个成员是否有库存。我仔细地将它作为一组独立的for循环,以便于阅读。您可以使用列表理解更有效地完成此操作。由于您没有库存中的数字或其他任何东西,因此您需要检查这些内容。

for ix in items:
    i = ix.strip() # remove leading and trailing blanks
    if i in stock:
        print "Item ", i, " has ", stock[i], "available."
    else:
        print "No items of ", i, " available"

如果某些东西没有库存,它将没有价格(使用price.get(i,0)使没有库存的东西的默认价格为0)。

请注意,这使用先前的方法来询问每个项目中的一个并从可用计数中减去一个。您可以询问每个项目的倍数。一种方法是使项目成为字典,其中请求的数字为值,项目名称为密钥。然后将相应的代码放入项循环中。

totprice = 0
# Note that items already used lower
for i in items:
    # Build the dictionaries with strip() to remove blanks
    avail = stock.get(i, 0) # This is a number
    each = price.get(i, 0) # this is a number
    req = items.get(i, 0).lower()  # this is a number
    if req > avail:
        print "Not enough items available, get ", avail
        req = avail
    total = req*each
    print "There are ", avail, "available of item", i
    print "Item ", i, "costs ",  each
    print req, " items requested"
    print "Total cost of item ", i, " is ", total
    totprice += total
    if avail > 0
        stock[i] -= req
print "Total price for all items is: ", totprice

如果没有特殊测试,这将自动跳过任何无效输入。

答案 1 :(得分:0)

您的问题出现在if items == "q" or ['q']声明中。这会评估items == "q"以及['q']。从那以后

>>> bool(['q'])
True
>>> 

您的if语句每次都会传递给return。相反,只需检查if items[0] == "q"