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

2024-06-16 10:53:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着为游戏中的项目建立一个列表,我不得不在我的程序中多次调用它。我注意到输入并没有存储在我的列表中,它每次都会替换它。你知道吗

我使用了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'] 

Tags: thetoyouaddyourlikeprintp1
2条回答
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)
  • 每次进行函数调用时都要重新初始化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,删除之前在那里的所有内容。你知道吗

相关问题 更多 >