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

2024-06-10 22:01:16 发布

您现在位置: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()

Tags: orininputgetreturnvaluedefcounter
2条回答
while counter < quantity:

该行应更改为:

while counter < len(quantity):

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

改变

while counter < quantity

while counter < len(quantity)

相关问题 更多 >