Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

ten small Python programs

4,634 views
Skip to first unread message

Steve Howell

unread,
May 26, 2007, 2:43:25 PM5/26/07
to pytho...@python.org
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

John K Masters

unread,
May 26, 2007, 3:15:16 PM5/26/07
to pytho...@python.org
On 11:43 Sat 26 May , 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.
>
> 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:
>

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)

Steven Bethard

unread,
May 26, 2007, 3:38:44 PM5/26/07
to
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

Steve Howell

unread,
May 26, 2007, 4:05:02 PM5/26/07
to Steven Bethard, pytho...@python.org

--- Steven Bethard <steven....@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.


> > 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)]
>

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

Paul McGuire

unread,
May 26, 2007, 9:23:39 PM5/26/07
to
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

Steve Holden

unread,
May 26, 2007, 9:35:54 PM5/26/07
to pytho...@python.org
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 ----------------

Steve Howell

unread,
May 26, 2007, 9:48:45 PM5/26/07
to Paul McGuire, pytho...@python.org

--- 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.


>
> >
> > > 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.
>

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

Paul McGuire

unread,
May 26, 2007, 10:13:46 PM5/26/07
to
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

Steven Bethard

unread,
May 26, 2007, 10:33:04 PM5/26/07
to
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

Steve Howell

unread,
May 26, 2007, 10:58:10 PM5/26/07
to Paul McGuire, pytho...@python.org

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

> 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.
>

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.



> 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.
>

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/

Paul McGuire

unread,
May 26, 2007, 10:58:59 PM5/26/07
to
Out of curiosity, how does this style jibe with the latest embracing
of Unicode identifiers? Ever tried to type an underscore on a non-US
keyboard? I have a heck of a time finding/typing the '_' character
when I visit our clients in Germany, but this may just be my own
personal Amerocentric issue (I also get messed up by the transposition
of Y and Z on German keyboards, but my German colleagues
understandably are not bothered by it). For someone already familiar
with that keyboard layout, is typing an underscore any more difficult
than my pressing Shift-_ on my US keyboard?

-- Paul

Paul McGuire

unread,
May 26, 2007, 11:37:51 PM5/26/07
to

Steve, sorry for going so far off-topic. I've started a new thread on
my questions about this aspect of PEP-8, and if there's more to say
about this, people should post it there.

-- Paul

Steven D'Aprano

unread,
May 27, 2007, 2:09:59 AM5/27/07
to
On Sat, 26 May 2007 18:48:45 -0700, Steve Howell wrote:

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


Is it as short as this one-liner?

ComplexNumber = complex


--
Steven.

Steve Howell

unread,
May 27, 2007, 2:30:37 AM5/27/07
to Steven D'Aprano, pytho...@python.org

--- Steven D'Aprano
<st...@REMOVE.THIS.cybersource.com.au> wrote:

The "It" above refers to *the* Python Tutorial,
written by Guido van Rossum. Here is an excerpt:

>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)

Obviously, it's not surprising that a useful class in
a tutorial would have a corresponding implementation
in the standard library, but I'm not sure newbies
would learn much about classes from this statement:

ComplexNumber = complex



____________________________________________________________________________________
Need Mail bonding?
Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.
http://answers.yahoo.com/dir/?link=list&sid=396546091

Steve Howell

unread,
May 27, 2007, 2:51:29 AM5/27/07
to pytho...@python.org

Along the idea of not reinventing a class from the
standard library in the list of ten small Python
programs (which has since grown), I went with the
classic BankAccount example for the first program to
introduce the "class" statement.

You can see the code here:

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


____________________________________________________________________________________Be a better Globetrotter. Get better travel answers from someone who knows. Yahoo! Answers - Check it out.
http://answers.yahoo.com/dir/?link=list&sid=396545469

BartlebyScrivener

unread,
May 27, 2007, 8:45:44 AM5/27/07
to
On May 26, 1:43 pm, Steve Howell <showel...@yahoo.com> wrote:

