python - 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)
推荐阅读
- twitter - 哪些模式/规则用于搜索推文?
- rust - Rust 横梁范围线程异步运行?
- c - 用于检查回文字符串的 C 程序
- wireguard - WireGuard:无法 ping 任何东西,握手成功时流量不通过
- node.js - 更新所有包时如何解决 NPM 上的“无法解析依赖树”?
- python - 如何通过 Python 数据类中的 kwargs 存储额外的属性
- xgboost - 使用 xgboost 预测 100 棵树与 1000 棵树所花费的时间相同
- java - Spring Boot socket-io-client v1 不会使用 ssl 发送到 socket.io 服务器
- rust - 如何在可变引用中获取、转换和替换向量?
- mysql-python - 注册检查Mysql和Python