[Tutor] Find out if a number is even or not

Lloyd Hugh Allen chandrakirti at gmail.com
Sat Oct 16 19:45:11 CEST 2004


I'm going to say more about mine.

We know that computers like binary better, because it is easier to
tell the difference between "on" and "off" than for a circuit to try
to measure an analog level of voltage on a circuit.

So to the computer, 6 looks like 110, which is (going from right to
left) 0*(2**0) + 1*(2**1) + 1*(2**2) == 0 + 2 + 4. Counting in binary
would look like

1  1
2  10
3  11
4  100
5  101
6  110
7  111
8  1000

we notice that the odd numbers have a "one's" digit, in binary, of one.

The bitwise and operator, &, compares the binary digits of its two
arguments. For instance, 4&5 notes that the only digit that is on in
both binary expansions is the one in the fours place. Therefore, 4&5
== 4. Similarly, 1 & odd == 1 and 1 & even == 0.

Python 2.3 has booleans. I like them, and the original question was
phrased as, "I want to know when a number is even."

So num & 1 will give a nonzero result for odds and a result of zero
for evens; since not zero is True and not (nonzero) is False, taking
not (num & 1) gives the "even-ness" of an integer.

As a happy sidenote, bitwise and gets angry when a float is thrown at
it. I don't want to guess as to whether a float is even or odd; my
function throws an exception.



On Fri, 15 Oct 2004 23:09:45 -0400, Lloyd Hugh Allen
<chandrakirti at gmail.com> wrote:
> There's also the bitwise & operation
> 
> def isEvenQ(num):
>     return not (num & 1)
> 
> don't know if it's actually faster though.
> 
> 
> 
> On Fri, 15 Oct 2004 12:00:18 +0100, nick at javacat.f2s.com
> <nick at javacat.f2s.com> wrote:
> > Hi group,
> >
> > Im sure this is simple to do, but Ive just been looking through the python docs
> > and the archive of this mailing list and cant find what Im after.
> >
> > I just want to know if a number is even or not.
> >
> > I've had a look at the math package but that doesnt seem to have anything this
> > simple in it.
> >
> > I thought something like
> >
> > >>> if 10 div 2 == 0 : print 'even'
> > >>> else : print 'odd'
> >
> > but obviously that doesnt work.
> >
> > Sorry for such a basic question, but I really cant find out how to do this.
> >
> > Kind regards
> > Nick.
> >
> > -------------------------------------------------
> > Everyone should have http://www.freedom2surf.net/
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>


More information about the Tutor mailing list