python-3.x - 如何制作杂货收据程序

标签 python-3.x function

我对编程还很陌生。

我的问题是我的 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()

最佳答案

像这样使用“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()

your 'if' statement breaks the loop if the length of userGroc < j; but even though it breaks the loop the other 'if' statement will be executed, and the index error will occur. so its better to use and 'else' statements,

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

关于python-3.x - 如何制作杂货收据程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66717673/

相关文章:

function - 有没有办法为 NavigationLink 添加额外的功能? swift 用户界面

c# - 在 python 中使用 key 应用 HMAC SHA-512 算法

python-3.x - 太空侵略者 bug pygame

python - 更新 panda 中的整个 Excel 行

c - c中的嵌套函数?

javascript - 如何使用 requireJS 从另一个文件调用函数

python - 将 PNG 图像编码为 Base64 时出现 AttributeError

python - 将 DataFrame 的结果输出到 QLabel

c - 在C中,Print语句没有在for循环中打印

javascript - 将方法动态链接到 javascript 函数