简介:我正在尝试将购物清单代码放在一起。但是,每次我输入一个项目而不是将其存储在列表中时,我都会收到一条错误消息,指出未定义该项目。
shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""")
def add_to_list():
shopping_list.append(new_item)
print("Here is the item that it's been added {}. There are now {} items".format(new_item, len(shopping_list)))
def show_list():
index = 1
for index, item in shopping_list:
print("Here is the current shopping list: {}. {}".format(index,item))
index = index + 1
show_help()
while True:
new_item = input("> ")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
add_to_list()
show_list()
问题:为什么不将字符串存储到列表中?
答案 0 :(得分:0)
这是正确的,因为您没有将任何项目传递给add_to_list()
方法。
代码应类似于:
shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""")
def add_to_list(new_item):
shopping_list.append(new_item)
print("Here is the item that it's been added {}. There are now {} items".format(new_item, len(shopping_list)))
def show_list():
index = 1
for index, item in shopping_list:
print("Here is the current shopping list: {}. {}".format(index,item))
index = index + 1
show_help()
while True:
new_item = input("> ")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
add_to_list(new_item)
show_list()
答案 1 :(得分:0)
input()
解释 ,例如,如果用户是输入一个整数值,输入函数将返回该整数值。另一方面,如果用户输入列表,则该函数将返回列表。
如果您不将输入内容括在引号中,Python会将您的姓名作为变量。因此,错误消息很有意义!
为避免此错误,您必须将变量 input 转换为字符串。例如:“ ABC”
或者,您可以使用raw_input()
。 raw_input
不解释 。它总是返回用户的输入而未更改,即原始。可以将原始输入更改为算法所需的数据类型。
答案 2 :(得分:0)
您还误解了功能show_list
。这是在Python 3.7上进行的测试
shopping_list = []
def show_help():
print("What should we pick up at the store?")
print("""
Enter 'DONE' to stop adding items.
Enter 'HELP' for this help.
Enter 'SHOW' to see your current list.
""")
def add_to_list():
shopping_list.append(new_item)
print("Here is the item that it's been added {}. There are now {} items".format(new_item, len(shopping_list)))
def show_list():
for index, item in enumerate(shopping_list):
print("Here is the current shopping list: {}. {}".format(index, item))
show_help()
while True:
new_item = input("> ")
if new_item == 'DONE':
break
elif new_item == 'HELP':
show_help()
continue
elif new_item == 'SHOW':
show_list()
continue
add_to_list()
show_list()
答案 3 :(得分:-1)
根据给出的错误,我认为您可能正在使用Python 2.7,并且该错误是因为您使用的是input()
而不是raw_input()
。使用Python 3时,应使用input()
。
因此,将new_item = input("> ")
更改为new_item = raw_input("> ")
,这应该会停止您的错误。
但是,您的代码中也存在错误,您在show_list
函数中也打印了最终列表。除非您调用enumerate
,否则for循环只会遍历列表中的每个项目,除非它会循环遍历返回索引和项目。
这可能是您在该功能中需要的:
def show_list():
for index, item in enumerate(shopping_list):
print("Here is the current shopping list: {}. {}".format(index,item))