0

Possible Duplicate:
Replacements for switch statement in python?

Given this method :

def getIndex(index):
    if((index) < 10):
        return 5
    elif(index < 100):
        return 4
    elif(index < 1000):
        return 3
    elif(index < 10000):
        return 2
    elif(index < 100000):
        return 1
    elif(index < 1000000):
        return 0

I want to make it in a switch-case style , however , Python doesn't support switch case .

Any replacements for that ?

Community
  • 1
  • 1
JAN
  • 21,236
  • 66
  • 181
  • 318
  • 1
    http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python - Check this out! :) – Henrik Andersson Jan 01 '13 at 20:51
  • You can use `if` instead of `elif` everywhere in this code. – Lev Levitsky Jan 01 '13 at 20:51
  • The reason Python doesn't have `switch` is that it's really, internally, exactly like your series of `elif` statements. Using the `elif` is essentially the same and more obvious what the logic is. It is already the preferred syntax for Python. There is no reason to change it. – Keith Jan 01 '13 at 20:56
  • See answers to the question [switch case in python doesn't work; need another pattern](http://stackoverflow.com/questions/3886641/switch-case-in-python-doesnt-work-need-another-pattern). – martineau Jan 02 '13 at 00:53

3 Answers3

3

what about 6-len(str(index))?

gefei
  • 18,922
  • 9
  • 50
  • 67
3

the classic pythonic way is to use a dictionary where the keys are your tests and the values are callable functions that reflect what you intend to do:

def do_a():
    print "did a"

self do_b():
    print " did b"

#... etc

opts = {1:do_a, 2:do_b}

if value in opts: 
    opts[value]()
else:
    do_some_default()
theodox
  • 12,028
  • 3
  • 23
  • 36
2

In this particular instance I would just use maths:

def get_index(index):
    return 6 - int(round(math.log(index, 10)))

You have to use the built-in function round as math.log returns a float.

Ben
  • 51,770
  • 36
  • 127
  • 149