Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading