0

I am working on a python hangman game and have my graphics based on a variable, lives, so when you have 1 lives, the corresponding picture appears. i put my graphics into definitions and want to call them from that. Here's my code so far:

if life== 1:
        graphics1()
 if life==2:
        graphics2()
 if life==3:
        graphics3()
 if life==4:
        graphics4()
 if life==5:
        graphics5()
 if life==6:
        graphics6()
 if life==7:
        graphics7()
 if life==8:
        graphics8()
 if life==9:
        graphics9()
 if life==10:
        graphics10()

and so on, so is there a command which would allow me to shorten this to one or two lines?

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 5
    how much `graphics1` differs from `graphics2` ? can't you make one `graphics()` function that takes `life` as an argument ? – Nir Alfasi Mar 09 '17 at 17:55
  • See the selected answer [here](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-via-a-while-loop) – juanpa.arrivillaga Mar 09 '17 at 18:04

2 Answers2

0

I highly discourage it, but it could be accomplished by doing:

globals()["graphics" + str(life)]()

However there's most definitely a better solution. Presuming that the contents of each graphics*() is similar to one another.

vallentin
  • 23,478
  • 6
  • 59
  • 81
0

Well, multiple if branches can be expressed via lookup table as

lt = {"1":graphics1(), "2":graphics2()}

and so on. Accès to if branch via (and provide a fallback function)

lt.get(life, graphics1())

If you want to create the dict dynamically use the dict comprehension and use the getattr to get the function. Or, as stated above, generalize the function graphics passing the "ith" param to it.

FrankBr
  • 886
  • 2
  • 16
  • 37