[Tutor] style question

dman dsh8290@rit.edu
Wed, 20 Feb 2002 18:16:39 -0500


On Wed, Feb 20, 2002 at 02:38:44PM -0600, Christopher Smith wrote:
| I have a question of style and am wondering if you would consider giving
| some feedbakc.  Let's say you have a task of finding out how many of 5
| positive integer numbers (a-e) are even.  Which (if either) of the two
| codes would be preferred:

How about this :

def is_even( n ) :
    return n % 2 == 0

def count_even( l ) :
    count = 0
    for i in l :
        if is_even( i ) :
            count += 1
    return count


The advantages of this style are :
    o   correct use of types (boolean vs. integer)
    o   generalizes to any finite sequence of numbers, not just 5
    o   each operation is coded once (no repetition like the if-else
        ladder)

I'm sure this could be written even shorter using functional styles or
list comprehensions, but this is the first way I thought of writing it
and it doesn't seem quite clear and not overly long.

-D

-- 

If we confess our sins, He is faithful and just and will forgive us our
sins and purify us from all unrighteousness.
        I John 1:9