[Tutor] Find out if a number is even or not
Riumu Kuraku
cyresse at gmail.com
Sat Oct 16 05:12:33 CEST 2004
I don't quite understand the syntax of
return x % 2 and 'Even' or 'Odd'...
so if x > 0 it should return x and 'Odd', but if x is 0 then it
returns 0 and 'Even'?
How does that work?
I can see how your isOdd function works, if x divides by 2 with no
remainder, then isOdd(x) is False.
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:....
Can anyone recommend a link that goes into details on if & while
statements, and the various checks?
Regards,
Liam Clarke
On Fri, 15 Oct 2004 23:51:37 +0100, Alan Gauld <alan.gauld at freenet.co.uk> wrote:
> > >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.
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list