Python 在split()函数的帮助下,下面的程序出现了什么错误?

Python 在split()函数的帮助下,下面的程序出现了什么错误?,python,Python,该程序基于以句子形式分隔用户给定的项目,并使用split()方法将其添加到列表中 total_list = [] billed_list = [] class Naveen: question = input('what would you like to buy : ') def shopping_cart(self,items): items = question.split() for item in items: print(

该程序基于以句子形式分隔用户给定的项目,并使用
split()
方法将其添加到列表中

total_list = []
billed_list = []

class Naveen:
  

  question = input('what would you like to buy : ')
  def shopping_cart(self,items):
      items = question.split()
      for item in items:
          print(item)
    

  def billed_items(self):
      for item in items:
          ask = input('do u really want '+ item+' ')
          if ask ==  'yes':
              billed_list.append(item)
          if ask == 'no':
              pass
      print(billed_list)
        
            
items = []
spacex = Naveen()
spacex.shopping_cart(items)

如果没有任何关于您的程序应该做什么的指示,就不明显有任何bug。但是如果我们假设你的程序是一个非常基本的购物车,它有以下问题

  • I/O可能应该在类外处理
  • 问题
    不应是全局类
  • 除了
    “yes”
    “no”
    之外,还应该定义输入的处理——要么将所有不是
    “yes”
    的输入视为
    “no”
    (这是您的代码当前所做的,但从外观上看,是错误的),要么循环直到收到
    “yes”
    “no”
    响应
  • 购物车中处理的项目应该封装到实例中,而不是全局变量中
  • 可能会尝试给类一个描述性的名称,而不是一个随机的名称
所以,也许是这样的

class ShoppingCart:
定义初始化(自):
self.items=[]
def购物车(自助、请求):
self.items=request.split()
def账单项目(自身):
账单=[]
对于self.items中的项目:
ask=input('您真的想要'+item+'吗?'))
如果ask==“是”:
账单追加(项目)
返回账单
spacex=购物车()
spacex.购物车(输入(“您想买什么?”)
to_pay=spacex.账单清单()
split()

carrot carrot turnip pepper

要生成
列表
['carrot'、'carrot'、'runip'、'pepper']
在问题前面添加self,您需要在split()函数中使用separator

请检查此解决方案代码:

total_list = []
billed_list = []

class Naveen:
  

  question = input('what would you like to buy : ')

  def shopping_cart(self,items):
        for item in items:
            total_list.append(item)
        print("Total List:", total_list)
    
    

  def billed_items(self, items):
      for item in items:
          ask = input('do u really want '+ item+': ')
          if ask ==  'yes':
              billed_list.append(item)
          if ask == 'no':
              pass
      print("Billed List:", billed_list)
        
            
items = []
spacex = Naveen()
items = spacex.question.split(',')
spacex.shopping_cart(items)
spacex.billed_items(items)
输入和输出示例:

what would you like to buy : Apple,Malta
Total List: ['Apple', 'Malta']
do u really want Apple: yes
do u really want Malta: no
Billed List: ['Apple']

是什么让您认为有错误?在类全局部分调用
input
显然很奇怪,而且可能是一个bug(但我们不知道您的需求是什么)。为什么我们在购物车函数中使用request?您是否在问类为什么不自己执行
input
?这使得它更加可重用。但是,
billed\u items
可能也应该避免做I/O。我想问的是,在这里请求作为参数有什么用?它只是一个变量名,如果你想的话,你可以称它为
naveen
(但随机名称对人类读者来说用处不大)。该变量包含来自用户的输入字符串(但我们不能将其称为
input
,因为这将使用相同的名称来隐藏内置项)。您将其称为
question
,但变量包含答案,而不是问题。但是
answer
对于一个函数来说是一个误导性的名称,它不一定从一个问题接收输入。我现在理解的是“变量请求用于分割我们给出的输入谢谢你的回答…它真的很有帮助。”