[Tutor] Very basic question about lists

spir denis.spir at free.fr
Tue Dec 23 13:16:47 CET 2008


> I see I have to do a loop inside a loop and that this the right expression
> if word == 'ar' or word == 'ko':
> 
> but this is not:
> if word == 'ar' or 'ko':

In the last example: as the 'or' operator has the least priority, it
will be applied last. Which means that all other operations in the
expression will be done first. In this case, there is only one, namely
(word=='ar'):

if ( (word == 'ar') or ('ko') ):

So that, in order to evaluate the or operation, python needs to know
whether either (word=='ar') or ('ko') is True. If either is True, the
whole is True too: this is precisely the sense of 'or'. Right?

* on left side, (word == 'ar') is true if word equals 'ar'
* on right side, 'ko' is true if... what?

This is the second point of my explanation. Conceptually, only logical
(boolean) values, and operations on these values, could/should be
allowed in logical expressions. But python also implicitely gives a
logic value to everything:

* numbers equal to zero are False
* empty containers (list, string) are False
* anything else is considered True

if 0			--> False
if ""			--> False
if []			--> False
if 1 			--> True
if [1,2,3]		--> True
if 'abc'		--> True
if 'a' and x=1 		--> True if x==1, because 'a' is True
if 'a' or x=1		--> alwaysTtrue, because 'a' is True
if word == 'ar' or 'ko'	--> always True
if 'ar' or 'ko' in seq	--> always True, because 'ar' is True

Note:
This comes from old times of programmation when False was represented by
0 and True by 1, -1, or any non-zero value (like in python). This
allowed very practicle and "clever" programming tricks, but difficult to
understand (as you see). Because conceptually wrong, in my opinion.
Python even extended that by giving a False value not only to numbers
equal to zero, but also to empty sets. This allows to write, for
instance:

if number:		# means: if number not null
	do something

if sequence:		# means: if sequence not empty
	do something

if max_number and total<max_number or collection:
	do something
# means: if there is a "max_number" condition (for it is not null) and
the actual total is less than max_number, or if there is something in
collection... do something


Denis



More information about the Tutor mailing list