[Tutor] Leap years
Tim Wilson
wilson@visi.com
Tue Jan 14 17:23:01 2003
On Tuesday 14 January 2003 15:52, ahimsa wrote:
> But ... how does one construct the test of whether something is true or
> not without the test to establish that, which is what the 'if-else'
> block was intended to do?
That's a good question. Look at the following:
wilson@copland:~> python
Python 2.2.1 (#1, Oct 15 2002, 03:52:39)
[GCC 3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def isEven(num):
=2E.. if num % 2 =3D=3D 0:
=2E.. return 1
=2E.. else:
=2E.. return 0
=2E..
>>> isEven(4)
1
>>> isEven(5)
0
>>> def isEven(num):
=2E.. return num % 2 =3D=3D 0
=2E..
>>> isEven(4)
1
>>> isEven(5)
0
I've created a very simply boolian function to illustrate this.
The first version is certainly more explicit. If you haven't run across i=
t=20
yet, the % operator in Python is called "mod" and is the same as the=20
remainder concept you probably recall from elementary school math class. =
In=20
this case, any number that has 0 remainder when divided by 2 is event and=
=20
anything else is odd.
For a given value of "num," the statement
num % 2 =3D=3D 0:
is either true or false. By using the construct
return num % 2 =3D=3D 0
I'm simply evaluating the "trueness" :-) of the num % 2 =3D=3D 0 expressi=
on and=20
returning that straight away. As always, this idiom is optional, but quit=
e=20
elegant I think.
-Tim
--=20
Tim Wilson
Twin Cities, Minnesota, USA
Science teacher, Linux fan, Zope developer, Grad. student, Daddy
mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813