通过用户定义的关键字终止字典的多行键、值输入

2024-06-10 12:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,打破了从多行添加到字典。该任务需要将多行产品、数量输入添加到“Cart”字典中。对字典的添加应该以关键字“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\u reece所指出的,上面的代码永远不会显示\u 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()

代码现在起作用了。然而,我仍然想知道,如果使用而真的是一个python的方式做事情?你知道吗


Tags: nameselfaddinputif字典mydef