0

So I'm trying to see if "Sword" appears in inventory so I want it to trigger if like "Iron Sword" is in inventory or "Sword" in inventory. I've tried several ways to do this like the one below but doing the 4 space indent is a pain for every line.

inventory = ['blahblahh blah']
def code():
   if "Sword" in inventory:
   #blah blah code
4
  • Does inventory just contain one string or is it multiple string elements? Commented Dec 23, 2016 at 17:05
  • multiple string, in my code it starts a blank list thats appended as the player goes Commented Dec 23, 2016 at 17:13
  • Great, trincots answer is correct then. Commented Dec 23, 2016 at 17:17
  • 1
    Okay thanks for confirming. Commented Dec 23, 2016 at 17:21

1 Answer 1

1

As your inventory is a list, you need to iterate over it, and then do you check on the found element(s):

def code(needle, inventory):
    for elem in inventory:
        if needle in elem:
            #blah blah code
            break

code("Sword", ['blahblahh blah', 'some other', 'my Sword'])

As shown above, it is better to pass your values as arguments.

Sign up to request clarification or add additional context in comments.

3 Comments

Is elem just a placeholder name or does it hold some specific importance? I'm new to python and i don't really know if its like a special thing
It takes the value of the string inside inventory. If inventory has more than one string, elem will get the value of each of them: one per iteration. It is a normal variable.
You can use any name. elem is just an example, but doesn't have any special properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.