-1

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

balderman
  • 22,927
  • 7
  • 34
  • 52
  • Please explain - do you want to have specific logic for each state? Why? – balderman Sep 29 '21 at 20:45
  • Should be doable with a loop or something like that, what's the "block of code" look like? is it a separate block for each state or a general function? – Rashid 'Lee' Ibrahim Sep 29 '21 at 20:48
  • 2
    If the logic for each state is encapsulated in a separate function, you can create a dict mapping state codes to their functions, then run `for state in inp.split(", "): logic_dict[state]()` – koorkevani Sep 29 '21 at 20:48
  • 1
    Welcome to Stack Overflow! Please take the [tour] and read [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/4518341) What have you already tried? To start, do you know how to split the input into each code then loop over them? What do the blocks of code look like? For more tips, see [ask]. That said, ultimately you'll probably want to [use a dict of functions](/a/11479840/4518341). – wjandrea Sep 29 '21 at 20:55

2 Answers2

0

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')()
balderman
  • 22,927
  • 7
  • 34
  • 52
0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Sami Tahri
  • 1,077
  • 9
  • 19
  • The UK isn't a US state... nor is the US itself. It's easier if you just use the codes from the question: `'CA': handler_CA`, etc – wjandrea Sep 29 '21 at 20:59
  • 1
    `handler_UK()` -- those parens shouldn't be there. I fixed it for you. – wjandrea Sep 29 '21 at 21:00