我正在尝试制作一个用于RPG游戏的库存程序.该程序需要能够添加和删除内容并将其添加到列表中.这是我到目前为止:
inventory=["sword","potion","armour","bow"]
print(inventory)
print("\ncommands: use (remove) and pickup (add)")
selection=input("choose a command [use/pickup]")
if selection=="use":
print(inventory)
remove=input("What do you want to use? ")
inventory.remove(remove)
print(inventory)
elif selection=="pickup":
print(inventory)
add=input("What do you want to pickup? ")
newinv=inventory+str(add)
print(newinv)
Run Code Online (Sandbox Code Playgroud)
当我运行它并尝试选择一些东西时,我收到此错误:
Traceback (most recent call last):
File "H:/Year 10/Computing/A453/Python Programs/inventory.py", line 15, in <module>
newinv=inventory+str(add)
TypeError: can only concatenate list (not "str") to list
Run Code Online (Sandbox Code Playgroud)
有没有人对此有所解决,将不胜感激
jab*_*edo 17
我想你想要做的是在列表中添加一个新项目,所以你改变了这一行newinv=inventory+str(add):
newinv = inventory.append(add)
Run Code Online (Sandbox Code Playgroud)
你现在正在做的是尝试用一个字符串连接一个列表,这是Python中的一个无效操作.
但是我认为你想要的是添加和删除列表中的项目,在这种情况下你的if/else块应该是:
if selection=="use":
print(inventory)
remove=input("What do you want to use? ")
inventory.remove(remove)
print(inventory)
elif selection=="pickup":
print(inventory)
add=input("What do you want to pickup? ")
inventory.append(add)
print(inventory)
Run Code Online (Sandbox Code Playgroud)
每次添加新项目时都不需要构建新的库存清单.