Home > Back-end >  Logic to execute one or multiple block of code based on the criteria
Logic to execute one or multiple block of code based on the criteria

Time:09-30

Instead of writing many if else statements I'm thinking someone smart may have a better logic for this.

inp = input("Type comma separated US state code(s)")

Logic to execute a block of code if inp is "MA". If inp is "MA, CA, MN" it will execute a block of code under MA, CA, and MN.

You can imagine inp could be 1 state or any combination of 50 states. Logic would execute a block of code written for each state

Writing program in python

CodePudding user response:

Logic would execute a block of code written for each state

The below should work for you. The idea is to call the function by its name and it is based on a strict naming convention: <state>_func

import sys
mod = sys.modules[__name__]
states = [s.lower() for s in input("Type comma separated US state code(s)").split(',')]


def ma_func():
    print('MA')

def ca_func():
    print('CA')
    
for state in states:
    getattr(mod,f'{state}_func')()

CodePudding user response:

You're basically doing some sort of switch/case, with a loop over an array of element.

You can do something like that in python :

def handler_US():
    ... do something ...
def handler_UK():
    ... do something else ...

handlers = {
            'US': handler_US, 
            'UK': handler_UK
            }
codes_str = input("Type comma separated US state code(s)")
codes = codes_str.split(',')
for code in codes:
    handlers[code]()

You can also use .get() on the handler dictionary to use a default handler when the value is not recognized.

  • Related