[Tutor] Truth value testing in if, while and boolean operations
Manprit Singh
manpritsinghece at gmail.com
Thu Oct 15 11:33:30 EDT 2020
Dear sir ,
While referring to python docs , i found that under the heading "Truth
Value testing" it is written that
empty sequences and collections: '', (), [], {}, set(), range(0) are
considered as false .
In PEP8 docs under "programming recommendations" it is written that :
"For sequences, (strings, lists, tuples), use the fact that empty sequences
are false:
so it is a valid practice to write like this
if sequence: # do_this() will be executed if sequence is not empty
do_this()
else: # do_this_1() will be executed if sequence is empty
do_this_1()
There is nothing mentioned in PEP 8 about using the sets, dicts etc in the
same way as given above . As we know that empty sets & dicts are also
considered false, using dicts and sets in the way as given above is valid
and adheres to PEP 8 guidelines ?
___________________________________________________________________
if dict: # do_this() will be executed if dict is not empty
do_this()
else: # do_this_1() will be executed if dict is empty
do_this_1()
_____________________________________________________________________
if set: # do_this() will be executed if set is not empty
do_this()
else: # do_this_1() will be executed if set is empty
do_this_1()
___________________________________________________________________
2 Examples just given above are valid according to PEP 8?
Regards
Manprit Singh
More information about the Tutor
mailing list