> ------
> 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)
>

For the person new to programming (doesn't come from C or other
languages), I think you need to add a separate explanation of string
formatting and how it works, or at least add a comment that tells them
you are using string formatting so that they can search and find out
how it works. If your aim is to teach simple programming concepts, why
confuse them so early on with fancy interpolation?

Something like

# uses Python string formatting
# http://docs.python.org/lib/typesseq-strings.html

but really I think it will just be a distraction

rd


Steve Howell

unread,
May 27, 2007, 11:23:26 AM5/27/07
to BartlebyScrivener, pytho...@python.org

--- BartlebyScrivener <bscriv...@gmail.com> wrote:

> On May 26, 1:43 pm, Steve Howell
> <showel...@yahoo.com> wrote:
> > ------

> > # 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)
> >
>

I decided to go with a simpler example up front.

------
# def defines a method in Python

def say_hello(name):
print 'hello', name
say_hello('Jack')
say_hello('Jill')

More here:

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

Somebody also fixed a few style things in my other
examples, changing a tuple to a list, catching a more
specific exception. Whoever you are, thanks, I agree.



____________________________________________________________________________________Sick sense of humor? Visit Yahoo! TV's
Comedy with an Edge to see what's on, when.
http://tv.yahoo.com/collections/222

Steve Howell

unread,
May 27, 2007, 11:36:28 AM5/27/07
to BartlebyScrivener, pytho...@python.org

--- BartlebyScrivener <bscriv...@gmail.com> wrote:

>
> For the person new to programming (doesn't come from
> C or other
> languages), I think you need to add a separate
> explanation of string
> formatting and how it works, or at least add a
> comment that tells them
> you are using string formatting so that they can
> search and find out
> how it works. If your aim is to teach simple
> programming concepts, why
> confuse them so early on with fancy interpolation?
>

It's a thought provoking question, and I think my aim
here is not exactly to teach simple programming
concepts, but more to expose people to what Python
looks like. I'm not really intending this page to be
a tutorial, as several good tutorials already exist.

I'm really targeting a particular niche of people.
There are folks that know how to program, but don't
know anything about Python, and they really just want
to see a bunch of small examples all in one place,
without a lot of explanation cluttering their
presentation.

That may sound like I'm narrowing my audience too
much, but I do think it's a niche group that's not
adequately addressed.

I do hope, though, that folks more in a teaching role
can reuse the examples, add better explanation, etc.,
as needed.

Also, I wouldn't mind at all to add a little link
called "Read more..." after each example.



____________________________________________________________________________________Ready for the edge of your seat?
Check out tonight's top picks on Yahoo! TV.
http://tv.yahoo.com/

Wildemar Wildenburger

unread,
May 27, 2007, 11:45:52 AM5/27/07
to pytho...@python.org
Steve Howell wrote:
> # def defines a method in Python
> def say_hello(name):
> print 'hello', name
> say_hello('Jack')
> say_hello('Jill')
>
Doesn't def define methods *xor* functions, depending on the context?
And in this example, say_hello (*yuck*, underscores ...) is certainly a
function. Or is it that functions are considered "module-methods"?

W

Steve Howell

unread,
May 27, 2007, 12:48:43 PM5/27/07
to Wildemar Wildenburger, pytho...@python.org

--- Wildemar Wildenburger <wild...@freakmail.de>
wrote:

Goodness, I didn't expect such a simple example to be
so controversial. But please see the new version
here:

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

I changed the method name to "greet" and removed the
comment, as hopefully the intent of the program will
be pretty obvious to anyone that reads it.



____________________________________________________________________________________Luggage? GPS? Comic books?
Check out fitting gifts for grads at Yahoo! Search
http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz

Steven Bethard

unread,
May 27, 2007, 1:08:43 PM5/27/07
to
Steve Howell wrote:
> --- Steven Bethard <steven....@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.

I think I would rewrite the current unit-testing example to use the
standard library unittest module::

