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

Alan Gauld alan.gauld at freenet.co.uk
Sat Oct 16 09:47:12 CEST 2004


> 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