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

Liam Clarke cyresse at gmail.com
Sat Oct 16 10:47:49 CEST 2004

Ah sorry, I haven't got to the functional programming bit yet. <embarrassed>

So, that would mean 'if not x' is shorthand for 'if x is False' or 'if x == 0'

so, any expression, say,  if a - 10: if a - 10 doesn't equal zero,
then it's true.

and the x % 2 and 'Even' or 'Odd'  thing is nifty..

That shines a ray of light on it for me, 


On Sat, 16 Oct 2004 08:47:12 +0100, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > I don't quite understand the syntax of
> >
> > return x % 2 and 'Even' or 'Odd'...
> This is fully exlained in my tutorial on the Functional Programming
> topic, but the short answer is:
> x % 2 and 'Even' or 'Odd'...
> Can be written:
> ((x%2) and 'Even') or 'Odd')
> This is a boolean expression.
> Python works out the first term, x%2 and of it is true looks at
> the second term in the AND expression, 'Even'. Since 'Even' is true
> (only empty strings are considered false) the whole AND expression
> is True and because it is True Python doesn't need to evaluate the
> second part of the OR expression so it returns the True part of the
> AND expression.
> And here is the trick. Python doesn't return an actual boolean value
> (True or False), instead it returns the actual value it last tested,
> in this case the string 'Even'.
> If x%2 is 0 and thus False in boolean terms the whole AND expression
> must be false. So Python now evaluates the second part of the OR
> expression, 'Odd'. Again this string is True boolean-wise, so Python
> returns the last True value, namely the string 'Odd'.
> So the actual return value from the overall expression is 'Even'
> if x%2 is true and 'Odd' if x%2 is False.
> This is not intuitively obvious but the tutorial page gives several
> more examples to illustrate how it works. In this case I thing the
> functional form works quite well because it kind of makes sense
> (to me anyway!) to say the function returns 'Even' or 'Odd'
> > I'm having trouble understanding conditionals, like... if x:   So if
> x
> > is... what exactly? Is it checking for a non-null or non-zero value?
> > Or if not x:....
> if x:
> is siply shorthand for saying
> if x == True:
> And the logical equivalent to True depends on the data type.
> Normally it is whatever comes closest in meaning to not
> being 'empty'. Thus for numbers it means not being zero,
> for sequences it really is not being empty, for files it
> means the file is open and readable - ie we aren't at the end.
> There is a page in the Python documentation that decribes
> for each type the boolean equivalents. I think its in the
> reference manual.
> HTH,
> Alan G.

More information about the Tutor mailing list