# Let's write reusable code, and unit test it.
def add_money(amounts):
# do arithmetic in pennies so as not to accumulate float errors
pennies = sum([round(int(amount * 100)) for amount in amounts])
return float(pennies / 100.0)
import unittest
class TestAddMoney(unittest.TestCase):
def test_float_errors(self):
self.failUnlessEqual(add_money([0.13, 0.02]), 0.15)
self.failUnlessEqual(add_money([100.01, 99.99]), 200)
self.failUnlessEqual(add_money([0, -13.00, 13.00]), 0)
if __name__ == '__main__':
unittest.main()

I believe I've still kept it to 13 lines.

STeVe

P.S. The "right" way to add money is using the decimal module, but I
couldn't think of a better example.

Steve Howell

unread,
May 27, 2007, 2:08:38 PM5/27/07
to Steven Bethard, pytho...@python.org

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

> I think I would rewrite the current unit-testing
> example to use the
> standard library unittest module::
>
> # Let's write reusable code, and unit test it.
> def add_money(amounts):
> # do arithmetic in pennies so as not to
> accumulate float errors
> pennies = sum([round(int(amount * 100)) for
> amount in amounts])
> return float(pennies / 100.0)
> import unittest
> class TestAddMoney(unittest.TestCase):
> def test_float_errors(self):
> self.failUnlessEqual(add_money([0.13,
> 0.02]), 0.15)
> self.failUnlessEqual(add_money([100.01,
> 99.99]), 200)
> self.failUnlessEqual(add_money([0,
> -13.00, 13.00]), 0)
> if __name__ == '__main__':
> unittest.main()
>
> I believe I've still kept it to 13 lines.
>

I approve this change, although in a sense, it's
harder for a Python newbie, because it introduces
inheritance a little earlier than I would have liked.

FWIW I'm in the minority (I think) of people that
prefer roll-your-own testing, but I don't want to
argue that, because I think it mostly comes down to
personal preference.

I'll only defend my position by posting this link,
which suggests that roll-your-own even has validity in
an educational setting:

http://www.elkner.net/jeff/testFirst/index.html


> P.S. The "right" way to add money is using the
> decimal module, but I
> couldn't think of a better example.

Agreed. Maybe somebody else will come up with
something more creative, but I'm happy enough with our
current version.

Steve Howell

unread,
May 27, 2007, 2:10:52 PM5/27/07
to Steven Bethard, pytho...@python.org

--- Steven Bethard <steven....@gmail.com> wrote:
>
> I think I would rewrite the current unit-testing
> example to use the
> standard library unittest module::
>
> # Let's write reusable code, and unit test it.
> def add_money(amounts):
> # do arithmetic in pennies so as not to
> accumulate float errors
> pennies = sum([round(int(amount * 100)) for
> amount in amounts])
> return float(pennies / 100.0)
> import unittest
> class TestAddMoney(unittest.TestCase):
> def test_float_errors(self):
> self.failUnlessEqual(add_money([0.13,
> 0.02]), 0.15)
> self.failUnlessEqual(add_money([100.01,
> 99.99]), 200)
> self.failUnlessEqual(add_money([0,
> -13.00, 13.00]), 0)
> if __name__ == '__main__':
> unittest.main()
>

Just a minor quibble, but wouldn't you want the import
and test class to only get executed in the ___main__
context?


____________________________________________________________________________________Got a little couch potato?
Check out fun summer activities for kids.
http://search.yahoo.com/search?fr=oni_on_mail&p=summer+activities+for+kids&cs=bz

Steven Bethard

unread,
May 27, 2007, 2:39:27 PM5/27/07
to

That would be fine too. In the real world, I'd put the tests in a
different module.

STeVe

Steven Bethard

unread,
May 27, 2007, 2:59:01 PM5/27/07
to

Have you tried py.test?

http://codespeak.net/py/dist/test.html

