There's a function that repeatedly shows up in languages, usually with more or less the following form (Python syntax):

var1 = raw_input("Input a number between one and three.")

choose var1:
   case "1":
      print "You inputted one."
   case "2":
      print "You inputted two."
   case "3":
      print "You inputted three."

Or something like that. I've also seen it called "switch." Does Python have anything like this?

In Python you can set up a dictionary to mimic switch/case ...

def choose(s):
    return {
    '1' : lambda:"You inputted one.",
    '2' : lambda:"You inputted two.",
    '3' : lambda:"You inputted three."
    }[s]()

var1 = raw_input("Input a number between one and three.")
print choose(var1)

Even in C the switch/case statement is not as efficient as multiple if/elif statements, so Python did not implement it.

Actually, in this case you don't need lambda, since you are only returning a string. Please shorten the code to ...

def choose(s):
    return {
    '1' : "You inputted one.",
    '2' : "You inputted two.",
    '3' : "You inputted three."
    }[s]

var1 = raw_input("Input a number between one and three.")
print choose(var1)

Mildy more elegant ...

def choose(s):
    return "You entered " + {
    '1' : "one",
    '2' : "two",
    '3' : "three"
    }[s]

var1 = raw_input("Input a number between one and three: ")
print choose(var1)

I'm going to feel really stupid when I see the answer to my question, because I'm sure I've seen it before and I've just forgotten. Anyway, I was just fiddling with this example, and I can't remember how to add a default case. In the example given I want to return the text "Bad input" for any value other than 1, 2, or 3. What do I need to add to the dictionary?

The standard try/except way would be:

def choose(s):
    try:
        return "You entered " + {
        '1' : "one",
        '2' : "two",
        '3' : "three"
        }[s]
    except:
        return "Bad input"

var1 = raw_input("Input a number between one and three: ")
print choose(var1)

Or straight foreward with dictionary method get():

def choose2(s):
    return "You entered " + {
    '1' : "one",
    '2' : "two",
    '3' : "three"
    }.get(s, "a bad number")

var1 = raw_input("Input a number between one and three: ")
print choose2(var1)

This is closer to the switch/case default.

This question has already been answered. Start a new discussion instead.