gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:36:53 27 4
gpt4 key购买 nike

我对编程还很陌生。

我的问题是我的 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 beexecuted, 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com