Python: Use a variable when calling a definition -
this question has answer here:
i'm making game compsci class, , want shorten our random monster fights. there way make when call def can change name depending on random variable? snippet i'm talking
loop = true monstertype = random.randint(1,20) monster*() battle() i have
def monster1 def monster2 def monster3 . . . def monster20 i want * in first snippet variable monstertype, there way have that? i.e. when runs, if monstertype = 15, it'll monster13() that's called.
yes there way, create dictionary , map each function integer:
import random def monster1(): print "hello monster1" def monster2(): print "hello monster2" def monster3(): print "hello monster3" def monster4(): print "hello monster4" d = {1:monster1, 2:monster2, 3:monster3, 4:monster4} #when need call: monstertype = random.randint(1, 4) d[monstertype]()
Comments
Post a Comment