Google Groups Home
Help | Sign in
ten small Python programs
There are currently too many topics in this group that display first. To make this topic appear first, remove this option from another topic.
There was an error processing your request. Please try again.
flag
  Messages 1 - 25 of 44 - Collapse all   Newer >
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
Steve Howell  
View profile
(3 users)  More options May 27 2007, 4:43 am
Newsgroups: comp.lang.python
From: Steve Howell <showel...@yahoo.com>
Date: Sat, 26 May 2007 11:43:25 -0700 (PDT)
Local: Sun, May 27 2007 4:43 am
Subject: ten small Python programs
I've always thought that the best way to introduce new
programmers to Python is to show them small code
examples.  

When you go to the tutorial, though, you have to wade
through quite a bit of English before seeing any
Python examples.

Below is my attempt at generating ten fairly simple,
representative Python programs that expose new users
to most basic concepts, as well as the overall syntax.

It was an interesting exercise.  I constrained myself
to ten lines or less, and it was pretty easy to
incorporate loops, conditionals, print, open(), lists,
tuples, dictionaries, and imported modules.  

It was harder to show classes, and my ShoppingCart
class is nothing more than an encapsulation of a list,
which has dubious value (although it's the start of
something more useful).

Anyway, here goes:

    ------
    print 'hello world'

    ------
    for name in ('peter', 'paul', 'mary'):
        print name

    ------
    # This is a Python comment. \n is a newline
    name = raw_input('What is your name?\n')
    print 'Hi', name

    ------
    parentRabbits, babyRabbits = (1, 1)
    while babyRabbits < 100:
        print 'This generation has %d rabbits' %
babyRabbits
        parentRabbits, babyRabbits = (babyRabbits,
parentRabbits + babyRabbits)

    ------
    # def defines a method in Python
    def tax(itemCharge, taxRate = 0.05):
        return itemCharge * taxRate
    print '%.2f' % tax(11.35)
    print '%.2f' % tax(40.00, 0.08)

    ------
    import re
    for test_string in [ '555-1212', 'ILL-EGAL']:
        if re.match('\d\d\d-\d\d\d\d$', test_string):
            print test_string, 'is a valid US local
phone number'
        else:
            print test_string, 'rejected'

    ------
    prices = {'apple': 0.40, 'banana': 0.50}
    myPurchase = {
        'apple': 1,
        'banana': 6}
    groceryBill = sum([prices[fruit] *
myPurchase[fruit]
        for fruit in myPurchase])
    print 'I owe the grocer $%.2f' % groceryBill

    ------
    class ShoppingCart:
        def __init__(self): self.items = []
        def buy(self, item): self.items.append(item)
        def boughtItems(self): return self.items
    myCart = ShoppingCart()
    myCart.buy('apple')
    myCart.buy('banana')
    print myCart.boughtItems()

    ------
    # indent your Python code to put into an email
    import glob
    pythonFiles = glob.glob('*.py')
    pythonFiles.sort()
    for fn in pythonFiles:
        print '    ------'
        for line in open(fn):
            print '    ' + line.rstrip()
        print

    ------
    import time
    now = time.localtime()
    hour = now.tm_hour
    if hour < 8: print 'sleeping'
    elif hour < 9: print 'commuting'
    elif hour < 17: print 'working'
    elif hour < 18: print 'commuting'
    elif hour < 20: print 'eating'
    elif hour < 22: print 'resting'
    else: print 'sleeping'

___________________________________________________________________________ _________
Expecting? Get great news right away with email Auto-Check.
Try the Yahoo! Mail Beta.
http://advision.webevents.yahoo.com/mailbeta/newmail_tools.html


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
John K Masters  
View profile
 More options May 27 2007, 5:15 am
Newsgroups: comp.lang.python
From: John K Masters <johnmast...@oxtedonline.net>
Date: Sat, 26 May 2007 20:15:16 +0100
Local: Sun, May 27 2007 5:15 am
Subject: Re: ten small Python programs
On 11:43 Sat 26 May     , Steve Howell wrote:

Many thanks for that. This is exactly what is missing in most introductory
books. Simple, relevant and concise examples.

Regards, John
--
War is God's way of teaching Americans geography
Ambrose Bierce (1842 - 1914)


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steven Bethard  
View profile
 More options May 27 2007, 5:38 am
