我遇到了从多行添加到字典的问题。该任务需要在“购物车”中添加多行产品,数量输入。字典。字典的添加应该通过关键字' show'来停止。或类似的东西,导致打印添加字典的元素。我已经能够启动购物车字典的多行输入,但无法通过“显示”来停止添加。关键字。
以下是我的代码的一部分供参考:
class cart():
pcart = {}
def __init__(self,name):
self.name = name
def Show_Cart(self):
print(self.pcart)
def Add_Item(self):
print('Adding your items and quantities')
p,q = input().rpartition(' ')[::2]
while q.lower() != 'show':
self.pcart[p] = q
if q.lower() == 'show':
self.Show_Cart()
My_Cart = cart(input('Name of your cart:'))
print('Choose from the following options:')
status = int(input('1:Add Item 2:Remove Item'))
if status == 1:
My_Cart.Add_Item()
编辑 - 正如@andrew_reece所指出的,上面的代码永远不会得到Show_Cart函数。然后我稍微调整一下并使用 While True 条件来循环执行函数操作并使用Else条件中断' Show'关键字出现。这是我的最终代码 -
class cart():
pcart = {}
def __init__(self,name):
self.name = name
def Show_Cart(self):
print(self.pcart)
Main()
def Add_Item(self):
print('Adding your items and quantities')
while True:
p,q = input().rpartition(' ')[::2]
if q.lower() != 'show':
self.pcart[p] = q
else:
self.Show_Cart()
break
def Remove_Item(self):
print('Your cart contents are :' ,self.pcart)
print('What all do you want to remove?')
while True:
p = input()
if p.lower() != 'show':
del self.pcart[p]
else:
self.Show_Cart()
break
def Main():
status = int(input('1:Add Item 2:Remove Item'))
if status == 1:
My_Cart.Add_Item()
elif status == 2:
My_Cart.Remove_Item()
My_Cart = cart(input('Name of your cart:'))
print('Choose from the following options:')
Main()
代码现在有效。但是我仍然想知道是否使用而True 是一种pythonic方法吗?