[Tutor] Truth value testing in if, while and boolean operations
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Oct 15 13:02:38 EDT 2020
On 15/10/2020 16:33, Manprit Singh wrote:
> 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()
> There is nothing mentioned in PEP 8 about using the sets, dicts etc in the
> same way as given above .
PEP 8 is a style guide not a language reference. it is not exhaustive.
However it does say "if sequence" and your quote in the first paragraph
says:
> empty sequences and collections: '', (), [], {}, set(), range(0) are
> considered as false .
ie. sequence includes strings, tuples, dicts, sets, lists, ranges...
So PEP8 includes all of the above.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list