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 to refactor many ifs and else with different conditions in python?

I have many ifs and elses that assign a variable an X value. Does anyone have any idea how to try to improve this code?

I’ve searched for several ideas on the internet, but I haven’t found anything that would help me in this specific case.

date1 = ''
date2 = ''
name = ''

query = ''

if date1 and date2 and name:
    query = 'query 1'
elif date1 and date1:
    query = 'query 2'
elif date1 and name:
    query = 'query 3'
else:
    query = 'query default'

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 :

You can try mapping your input values to queries

# map (date1, date2, name) => query
query_map = {
    (date1, None, None): query1,
    (None, date2, None): query2,
    (date1, None, name): query3,
}

query = query_map.get((input_date1, input_date2, input_name), "default_query")
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