如何将输入添加到空列表并保存它?

How to add inputs to an empty list and keep it stored?

我正在尝试为游戏中的项目创建一个列表,但我必须在我的程序中多次调用它。我注意到输入没有存储在我的列表中,它每次都会替换它。

我使用了 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'] 
def addbackpack(playeritems):
    gameitems= ["sword", "potion"]
    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(playeritems)
playeritems = []
addbackpack(playeritems)
print (playeritems)
addbackpack(playeritems)
print (playeritems)
  • 您每次进行函数调用时都在重新初始化播放器项目。而只是将列表传递给函数调用。

PS :我建议不要使用递归。相反,您可以采用这种迭代方式。

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)

确实 工作(因为每个新项目都会被添加),但是每次调用 addbackpack 都会重新初始化 playeritems,删除所有已经以前去过