I've heard good things about it, but haven't gotten around to trying it
yet. Here's a two-line test suite from the page above:

def test_answer():
assert 42 == 43

STeVe

Steve Howell

unread,
May 27, 2007, 3:00:16 PM5/27/07
to Steven Bethard, pytho...@python.org

Maybe this is the first good example that motivates a
hyperlink to alternatives. Would you accept the idea
that we keep my original example on the SimplePrograms
page, but we link to a UnitTestingPhilosophies page,
and we show your alternative there? Or vice versa,
show your example on the first page, but then show
mine on the hyperlinked page?

I am in 100% agreement with you that most unit tests
would be completely outside the module, although I
often follow the practice that my modules have a
little "if __main__" section that runs a few simple
unit tests, as sort of a bit of self-documentation.



____________________________________________________________________________________Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online.
http://smallbusiness.yahoo.com/webhosting

Steven Bethard

unread,
May 27, 2007, 3:01:54 PM5/27/07
to

Sure. Either way is fine.

STeVe

Steve Howell

unread,
May 27, 2007, 3:14:54 PM5/27/07
to pytho...@python.org

Changed the subject line.

Nope, I haven't. I'm a tremendous advocate of unit
testing, but I've never felt compelled to try out
other libraries, because I work mostly on private code
now, so the
following-standard-practices-to-benefit-from-familiarity
argument doesn't carry much weight with me, and also
because I find it easy enough to do things on a
roll-your-own basis. YMMV, of course.

I have slowly introduced unit testing into my own work
environment, with some success. We don't use a 3rd
party testing framework, but here's my roll-your-own
approach:

1) For flat-out failures, we just fail with a
traceback right away. We don't bother to capture
stats on how many tests failed. If one test fails,
that's enough to clue in a developer that he/she broke
something.

2) We don't use assertions very often, but rather
just diff the output files to the GOLD files. This
may eventually stop to scale, but it hasn't yet.

3)We have a little trickery to override imports,
etc., as 99.99% of our code was never written with
unit testing in mind, but I still want to regression
test it.

4) We have quite a few mock-ish objects, mainly
relating to simulating I/O situations.


____________________________________________________________________________________Pinpoint customers who are looking for what you sell.
http://searchmarketing.yahoo.com/

Steve Howell

unread,
May 27, 2007, 3:17:29 PM5/27/07
to Steven Bethard, pytho...@python.org

Ok, for now, I'm taking no action, let's let the unit
testing discussion progress a little. Despite my
saying early that I don't want to debate it, I do want
to discuss it :), as it is near in dear to my heart.

Paul Rubin

unread,
May 27, 2007, 4:13:10 PM5/27/07
to
Steven Bethard <steven....@gmail.com> writes:
> I think I would rewrite the current unit-testing example to use the
> standard library unittest module::

I think these days we're supposed to like doctest better than unittest.

Adonis Vargas

unread,
May 27, 2007, 6:37:13 PM5/27/07
to
Steve Howell wrote:
> I've always thought that the best way to introduce new
> programmers to Python is to show them small code
> examples.

<snip>

You could try this wiki page:

http://rosettacode.org/wiki/Main_Page

It has a fair amount of Python examples as well as many more other
languages (doing the same algorithm).

Hope this helps.

Adonis

Steven Bethard

unread,
May 27, 2007, 7:14:20 PM5/27/07
to
Steve Howell wrote:
> --- Steven Bethard <steven....@gmail.com> wrote:
>> Have you tried py.test?
>>
>> http://codespeak.net/py/dist/test.html
>>
>> I've heard good things about it, but haven't gotten
>> around to trying it
>> yet. Here's a two-line test suite from the page
>> above:
>>
>> def test_answer():
>> assert 42 == 43
>>
>
> Changed the subject line.
>
> Nope, I haven't. I'm a tremendous advocate of unit
> testing, but I've never felt compelled to try out
> other libraries, because I work mostly on private code
> now, so the
> following-standard-practices-to-benefit-from-familiarity
> argument doesn't carry much weight with me, and also
> because I find it easy enough to do things on a
> roll-your-own basis. YMMV, of course.