Newsgroups: comp.lang.python
From: Steven Bethard <steven.beth...@gmail.com>
Date: Sat, 26 May 2007 13:38:44 -0600
Local: Sun, May 27 2007 5:38 am
Subject: Re: ten small Python programs

Steve Howell wrote:
> I've always thought that the best way to introduce new
> programmers to Python is to show them small code
> examples.  

> When you go to the tutorial, though, you have to wade
> through quite a bit of English before seeing any
> Python examples.

> Below is my attempt at generating ten fairly simple,
> representative Python programs that expose new users
> to most basic concepts, as well as the overall syntax.

Very cool! Do you mind putting this up on the Wiki somewhere so that we
can link to it more easily? Maybe something like:

     http://wiki.python.org/moin/SimplePrograms

<nitpick>
Though the code should probably follow PEP 8 guidelines, e.g.
under_scores instead of camelCase for object and method names:

     http://www.python.org/dev/peps/pep-0008/
</nitpick>

>     class ShoppingCart:
>         def __init__(self): self.items = []
>         def buy(self, item): self.items.append(item)
>         def boughtItems(self): return self.items
>     myCart = ShoppingCart()
>     myCart.buy('apple')
>     myCart.buy('banana')
>     print myCart.boughtItems()

I think boughtItems() is probably not a good example of Python code
since in this case, you should probably just write ``my_cart.items``.
Maybe it should define ``__len__`` instead? Or maybe something like::

     def select_items(self, prefix):
         return [item for item in self.items if item.startswith(prefix)]

STeVe


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steve Howell  
View profile
 More options May 27 2007, 6:05 am
Newsgroups: comp.lang.python
From: Steve Howell <showel...@yahoo.com>
Date: Sat, 26 May 2007 13:05:02 -0700 (PDT)
Local: Sun, May 27 2007 6:05 am
Subject: Re: ten small Python programs

--- Steven Bethard <steven.beth...@gmail.com> wrote:

> Very cool! Do you mind putting this up on the Wiki
> somewhere so that we
> can link to it more easily? Maybe something like:

>      http://wiki.python.org/moin/SimplePrograms

Done.

> <nitpick>
> Though the code should probably follow PEP 8
> guidelines, e.g.
> under_scores instead of camelCase for object and
> method names:

>      http://www.python.org/dev/peps/pep-0008/
> </nitpick>

I think I fixed them, please see Wiki to verify.

I think the problem here is that it's hard to write a
useful class in less than 10 lines of code.  Can
somebody else give it a try?

Although I didn't call it out in the email, I tried to
make each program progressively one line longer, so if
somebody wants to write, say, an 11-line class
example, then I will try fill in the gap with another
8-liner.

Did I miss any basic concepts in the first 10
programs?  Maybe an 8-liner could demonstrate command
line arguments?

___________________________________________________________________________ _________Yahoo! oneSearch: Finally, mobile search
that gives answers, not web links.
http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Paul McGuire  
View profile
 More options May 27 2007, 11:23 am
Newsgroups: comp.lang.python
From: Paul McGuire <pt...@austin.rr.com>
Date: 26 May 2007 18:23:39 -0700
Local: Sun, May 27 2007 11:23 am
Subject: Re: ten small Python programs
I ***love*** this "10 Little Programs" idea!  As soon as I get a
breathing space, I'm going to add a "10 Little Parsers" page to the
pyparsing wiki!

On May 26, 2:38 pm, Steven Bethard <steven.beth...@gmail.com> wrote:

> <nitpick>
> Though the code should probably follow PEP 8 guidelines, e.g.
> under_scores instead of camelCase for object and method names:

>      http://www.python.org/dev/peps/pep-0008/
> </nitpick>

Really?  Underscore-separated words preferred over camel case?  What
is the rationale for this?  This style is so retro/80's/C-ish.  It
seems more like a Java backlash to me than anything else.  If we (or
Guido) don't like changing case to indicate word breaks, why are class
names to be UpperCamelCase, and not Capitalized_with_underscores?  If
there is a casing convention nit to pick, I'd focus on UpperCamelCase
for class names, lower case (either with underscores or mixed case)
for attributes and method names, and UNDERSCORE_SEPARATED_ALL_CAPS for
constants.

If we want to just say "well, PEP-8 says such and such," I think this
is an area where the thinking has possibly evolved since 2001.  Also,
I think the PEP would benefit from explicitly discouraging some
practices, such as Hungarian notation.

