[python-advocacy] example code

Carl Karsten carl at personnelware.com
Thu Nov 12 18:04:40 CET 2009


On Thu, Nov 12, 2009 at 10:33 AM, Ray Allen <rayallen153 at googlemail.com> wrote:
> Thanks for the comments.  Taking them onboard, we'd end up with the
> following..
>
> """Example Python Program"""
>
> import random
>
> # Create  list
> python = ["Easy to read",
> "Fast to code",
> "Quick to learn",
> "Modular and object oriented"]
>
> # Append list
> python.append("Open source and cross platform")
>
> # Shuffle list
> random.shuffle(python)
>
> # Loop list
> print "Python is ... "
> for index, each in enumerate(python):

each is a keyword in other languages (for each foo in bar) so it may
add confusion here.

for feature in python:
     print(feature)


I also think we should leave out the comments.  at least these.  I
doubt anyone puts this level of comment in their code.  We want to
keep the snippet short, and I am pretty sure anyone who understands
the comment will also understand the code.

>     print index + 1, each
>
> print "Discover more at http://www.python.org"
>
> It's fewer lines than many 'helloworld!' examples in other languages, but it
> demonstrates a few good features without confusing anybody.
>
> 2009/11/12 Carl Karsten <carl at personnelware.com>
>>
>> 2009/11/12 Tarek Ziadé <ziade.tarek at gmail.com>:
>> > On Thu, Nov 12, 2009 at 3:39 PM, Ray Allen <rayallen153 at googlemail.com>
>> > wrote:
>> > [..]
>> >>
>> >> # Loop through list
>> >> count = 1
>> >> print "Python is ... "
>> >> for each in python:
>> >>     print count,each
>> >>     count += 1
>> >
>> > I'd replace this bloc by:
>> >
>> > # Loop through list
>> > print "Python is ... "
>> > for index, each in enumerate(python):
>> >    print index + 1, each
>> >
>> > (using enumerate is much more pythonic than using a count variable)
>>
>> I would avoid the counter.
>>
>> I learned to iterate a list by using a counter as an index into the
>> list.  When I was shown that I didn't need the counter, I felt uneasy
>> - perhaps even in denial that this was a good thing - seemed like a
>> short cut.   Weeks or months later it hit me: The reason I needed it
>> in those other languages is because they didn't have this 'feature',
>> so the counter/index/item was a work around.
>>
>> A few months ago someone getting started with python was asking me
>> ~"why is the counter/index/item pattern so cumbersome?"  A:"Because
>> you normally don't need the counter."  I could see in his eyes the
>> exact same disbelief I had felt.
>>
>> I think we should to focus on what makes python different.
>>
>> --
>> Carl K
>> _______________________________________________
>> Advocacy mailing list
>> Advocacy at python.org
>> http://mail.python.org/mailman/listinfo/advocacy
>
>



-- 
Carl K


More information about the Advocacy mailing list