1

So I can do a Select Case in python with

if integer == 1:
  case0()
elif integer == 2:
  case2()
elif integer == 3:
  case3()
....
elif integer == N:
  caseN()

Some times I use a list using the index as a selector.

selectCase = [case0(),case1(),case3(),...,caseN()] [N]

But this makes that each item in the list to be processed before selected right?

So I was wondering if there other ways to do this without spanning so much vertically to control what code is executed. Are there maybe ways to jump to parts of the code? Maybe I don't want to solve a function but just skip some lines.

Thanks

probiner
  • 91
  • 9

1 Answers1

3

One way is to take advantage of the fact that you can store functions in dictionaries:

functions = {
    1: case1,
    2: case2,
    ...
}

functions[case]() 

Notice I'm not using the parenthesis in the dictionary. In your example in the list you would storing the result of the function not the function itself.

kylieCatt
  • 10,672
  • 5
  • 43
  • 51
  • 1
    for sequential numbers starting at 0 or 1, just use a list. For starting at 1, insert a `None` at the start to cover `0`. – Martijn Pieters Aug 18 '15 at 13:14
  • I was just using arbitrary numbers, I'm not sure if the OP's use case is actually that simple. – kylieCatt Aug 18 '15 at 13:15
  • From the queston: *Some times I use a list using the index as a selector* – Martijn Pieters Aug 18 '15 at 13:16
  • This is a good solution. Only issue is if each function needs different arguments, so I would need something like: [HERE](http://repl.it/BCwN) Since I was basically trying to select which code runs like you do with elifs. As long as the arguments are calculated variables, this only takes the extra time to build the lists versus elifs, I think. – probiner Aug 21 '15 at 06:20
  • @IanAuld Indeed I was trying to do flow control – probiner Aug 21 '15 at 06:23
  • By the way is [option1, option2][condition] a good practice? Thanks – probiner Sep 16 '15 at 12:12