9

My code currently looks something like this:

if option1:
    ...
elif option2:
    ...
elif option3:
    ....

so on so forth. And while I'm not displeased with it, I was wondering if there was a better alternative in python. My script is a console based script where I'm using argparser to fetch for what the user needs.

Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144

3 Answers3

21

If 'option' can contain 'one', 'two', or 'three', you could do

def handle_one():
  do_stuff

def handle_two():
  do_stuff

def handle_three():
  do_stuff


{'one': handle_one, 
 'two': handle_two, 
 'three': handle_three}[option]()
Fredrik Håård
  • 2,856
  • 1
  • 24
  • 32
7

I'm guessing you're starting Python scripting with a background somewhere else, where a switch statement would solve your question. As that's not an option in Python, you're looking for another way to do things.

Without context, though, you can't really answer this question very well (there are far too many options).

I'll throw in one (somewhat Pythonic) alternative:

Let's start with an example of where I think you're coming from.

def add_to_x (x):
    if x == 3:
        x += 2
    elif x == 4:
        x += 4
    elif x == 5:
        x += 5
    return x

Here's my alternative:

def add_to_x (x):
    vals = { 3 : 5  ,  4 : 8  ,  5 : 10 }
    return vals[x]

You can also look into lambdas which you can put into the dictionary structure I used.

But again, as said, without context this may not be what you're looking for.

James Roseman
  • 1,614
  • 4
  • 18
  • 24
3

This is the first thing that comes to my mind:

Instead of doing this:

if option1:
    a = 1
elif oprtion2:
    a = 2
elif oprtion3:
    a = 3
else:
    a = 0

You can do this:

a = 1 if option1 else 2 if option 2 else 3 if option3 else 0

For more detail, see: PEP 308: Conditional Expressions!

nicolas.leblanc
  • 588
  • 7
  • 27