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

Alan Gauld alan.gauld at freenet.co.uk
Sat Oct 16 00:51:37 CEST 2004


> >def OddorEven(x):
> >a=0
> >a=x % 2
> >if a ==0:
> >     return "Even"
> >else:
> >     return "Odd"

I may have missed this one earlier but an obvious shortner 
here is:

def OddorEven(x):
   return x % 2 and 'Even' or 'Odd'

But IMHO better still is to turn it into a true predicate:

def isOdd(x):
   return x%2

So we get a boolean result and can display a suitable message 
outside the function. Keeping presentation away from logic is 
nearly always the right thing...
 
Alan G.



More information about the Tutor mailing list