Python 中杂货店购物程序中的错误



我是Python的新手,需要帮助我为编程课创建的程序。这是一个基本的杂货购物清单程序,要求杂货店名称、数量,并将它们存储在一个数组中。它还询问他们是否需要纸张或塑料。最后,应用程序应输出他们想要的杂货清单、数量以及他们选择的纸袋或塑料袋。但是,我收到以下错误,如果不修复它就无法继续:

Traceback (most recent call last):
line 164, in <module>
grocery_list()
line 159, in grocery_list 
total_quantity = calculate_total_groceries(quantity)
line 133, in calculate_total_groceries
while counter < quantity:
TypeError: '<' not supported between instances of 'int' and 'list'

以下是该程序的代码:

def get_string(prompt):
value = ""
value = input(prompt)
return value
def valid_real(value):
try:
float(value)
return True
except:
return False
def get_real(prompt):
value = ""
value = input(prompt)
while not valid_real(value):
print(value, "is not a number. Please provide a number.")
value = input(prompt)
return float(value)

def get_paper_or_plastic(prompt):
value = ""
value = input(prompt)
if value == "plastic" or value == "Plastic" or value == "paper" or value == "Paper":
return value
else:
print("That is not a valid bag type. Please choose paper or plastic")
value = input(prompt)
def y_or_n(prompt):
value = ""
value = input(prompt)
while True:
if value == "Y" or value == "y":
return False
elif value == "N" or value == "n":
return True
else:
print("Not a valid input. Please type Y or N")
value = input(prompt)
def get_groceries(grocery_name, quantity,paper_or_plastic):
done = False
counter = 0
while not done:
grocery_name[counter] = get_string("What grocery do you need today? ")
quantity[counter] = get_real("How much of that item do you need today?")
counter = counter + 1
done = y_or_n("Do you need anymore groceries (Y/N)?")
paper_or_plastic = get_paper_or_plastic("Do you want your groceries bagged in paper or plastic bags today?")
return counter
def calculate_total_groceries(quantity):
counter = 0
total_quantity = 0
while counter < quantity:
total_quantity = total_quantity + int(quantity[counter])
counter = counter + 1
return total_quantity
def grocery_list():
grocery_name = ["" for x in range (maximum_number_of_groceries)]
quantity = [0.0 for x in range (maximum_number_of_groceries)]
total_quantity = 0
paper_or_plastic = ""
get_groceries(grocery_name, quantity, paper_or_plastic)
total_quantity = calculate_total_groceries(quantity)

print ("Total number of groceries purchased is: ", total_quantity," and you have chosen a bage type of ", paper_or_plastic)
grocery_list()
while counter < quantity:

该行应更改为:

while counter < len(quantity):

因为您要将计数器与列表的长度进行比较,而不是与列表本身进行比较。

更改

while counter < quantity

while counter < len(quantity)

最新更新