My view is generally that if I can get someone else to maintain parts of
my code for me, that's a good thing. ;-)

> 1) For flat-out failures, we just fail with a
> traceback right away.

Looks like that's the -x/--exitfirst option in py.test.

> 2) We don't use assertions very often, but rather
> just diff the output files to the GOLD files. This
> may eventually stop to scale, but it hasn't yet.

I guess I don't do enough stuff with file input and file output for this
to make sense for me.

> 3)We have a little trickery to override imports,
> etc., as 99.99% of our code was never written with
> unit testing in mind, but I still want to regression
> test it.
>
> 4) We have quite a few mock-ish objects, mainly
> relating to simulating I/O situations.


You might look into the Python Mock module:

http://python-mock.sourceforge.net/

STeVe

Steve Howell

unread,
May 27, 2007, 7:32:45 PM5/27/07
to Steven Bethard, pytho...@python.org
Let me preface every reply here by YMMV. I strongly,
strongly encourage people to tap into the unit testing
community for all tools that are available to them.

Also, let me say that despite any place where Steven
and I disagree about the mechanics of unit testing,
we're in firm agreement that UNIT TESTING IS
IMPORTANT. And sorry for shouting. And, really, if
you're not doing automated tests on your application
now, you don't know what you're missing.


--- Steven Bethard <steven....@gmail.com> wrote:
>
> > 1) For flat-out failures, we just fail with a
> > traceback right away.
>
> Looks like that's the -x/--exitfirst option in
> py.test.
>

Yes, but for my purposes, it's even easier to do
absolutely nothing when a test fails, just let it pass
through.


> > 2) We don't use assertions very often, but
> rather
> > just diff the output files to the GOLD files.
> This
> > may eventually stop to scale, but it hasn't yet.
>
> I guess I don't do enough stuff with file input and
> file output for this
> to make sense for me.
>

First, I should say that we don't completely ignore
assertion tests, as it's useful for testing truly
functional code, such as something that simply parses
a message.

But most of our application is I/O driven, and the
actual tricky modules of our application do manage a
conversation between a terminal and a host, and it's
that conversation between the terminal that we want to
proceed in a predictable fashion.


> > 4) We have quite a few mock-ish objects, mainly
> > relating to simulating I/O situations.
>
>
> You might look into the Python Mock module:
>
> http://python-mock.sourceforge.net/
>

Again, this is a case, where pardon my arrogance, I
already know how my objects work, so I already know
how to emulate them. I've read up on mock objects, so
I'm not totally ignoring common wisdom, it's just that
I get it, have a powerful language at my disposal,
etc. I fully concede that my mock objects might be
missing key features from the Python Mock module, but
I also assert that I can implement pretty robust unit
testing without it.

DJ Fadereu

unread,
May 28, 2007, 1:17:11 AM5/28/07
to

>
> You could try this wiki page:
>
> http://rosettacode.org/wiki/Main_Page
>
> It has a fair amount of Python examples as well as many more other
> languages (doing the same algorithm).
>
> Hope this helps.
>
> Adonis


THIS IS GREAT :) Thanx!

Nis Jørgensen

unread,
May 28, 2007, 4:34:49 AM5/28/07
to
Steve Howell skrev:

> And, really, if
> you're not doing automated tests on your application
> now, you don't know what you're missing.

Quote of the day, IMO.

Nis

Stef Mientki

unread,
May 28, 2007, 11:43:14 AM5/28/07
to
Steve Howell wrote:
> I've always thought that the best way to introduce new
> programmers to Python is to show them small code
> examples.
>
This is really a nice piece of missing Python.

Sorry I didn't follow this thread accurately,
but have you considered to produce an example environment like in wxPython ?