> >     class ShoppingCart:
> >         def __init__(self): self.items = []
> >         def buy(self, item): self.items.append(item)
> >         def boughtItems(self): return self.items
> >     myCart = ShoppingCart()
> >     myCart.buy('apple')
> >     myCart.buy('banana')
> >     print myCart.boughtItems()

If you want to nitpick, I'd rather go after the one-liner methods with
the body on the same line as the def statement.

How's this for a better non-trivial method example:

    MAX_ITEMS_FOR_EXPRESS_LANE = 10
    def canUseExpressLane(self):
        return (len(self.items) <= MAX_ITEMS_FOR_EXPRESS_LANE)

or call it "can_use_express_lane" if you must.

I guess pyparsing with its mixedCase functions and attributes is
doomed for the Dunce Corner.  Too bad for BeautifulSoup, cElementTree,
and wxPython that are also at variance with this canon of Python
coding style. ("Modules should have short, all-lowercase names. ...
Python packages should also have short, all-lowercase names, although
the use of underscores is discouraged.")

-- Paul


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steve Holden  
View profile
 More options May 27 2007, 11:35 am
Newsgroups: comp.lang.python
From: Steve Holden <st...@holdenweb.com>
Date: Sat, 26 May 2007 21:35:54 -0400
Local: Sun, May 27 2007 11:35 am
Subject: Re: ten small Python programs
Paul McGuire wrote:

[...].

> I guess pyparsing with its mixedCase functions and attributes is
> doomed for the Dunce Corner.  Too bad for BeautifulSoup, cElementTree,
> and wxPython that are also at variance with this canon of Python
> coding style. ("Modules should have short, all-lowercase names. ...
> Python packages should also have short, all-lowercase names, although
> the use of underscores is discouraged.")

Although the names in wxPython are indeed contrary to PEP 8 (because
they are the same as the names used in wxWidgets) I should point out
that nowadays the name you import is "wx".

regards
  Steve
--
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steve Howell  
View profile
 More options May 27 2007, 11:48 am
Newsgroups: comp.lang.python
From: Steve Howell <showel...@yahoo.com>
Date: Sat, 26 May 2007 18:48:45 -0700 (PDT)
Local: Sun, May 27 2007 11:48 am
Subject: Re: ten small Python programs

--- Paul McGuire <pt...@austin.rr.com> wrote:

> I ***love*** this "10 Little Programs" idea!  As
> soon as I get a
> breathing space, I'm going to add a "10 Little
> Parsers" page to the
> pyparsing wiki!

Thanks. :)

I'm thinking you could actually have a progression
from a 1 line program up to a 50-line program.  The
number 50 is kind of arbitrary, but my gut says that
by a 50-line program, you will have demonstrated
almost every useful concept.

Agreed.  I didn't like that either.

> How's this for a better non-trivial method example:

>     MAX_ITEMS_FOR_EXPRESS_LANE = 10
>     def canUseExpressLane(self):
>         return (len(self.items) <=
> MAX_ITEMS_FOR_EXPRESS_LANE)

> or call it "can_use_express_lane" if you must.

Yep, that sounds more in the ballpark of what I'd want
to show, versus a weakish class that just encapulates
a list.

Here's my challenge to whoever wants to take it--write
(or find) a program with 20 or fewer lines that
sufficiently motivates the need for classes, has
decent Python style, and is newbie friendly.

The tutorial has this example, which is useful for
demonstrating the syntax of classes, but it doesn't
actually do anything interesting:

class MyClass:
    "A simple example class"
    i = 12345
    def f(self):
        return 'hello world'

It also has a ComplexNumber class, but I don't want to
scare away mathphobes.

It does have this idiom, which I think is worth
putting somewhere into the progression.

class Employee:
    pass

john = Employee() # Create an empty employee record

# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000

___________________________________________________________________________ _________Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more.
http://mobile.yahoo.com/go?refer=1GNXIC


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Paul McGuire  
View profile
 More options May 27 2007, 12:13 pm
Newsgroups: comp.lang.python
From: Paul McGuire <pt...@austin.rr.com>
Date: 26 May 2007 19:13:46 -0700
Local: Sun, May 27 2007 12:13 pm
Subject: Re: ten small Python programs
On May 26, 8:48 pm, Steve Howell <showel...@yahoo.com> wrote:

> I'm thinking you could actually have a progression
> from a 1 line program up to a 50-line program.  The
> number 50 is kind of arbitrary, but my gut says that
> by a 50-line program, you will have demonstrated
> almost every useful concept.

If there is anything arbitrary here, I'd say it is your "increment
each example by one source line" constraint.  This can force you to
use some bad coding practices to meet your target line count for a
given example.

Maybe try this approach:  pick your top 10/20/50 language features and
develop concise examples. Then order the examples by length as a first
cut (longer examples probably *are* more complex), and then reorder a
bit to handle pre-requisites (introduce a minimum of new features,
preferably 1, per example).  Overall, I'd have a tough time picking
just 10 language features to illustrate, but there are probably 10-20
basic features that will get new people onto fairly productive
ground.  Pick 20 as your example count (50 sounds a bit long), and
stick to it, and then later add "20 More Little Programs" for the next
wave of examples in increasing complexity.

One other nit to pick: have your example classes inherit from object,
to get new people using new-style classes from the get-go.

-- Paul


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steven Bethard  
View profile
(1 user)  More options May 27 2007, 12:33 pm
Newsgroups: comp.lang.python
From: Steven Bethard <steven.beth...@gmail.com>
Date: Sat, 26 May 2007 20:33:04 -0600
Local: Sun, May 27 2007 12:33 pm
Subject: Re: ten small Python programs

Paul McGuire wrote:
> I ***love*** this "10 Little Programs" idea!  As soon as I get a
> breathing space, I'm going to add a "10 Little Parsers" page to the
> pyparsing wiki!

> On May 26, 2:38 pm, Steven Bethard <steven.beth...@gmail.com> wrote:
>> <nitpick>
>> Though the code should probably follow PEP 8 guidelines, e.g.
>> under_scores instead of camelCase for object and method names:

>>      http://www.python.org/dev/peps/pep-0008/
>> </nitpick>

> Really?  Underscore-separated words preferred over camel case?  What
> is the rationale for this?

Rationale?  It's a style guide.  There is no rationale. ;-)

> If we want to just say "well, PEP-8 says such and such," I think this
> is an area where the thinking has possibly evolved since 2001.

I really don't think so. If anything, it's gotten more strict. PEP 8
used to allow either camelCase or under_scores. Now it only allows the
latter.

> I guess pyparsing with its mixedCase functions and attributes is
> doomed for the Dunce Corner.  Too bad for BeautifulSoup, cElementTree,
> and wxPython that are also at variance with this canon of Python
> coding style.

Many (if not all) of these modules were written before the most recent
incarnation of PEP 8. Thus, they fall under the second good reason "to
break a particular rule":

     (2) To be consistent with surrounding code that also breaks it

Of course, for new code, such as that in this thread, there's no reason
to break from the PEP 8 guidelines.

STeVe


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Steve Howell  
View profile
 More options May 27 2007, 12:58 pm
Newsgroups: comp.lang.python
From: Steve Howell <showel...@yahoo.com>
Date: Sat, 26 May 2007 19:58:10 -0700 (PDT)
Local: Sun, May 27 2007 12:58 pm
Subject: Re: ten small Python programs

--- Paul McGuire <pt...@austin.rr.com> wrote:

I understand your point, but I'm sticking to the
concept for now.  My intent with the progression isn't
so much for each example to thoroughly teach a concept
(although I could certainly hyperlink to a more
in-depth treatment), but really more to give a bird's
eye view of the language very quickly.

I recently helped teach a Java programmer to program
in Python, and he learned a lot just by seeing simple
examples.  So I guess my target audience isn't so much
people learning how to program; it's more for
programmers getting their first exposure to Python.

On the other side of the fence, I recently tried to
relearn a bit of Ruby, and I remember being frustrated
by their tutorials, as really, I just wanted to see a
bunch of simple programs, and I can figure out mostly
what they're doing.  Instead, I had to wade through
verbose descriptions of what a variable is, rules for
how you construct identifiers, etc.

My only reluctance with that approach is that it
sounds like a little more work than I'm ready to take
on right away.  But it's on the Wiki now, so maybe
other folks can help me grow it.

> One other nit to pick: have your example classes
> inherit from object,
> to get new people using new-style classes from the
> get-go.

My only fear here is that when old classes go away
(Py3K? I don't know), that practice may become
obsolete.

But on a more general note, I welcome folks to just
clean up my examples on the Wiki if I accidentally
introduce some bad practices...but preserving line
counts. :)

___________________________________________________________________________ _________
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives.
http://tools.search.yahoo.com/toolbar/features/mail/


    Reply to author