[Edu-sig] Pythonic "case statement"

kirby urner kirby.urner at gmail.com
Thu Jun 15 02:49:04 CEST 2006


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

Here's some fallout already:  a "bug" in my comment.  Should be 2,3 or 0.

But note how you can clump all this multi-line output in just one
print statement.  I've seen some newbies go print, print, print all
the way down the right side, avoiding this elegant solution.

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

A next thing to do with big print blocks is interpolate strings from a
dictionary.  Like with 8th graders I'll write a little story, leaving
out key nouns, verbs and adjectives.  Or they write the story...

"""
Once upon a time, some Swiss escaped to New Zealand to avoid
persecution by a dominant denomination (in their case, Catholics,
though this brand of Jesus freak was much outnumbered in other parts
of the world, and therefore likewise vulnerable to persecution by some
fanatical lot).
"""

Now we could replace Swiss, New Zealand, Catholics and Jesus with
%(keystring)s, like so:

>>> storytemplate = """
Once upon a time, some %(beleaguered people)s escaped to %(some
promised land)s to avoid persecution by a dominant denomination (in
their case, %(whatever nutcases)s, though this brand of %(so-called
followers)s was much outnumbered in other parts of the world, and
therefore likewise vulnerable to persecution by some fanatical lot).
"""

Then you could tell a whole different story this way:

>>> mystory = {'beleaguered people':'Cherokee' , 'some promised
land':'a godforsaken spot', 'whatever nutcases' : 'cowboy Anglos and
Euros with guns', 'so-called followers':'violent gun worshipper'}

Now the merge operation (string substitution, pulling from the dictionary):

>>> print storytemplate % mystory

Once upon a time, some Cherokee escaped to a godforsaken spot to avoid
persecution by a dominant denomination (in their case, cowboy Anglos
and Euros with guns, though this brand of violent gun worshipper was
much outnumbered in other parts of the world, and therefore likewise
vulnerable to persecution by some fanatical lot).

Doesn't ring quite true does it?  For one thing, I'm obviously not
Cherokee.  But I think you get the idea (of using dictionaries to
populate prekeyed blocks of text).

Kirby


More information about the Edu-sig mailing list