Home > Software engineering >  How do I identify if a variable is in a list?
How do I identify if a variable is in a list?

Time:10-23

How do I identify if a randomly selected variable is in a list? Python 3

Example:

WarriorList = ['Achilles', 'Sun Wukong']
GuardianList = ['Ares', 'Ymir']
HunterList = ['Apollo', Artemis']
MageList = ['Anubis', 'ra']

Tank = ()

def TankPick():
    Tank = (random.choice(WarriorList))
    print (Tank)

def BalancePick():
    if (Tank) in WarriorList:
        print ('yes')
        print (random.choice(Magelist))
    else:
        print ('no')
        print (random.choice(Hunterlist))

Expected outcome:

'Sun Wukong'
'yes'
'ra'

or

'Ymir'
'no'
'Artemis'

CodePudding user response:

How do I identify if a randomly selected variable is in a list? Python 3

Simple: x in y, where x is the element you want to check and y is your iterable of values.

There are some other problems with your code, though. You define two functions which are never called, neither one of which returns any value. You have a multiple Tank variables that won't work the way you seem to think they will. Those variables only live within the scope of their functions where they are defined. After the function finishes, the respective Tank variables are destroyed. The one you declare outside of the functions (in the "global scope") meanwhile is only once set to be an empty tuple and then never changed because, again, the other Tank variables are confined to their respective function scopes. If you absolutely must, you should declare them as global in the functions - or, even better yet, properly use them as function arguments and return values.

CodePudding user response:

I don't fully understand what the final product is that you're working to, but I went ahead and did the best I could!

import random
WarriorList = ['Achilles', 'Sun Wukong']
GuardianList = ['Ares', 'Ymir']
HunterList = ['Apollo', 'Artemis']
MageList = ['Anubis', 'ra']

class Container:
    def __init__(self):
        self.Tank = ()
    def TankPick(self):
        # Grabs a random name from all of the lists included
        self.Tank = (random.choice(WarriorList   GuardianList   HunterList   MageList))
        print (self.Tank)

    def BalancePick(self):
        if self.Tank in WarriorList:
            print ("yes\n"   random.choice(MageList))
            # \n is new line
        else:
            print ("no\n"   random.choice(HunterList))


cr = Container()
# Runs TankPick inside of Container
cr.TankPick()
# Runs BalancePick inside of Container after TankPick
cr.BalancePick()
  • Related