The wxPython demo program is written as an interactive tutorial,
with a few hundred examples, nicely ordered in groups.
The user can view the demo, the code and the help text.
The user can also change the code and see the results right away.

It would even be nicer, if everybody could drop her/his examples
in a standard way, so they would be automatically incorporated in
something like the wxPython interactive demo.

cheers,
Stef Mientki

Kay Schluehr

unread,
May 28, 2007, 11:42:29 AM5/28/07
to
Just for the amusement of the audience. The following is a reusable
testscript:

>>> def add_money(amounts):
... pennies = sum([round(int(amount * 100)) for amount in amounts])
... return float(pennies / 100.0)
...
>>> add_money([0.13, 0.02]) == 0.15
0.14999999999999999
>>> add_money([0.13, 0.02]) == 0.15
True
>>> assert add_money([0.13, 0.02]) == 0.15
>>> assert add_money([100.01, 99.99]) == 200
>>> assert add_money([0, -13.00, 13.00]) == 0


It's just a matter of perspective...

http://fiber-space.de/EasyExtend/doc/consoletest/consoletest.html

Steve Howell

unread,
May 28, 2007, 12:35:45 PM5/28/07
to Stef Mientki, pytho...@python.org

--- Stef Mientki <S.Mientk...@mailbox.kun.nl>
wrote:

> Steve Howell wrote:
> > I've always thought that the best way to introduce
> new
> > programmers to Python is to show them small code
> > examples.
> >
> This is really a nice piece of missing Python.
>

Thanks.

> The wxPython demo program is written as an
> interactive tutorial,
> with a few hundred examples, nicely ordered in
> groups.
> The user can view the demo, the code and the help
> text.
> The user can also change the code and see the
> results right away.
>

Do you have a link?

> It would even be nicer, if everybody could drop
> her/his examples
> in a standard way, so they would be automatically
> incorporated in
> something like the wxPython interactive demo.
>

Can you elaborate?


____________________________________________________________________________________
8:00? 8:25? 8:40? Find a flick in no time
with the Yahoo! Search movie showtime shortcut.
http://tools.search.yahoo.com/shortcuts/#news

Stef Mientki

unread,
May 28, 2007, 2:48:53 PM5/28/07
to

>
>> The wxPython demo program is written as an
>> interactive tutorial,
>> with a few hundred examples, nicely ordered in
>> groups.
>> The user can view the demo, the code and the help
>> text.
>> The user can also change the code and see the
>> results right away.
>>
>
> Do you have a link?
wxPython including demos can be downloaded from

http://www.wxpython.org

but there's no separate page of the demo,
so I made a few screenshots:

http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/wxpython_overview.html

>
>> It would even be nicer, if everybody could drop
>> her/his examples
>> in a standard way, so they would be automatically
>> incorporated in
>> something like the wxPython interactive demo.
>>
>
> Can you elaborate?

Well if you see the above demo,
I've the following in mind:
- create a new-demo in a special directory
- add some special keywords in the new-demo, in which treenodes it should popup
- on restart of the demo, the new-demo is added to the tree

cheers,
Stef Mientki

Steve Howell

unread,
May 28, 2007, 3:38:04 PM5/28/07
to pytho...@python.org

--- Stef Mientki <S.Mientk...@mailbox.kun.nl>
wrote:
> >
> >> It would even be nicer, if everybody could drop
> >> her/his examples
> >> in a standard way, so they would be automatically
> >> incorporated in
> >> something like the wxPython interactive demo.
> >>
> >
> > Can you elaborate?
>
> Well if you see the above demo,
> I've the following in mind:
> - create a new-demo in a special directory
> - add some special keywords in the new-demo, in
> which treenodes it should popup
> - on restart of the demo, the new-demo is added to
> the tree
>

To the extent that you just want a group of people to
be able to organically organize a tree-like collection
of Python examples, you could use a MoinMoin that has
sensible page names and the Local Site Map featured
turn on. Are you also suggesting the need for
something local, so that you can actually run the
programs?

Stef Mientki

