[Edu-sig] Pythonic "case statement"

kirby urner kirby.urner at gmail.com
Thu Jun 15 02:25:26 CEST 2006


Hi Bernie --

Pythoneers (or Pythonistas as some say -- snake charmers) do have a
case statement of sorts, thanks to functions (subprocedures) being top
level.

What does that mean?

It means we can pass a function around like a variable, list it, put
it in a dictionary, whatever we can do with most any Python object.

For example:

==== casestructure.py ====

def f():
	x = float(raw_input("What number? "))
	return x**2  # 2nd powering

def g():
	x = float(raw_input("What number? "))
	return x**3  # 3rd powering

"""
>>> g()
What number? 10
1000.0

Then:
"""

switch = [None, None, f, g]  # a list.  Note: switch[2] would be f.

looping = True

while looping:

   """
   Show menu, get user input, 0,1 or 2
   """

   print """
2. Square a number
3. Cube a number
0. Exit
"""

   usersays = raw_input("Choice? ")

   if usersays == '0':
        looping = False

   else:
        try:
            assert usersays in ['2','3']
            usersays = int(usersays)
        except:
            print "Enter 2,3 or 0"
            continue

        mychoice = switch[usersays]  # in essence, a switch or case statement

	output = mychoice()  # call whichever function was selected

	print output

==== casestructure.py ====

Of course that's not very many choices (just two), but it illustrates
using a list of functions, and a numeric index, to do one of those
loopy menu programs people used to do, pre the dawn of the
event-driven GUI app.

I'm also showing some other charming snake tricks.

Kirby

Cc:  edu-sig (where we debate about ways to teach Python to busy
science professionals such as yourself).  You may get some follow-up
traffic, we hope on topic.


More information about the Edu-sig mailing list