【问题标题】:How to make a grocery receipt program如何制作杂货收据程序
【发布时间】:2021-03-20 02:21:46
【问题描述】:

我对编程很陌生。

我的问题是我的 if 语句出现了 IndexError。因此,我将 if 语句放入另一个单元格并使用不同的列表进行了尝试,它工作正常。我做错了什么?

from datetime import datetime
import math
def GroceryReceipt():
    grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3], ["beef", 8]]
    amountGroceries = int(input("Input the amount of food you wish to buy: "))
    userGroc = []
    
    for i in range(amountGroceries):
        buyGroceries = input("Pick some foods: ")
        userGroc.append(buyGroceries)
        for j in range(len(grocery)):
            if(len(userGroc) < j):
                break
            else:
                print("$",grocery[j][1])
            
            if(userGroc[j] in grocery[j][0]):
                add = grocery[j][1] + grocery[j][1]
            tax = math.pi/100 * add
            total = tax + add
            round(total, 2)
            x = datetime.today()
            print(total, x)
            
GroceryReceipt()

【问题讨论】:

  • 请根据用户的相应输入分享一个您期望的输出示例。很难用for j 循环来判断您要完成什么。
  • 我正在尝试获取杂货清单中项目旁边的整数,即其成本。然后我想用进口数学加总和加税,还想打印购买的日期和时间。

标签: python-3.x function


【解决方案1】:

像这样使用“else”命令:

from datetime import datetime
import math
def GroceryReceipt():
    grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3]], ["beef", 8]
    amountGroceries = int(input("Input the amount of food you wish to buy: "))
    userGroc = []
    for i in range(amountGroceries):
       buyGroceries = input("Pick some foods: ")
       userGroc.append(buyGroceries)

        for j in range(len(grocery)):
            if(len(userGroc) < j):
                break
            else:                    # Use 'else' here
                print("$3")
GroceryReceipt()

如果 userGroc 的长度,您的 'if' 语句会中断循环 但即使它打破了循环,另一个“if”语句将是 执行,会出现索引错误。所以它更好地使用和 'else' 陈述,

else语句只有在'if'语句不满足要求时才会执行,否则'if'语句都会被执行。

【讨论】:

    【解决方案2】:

    作为程序员起步时的一大挑战是弄清楚如何拆分程序以降低代码中任何给定点的复杂性。另一个挑战是选择正确的数据结构以使您的任务更容易。这是考虑到这些问题的另一种想象解决问题的方法

    例子:

    from datetime import datetime
    import math
    
    in_stock = {
        "bread": 3.0,
        "eggs": 3.0,
        "soda": 7.0,
        "chips": 3.0,
        "beef": 8.0
    }
    
    def select_stock_item():
        stock_string = ", ".join([key for key in in_stock])
    
        while True:
            item = input(
                f"Please choose an item from available stock\n[{stock_string}]: "
            ).casefold()
    
            if not item in in_stock:
                print(f"I'm sorry, that item is not in stock.")
                continue
    
            return item, in_stock[item]
    
    
    def grocery_session():
        purchase_qty = int(input("How many items will you be purchasing today? "))
        purchases = []
        
        for _ in range(purchase_qty):
            purchases.append(select_stock_item())
    
        for one_purchase in purchases:
            purchase_subtotal = sum(one_purchase[1] for one_purchase in purchases)
        
        tax_on_purchase = purchase_subtotal * math.pi / 100
    
        purchase_total = purchase_subtotal + tax_on_purchase
    
        date_and_time = datetime.today().strftime("%m/%d/%y %H:%M")
    
        print("Thank you for your purchases.")
        print(f"You spent a total of ${round(purchase_total, 2)} on {date_and_time}")
        print("Please come again.")
    
    grocery_session()
    

    输出:

    How many items will you be purchasing today? 3
    Please choose an item from available stock
    [bread, eggs, soda, chips, beef]: soap
    I'm sorry, that item is not in stock.
    Please choose an item from available stock
    [bread, eggs, soda, chips, beef]: bread
    Please choose an item from available stock
    [bread, eggs, soda, chips, beef]: eggs
    Please choose an item from available stock
    [bread, eggs, soda, chips, beef]: soda
    Thank you for your purchases.
    You spent a total of $13.41 on 03/20/21 15:55
    Please come again.
    

    【讨论】:

      【解决方案3】:

      grocery = [["bread", 3], ["eggs", 3], ["soda", 7], ["chips", 3], ["beef", 8] 中您忘记添加另一个“]”。如果你添加它,它应该工作得很好。

      【讨论】:

      • 它仍然无法使列表索引超出范围
      猜你喜欢
      • 1970-01-01
      • 2017-06-20
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      相关资源
      最近更新 更多