过去四天我一直在研究python问题,当我运行代码时,我一直遇到一个小问题。我得到的错误如下:
追踪(最近一次通话): 文件" cuddy_m_chap10_7.py",第163行,in 主要() 文件" cuddy_m_chap10_7.py",第121行,在main中 cr1.clear(R3) 文件" cuddy_m_chap10_7.py",第48行,清楚 自.__ list_item.remove(r)的 ValueError:list.remove(x):x不在列表中
现在,我已经研究过这个问题,但找不到任何有帮助我的东西。首先,我有一个简单的程序,有三个对象,代表衣服。我有一个收银机类,这里有一些方法:
def __init__(self):
self.__list_item = []
def purchase_item(self, r):
self.__list_item.append(r)
def clear(self, r):
for item in self.__list_item:
self.__list_item.remove(r)
当程序运行时,用户可以将衣服添加到购物车或取出衣服。现在,如果我添加两件衣服,我可以使用透明方法并取出一件。但是,如果我在购物车中有三件衣服,则会收到追溯错误。所以,购物车中的2件商品,一切正常,三件或更多件我得到了我的错误。这里的代码是一些主要的功能代码:
#Creating the objects from the class
r1 = RetailItem('Jacket', 12, 59.95)
r2 = RetailItem('Designer Jeans', 40, 34.95)
r3 = RetailItem('Shirt', 20, 24.95)
#creating cash register object
cr1 = CashRegister()
print("Listing All Items:")
print('ITEM', '\t', '\t', '\t', 'PRICE')
print(r1.get_desc(), '\t', '\t', '\t', r1.get_price())
print(r2.get_desc(), '\t', '\t', r2.get_price())
print(r3.get_desc(), '\t', '\t', '\t', r3.get_price())
#Asking the user which items they want to buy
ch = 'y'
while ch.upper() == 'Y':
print()
print("Please enter the name of the item to be purchased")
item = input('Name: ')
if item.upper() == r1.get_desc().upper():
cr1.purchase_item(r1)
elif item.upper() == r2.get_desc().upper():
cr1.purchase_item(r2)
elif item.upper() == r3.get_desc().upper():
cr1.purchase_item(r3)
ch = input('Select another item: (y/n): ')
#Displaying a list of the items which have been placed in the cart
print()
print("The list of the items you have in your cart are as follows: ")
print(cr1.show_items())
print()
remove = input("Do you want to remove an item? (y/n) ")
while remove.lower() == 'y':
if remove.lower() == 'y':
print("Please enter the name of the item you want to be remove: ")
name = input('Item: ')
if name.upper() == r1.get_desc().upper():
cr1.clear(r1)
print("The", r1.get_desc(), "has been removed!")
elif name.upper() == r2.get_desc().upper():
cr1.clear(r2)
print("The", r2.get_desc(), "has been removed!")
elif name.upper() == r3.get_desc().upper():
cr1.clear(r3)
print("The", r3.get_desc(), "has been removed!")
remove = input("Do you want to remove an item? (y/n) ")
任何有关我的程序为何与购物车中的2件物品配合使用而不是3件物品的帮助将不胜感激!谢谢
答案 0 :(得分:0)
您不应该在所有中使用for
循环。只需删除该项:
def clear(self, r):
self.__list_item.remove(r)
您尝试从列表中删除r
的次数与列表中的总项目数相同..