Skip to main content

Ors & Ands

Updated 1 min readMarkdown
Ors & Ands

I came across Stephen Grupetta’s article that highlights a nuance that I didn’t consider. or and and don't return booleans. They return one of their operands which can be any data type.

The Rules

or:

  • Returns the first operand when it's truthy

  • Returns the second operand when the first is falsy

and:

  • Returns the first operand when it's falsy

  • Returns the second operand when the first is truthy

Python objects are either truthy or falsy, it doesn't matter that or and and don't return Booleans! Leverage this to short circuit on assignment for idiomatic code and avoid a gotcha

Happy Hackin’

References

About the author

  • I am developer/code-reviewer/debugger/bug-fixer/architect/teacher/builder from dubai, uae

No comments yet. Be the first to comment.