# [Tutor] style question

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 20 Feb 2002 13:30:21 -0800 (PST)

```On Wed, 20 Feb 2002, 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:
>
> # {option A}
> odd=a%2+b%2+c%2+d%2+e%2

> # {option B}
> if a%2==0:
> 	even = even + 1
> if b%2==0:
> 	even = even + 1
> if c%2==0:
> 	even = even + 1
> if d%2==0:
> 	even = even + 1
> if e%2==0:
> 	even = even + 1
> odd = 5 - even

I like option A better than option B.  Option B has the real potential of
hiding errors because it's forcing us to look at the same variables over
and over and over again.  Humans will often get bored at repetition, and
most programmers that I know are human.  *grin*

Here's a hypothetical example of why repetitious code can be a little
hazardous:

###
if a%2==0:
even = even + 1
if b%2==0:
even = even + 1
if c%2==0:
even = even + 1
if c%2==0:	             ##  <--- ??!
even = even + 1
if e%2==0:
even = even + 1
odd = 5 - even
###

Something like the above is silly and very obvious when we have five
cases... but yet it's still so easy to miss if we're not careful.  Better
to avoid the temptation altogether.

> Is option A guilty of relying on the "side effect" of mod 2 being a 1
> or zero or is this a desireable/understandable use of this function's
> return value?

I think the approach with 'mod 2' is understandable; the modulo
(remainder) function with 2 always returns a one or a zero.  Don't worry;
you're using the modulo operator the way it was meant to be used.

It might be useful to see if applying list stuff can be helpful; when
we're doing the same sort of stuff on a bunch of variables, that's often a
sign that using a list might be better.  For example:

###
numbers = [a, b, c, d, e]
odd = 0
for n in numbers: odd = odd + (n % 2)
###

is nice because it's easily amendable; if we have more numbers to test,
all we need to do is add them into the 'numbers' list.

```