TypeError: can only concatenate list (not “str”) to list

后端 未结 5 620
情深已故
情深已故 2020-12-06 09:24

I am trying to make an inventory program to use in an RPG. The program needs to be able to add and remove things and then add them to a list. This is what I have so far:

5条回答
  •  既然无缘
    2020-12-06 09:47

    I think what you want to do is add a new item to your list, so you have change the line newinv=inventory+str(add) with this one:

    newinv = inventory.append(add)
    

    What you are doing now is trying to concatenate a list with a string which is an invalid operation in Python.

    However I think what you want is to add and delete items from a list, in that case your if/else block should be:

    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)
    

    You don't need to build a new inventory list every time you add a new item.

提交回复
热议问题