Python 如何将输入添加到空列表并保存它?
我正在尝试为游戏中的项目制作一个列表,我必须在我的程序中多次调用它。我注意到输入并没有存储在我的列表中,它每次都会替换它 我使用了Python 如何将输入添加到空列表并保存它?,python,list,function,append,storage,Python,List,Function,Append,Storage,我正在尝试为游戏中的项目制作一个列表,我必须在我的程序中多次调用它。我注意到输入并没有存储在我的列表中,它每次都会替换它 我使用了playeritems.append()和playeritems.extend(),但它不起作用 def addbackpack(): global playeritems gameitems= ["sword", "potion"] playeritems = [] print ("\nWhat would you like to a
playeritems.append()
和playeritems.extend()
,但它不起作用
def addbackpack():
global playeritems
gameitems= ["sword", "potion"]
playeritems = []
print ("\nWhat would you like to add to your backpack? The sword or potion?\n")
p1_additem = str(input())
if p1_additem in gameitems:
playeritems.append(p1_additem)
print ("\nYou added",p1_additem,"to your backpack.\n")
else:
print ("\nThat is not a choice!\n")
return addbackpack()
addbackpack()
print (playeritems)
addbackpack()
print (playeritems)
这是我第一次输入剑,第二次输入药剂后的准确结果:
What would you like to add to your backpack? The sword or potion?
sword
You added sword to your backpack
['sword']
What would you like to add to your backpack? The sword or potion?
potion
You added potion to your backpack
['potion']
- 每次进行函数调用时,您都在重新初始化playeritems。相反,只需将列表传递给函数调用
def addbackpack():
gameitems= ["sword", "potion"]
print ("\nWhat would you like to add to your backpack? The sword or potion?\n")
p1_additem = str(input())
# read until player input correct item.
while p1_additem not in gameitems:
print ("\nThat is not a choice!\n")
p1_additem = str(input())
playeritems.append(p1_additem)
print ("\nYou added",p1_additem,"to your backpack.\n")
playeritems = []
addbackpack()
print (playeritems)
addbackpack()
print (playeritems)
它确实起作用(因为每个新项都会被添加),但是每次调用
addbackack
都会重新初始化playeritems
,删除之前的所有内容。不要使用递归调用,只需在函数中使用循环,然后返回列表。每次调用addbackack()
时,都会重置playeritems
的值。您需要将playeritems
的当前值传递给addbackack(playeritems)
,以保留当前项目和新项目。@Jean Françoisfare谢谢,我还编写了迭代方法供考虑。
def addbackpack():
gameitems= ["sword", "potion"]
print ("\nWhat would you like to add to your backpack? The sword or potion?\n")
p1_additem = str(input())
# read until player input correct item.
while p1_additem not in gameitems:
print ("\nThat is not a choice!\n")
p1_additem = str(input())
playeritems.append(p1_additem)
print ("\nYou added",p1_additem,"to your backpack.\n")
playeritems = []
addbackpack()
print (playeritems)
addbackpack()
print (playeritems)