我试着为游戏中的项目建立一个列表,我不得不在我的程序中多次调用它。我注意到输入并没有存储在我的列表中,它每次都会替换它。你知道吗
我使用了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']
PS:我建议不要使用递归。相反,你可以这样迭代。你知道吗
它确实可以工作(因为每个新项都会被添加),但是每次对
addbackpack
的调用都会重新初始化playeritems
,删除之前在那里的所有内容。你知道吗相关问题 更多 >
编程相关推荐