首页 > 解决方案 > 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()

标签: pythonpython-3.x

解决方案


改变

while counter < quantity

while counter < len(quantity)

推荐阅读