[Tutor] Creatively solving math problems -----help

Alan Gauld alan.gauld at blueyonder.co.uk
Wed Sep 10 23:32:55 EDT 2003


> >for x in range(20000):
> >         if x/2 == int(x/2) and x/3 == int(x/3) and x/4 == int(x/4)
and \
> >         x/5 == int(x/5) and x/6 == int(x/6) and x/7-1 ==
int(x/7-1):

Somebody already mentioned the modulo operator howebver as a general
rule its worth using parens to group your test:

         if (x/2 == int(x/2))  and  (x/3 == int(x/3)) and
            (x/4 == int(x/4))  and  (x/5 == int(x/5)) and
            (x/6 == int(x/6))  and  (x/7-1 == int(x/7-1)):


Otherwise there is a danger of the test being interpreted as:

if x/2 == (int(x/2) and x/3) ...etc...

ie comparing a number to a boolean. This will always be true
unless x/2 is zero! The way Python interprets the tests is
down to something called operator precedence which is way
to complicated to even try to remember(for me anyway!) so
just put parens in, space it liberally, and avoid any ambiguity.

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list