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
对于一个函数来说是一个误导性的名称,它不一定从一个问题接收输入。我现在理解的是“变量请求用于分割我们给出的输入谢谢你的回答…它真的很有帮助。”