newbie: good reasons for learning Python?

Max M maxm at mxm.dk
Wed Jun 25 04:19:07 EDT 2003


Sean Ross wrote:

> Actually, I wasn't trying to make an alternative to that code, I was just
> trying to write something similar to the Ruby version I showed.
> But, while we're here:
> 
> # version of Fredrik Lundh's code at
> # http://99-bottles-of-beer.ls-la.net/p.html#Python
> # using dict.get() rather than try/except
> verse = """
> %(b1)s on the wall, %(b1)s,
> take one down, pass it around,
> %(b0)s on the wall.
> """
> 
> def bottle(n):
>     return {0: "no more bottles",
>                 1: "1 bottle"}.get(n, "%d bottles"%n) + " of beer"
> 
> for i in range(99, 0, -1):
>     b1, b0 = bottle(i), bottle(i-1)
>     print verse % locals()


Actually I find both that and frederiks version of the code overly complex.

This is a bit longer but should be more "pythonic" and far easier to 
understand:

verse = """
%(b1)s on the wall, %(b1)s,
take one down, pass it around,
%(b0)s on the wall.
"""

for i in range(99, 0, -1):
     bot_1 = '1 bottle of beer'
     bot_n = '%s bottles of beer'
     if i >= 2:
         b1 = bot_n % i
         b0 = bot_n % (i-1)
     if i == 2:
         b0 = bot_1
     if i == 1:
         b1 = bot_1
         b0 = bot_n % 'no more'
     print verse % locals()


regards Max M





More information about the Python-list mailing list