unread,
May 28, 2007, 5:22:53 PM5/28/07
to
Steve Howell wrote:
> --- Stef Mientki <S.Mientk...@mailbox.kun.nl>
> wrote:
>>>> It would even be nicer, if everybody could drop
>>>> her/his examples
>>>> in a standard way, so they would be automatically
>>>> incorporated in
>>>> something like the wxPython interactive demo.
>>>>
>>> Can you elaborate?
>> Well if you see the above demo,
>> I've the following in mind:
>> - create a new-demo in a special directory
>> - add some special keywords in the new-demo, in
>> which treenodes it should popup
>> - on restart of the demo, the new-demo is added to
>> the tree
>>
>
> To the extent that you just want a group of people to
> be able to organically organize a tree-like collection
> of Python examples, you could use a MoinMoin that has
> sensible page names and the Local Site Map featured
> turn on. Are you also suggesting the need for
> something local, so that you can actually run the
> programs?

I don't know MoinMoin,
but the answer is Yes (although maybe not for your ten snippets).
First of all I think all programmers keep there own collection of code snippets,
which much more valuable then "all the code code snippets from everyone".
Secondly, Python is nowadays not only used by programmers,
but also by e.g. Scientific users (former MatLab users),
who are not interested in the code itself,
but just in the results of that particular code.
For these people a lot of example programs,
for which they can easily see the results,
make some small changes and see the result again,
would be a wonderful addition.

just my 2 cents,
cheers,
Stef Mientki


Steve Howell

unread,
May 28, 2007, 5:45:26 PM5/28/07
to Stef Mientki, pytho...@python.org

--- Stef Mientki <S.Mientk...@mailbox.kun.nl> > >

> I don't know MoinMoin,
> but the answer is Yes (although maybe not for your
> ten snippets).
> First of all I think all programmers keep there own
> collection of code snippets,
> which much more valuable then "all the code code
> snippets from everyone".

Agreed.

> Secondly, Python is nowadays not only used by
> programmers,
> but also by e.g. Scientific users (former MatLab
> users),
> who are not interested in the code itself,
> but just in the results of that particular code.
> For these people a lot of example programs,
> for which they can easily see the results,
> make some small changes and see the result again,
> would be a wonderful addition.
>

In your own personal use, what are some
libraries/techniques/etc. that you think could benefit
from some kind of more organized presentation of
example programs (or better way of showing how the
examples work, etc.)? Are you part of the Scientific
community?

How new are you to Python? I do think
newbies/intermediates/advanceds all have different
needs.

stef

unread,
May 29, 2007, 5:30:16 AM5/29/07
to

>
>> Secondly, Python is nowadays not only used by
>> programmers,
>> but also by e.g. Scientific users (former MatLab
>> users),
>> who are not interested in the code itself,
>> but just in the results of that particular code.
>> For these people a lot of example programs,
>> for which they can easily see the results,
>> make some small changes and see the result again,
>> would be a wonderful addition.
>>
>>
>
> In your own personal use, what are some
> libraries/techniques/etc. that you think could benefit
> from some kind of more organized presentation of
> example programs (or better way of showing how the
> examples work, etc.)?
for example SciPy,
but I think it yield for all libs/techniques.
And I guess Windows users have a much greater need for such an
organization than *nix users.

> Are you part of the Scientific
> community?
>
>
sort of, I indeed work at a university,
but not doing scientific work myself,
I work on a supporting department.

> How new are you to Python?

very new ;-)
(I've lot of experience in a other programming languages,
last years mostly Delphi, JAL, MatLab)

> I do think
> newbies/intermediates/advanceds all have different
> needs.
>

agreed.

cheers,
Stef Mientki

Jacob Hallen

unread,
Jun 8, 2007, 4:32:20 AM6/8/07
to
In article <mailman.8216.1180205...@python.org>,

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

Something like this:

http://www.lava.se/sam/

Jacob Hallén

--

0 new messages