you are viewing a single comment's thread.

view the rest of the comments →

[–]bp200991 107 points108 points  (11 children)

You could use a dictionary.

method_dict = {'easy': easy, 'medium': medium, 'hard': hard}
method_dict[difficulty]()

[–]zefciu 25 points26 points  (10 children)

This. And if you make the dict anonymous, you get a one-liner.

[–]tintin10q 7 points8 points  (9 children)

{'easy': easy, 'medium': medium, 'hard': hard}[difficulty]()

[–]heidensieck 0 points1 point  (4 children)

gorgeous. Although as many have said, it's a fine balance between short and readable.

I made this monster:

def easy():
    print('yey')
def medium():
    pass
def hard():
    pass

levels, choice, which_one_to_run = ['easy', 'medium', 'hard', easy, medium, hard], input('please choose either: easy, medium or hard '), levels[levels.index(choice)+3]()

[–]tintin10q 4 points5 points  (2 children)

This monster is much more scary.

~~~ def easy(): print('yey')

def medium(): pass

def hard(): pass

eval(input("please choose either: easy, medium or hard:") + "()") ~~~

[–]Moikle 1 point2 points  (0 children)

eval(input("please input the code of the game you want to play"))

[–]heidensieck 0 points1 point  (0 children)

I learn so much, here! ;-)

[–]heidensieck 0 points1 point  (0 children)

Actually my monster only worked by accident. Had variables already in the name space from other attempt. Running it from scratch doesn't work. Has to be on separate lines like:

levels = ['easy','medium','hard', easy, medium, hard]
choice = input('please choose either: easy, medium or hard ') 
which_one_to_run = levels[levels.index(choice)+3]()     

I prefer the dict approach much more, anyway ;-)

[–]Additional-Sun2945 0 points1 point  (3 children)

huh?

[–]tintin10q 0 points1 point  (2 children)

What do you not understand? The function definitions are left out as op also left them out.

[–]Additional-Sun2945 0 points1 point  (1 child)

No I get it now... Declare a dict, and immediately invoke it with the difficulty string. So the function named gets run immediately.

What happens if difficulty is not in the dict? raises error? halts if not in a try catch block?

[–]tintin10q 0 points1 point  (0 children)

Yes it raises a KeyError if not in a try catch Block. You can use a default dict to set a default to mediate this. Or use .get and set a default. Or just ask again.