How does boolean operator work on string in python

Python and and or operations stop when the answer is determined and return the value of the last object scanned. They do not return True or False. I love this feature and find myself using it all the time.

Since non-empty strings count as True

True and "asdf" or absolutely_anything_here_or_following

stops calculating when it hits the or because the answer is now determined (one of the or values is true), and returns the last thing it checked (“asdf”). No further operands are even inspected.

On the other hand, when

False and "asdf" or absolutely_anything_here

hits the or, it doesn’t know the anwser yet so continues to the next operand. As long as absolutely_anything_here is the last operation, the answer is determined and the last thing scanned is returned.

Leave a Comment