how can i simplify this code? is there a way to transform this into a for loop?

How can i simplify this code? Is there a way to transform this into a for loop?
I have tried some for loops but nothing works or is shorter than this and is more effective.

This is the code i want to optimize:

if selection == 1:
    function1
elif selection == 2:
    function2
elif selection == 3:
    function3
elif selection == 4:
    function4

>Solution :

It looks like you want to execute a different function based on the selection’s value. A nice way to do that is by having a dictionary with the values and the functions you want to call which acts as map between the selection and the function. For example:

functions = {'1': function1, '2': function2, '3': function3}

and then if execute the the function based on the selection:

functions[selection]()

And you can improve it a little by adding some error handling in case the key does not exist in the dictionary

Leave a Reply