r/pythontips • • Jun 03 '21

Syntax Learn the short-circuiting functionality of the Boolean operators 'and'/'or'

"Short-circuiting" means that and and or only evaluate the right operand if the value of the left operand is not enough to determine the final result. This might seem odd at first, but learning this means you'll be able to use it to write idiomatic code, and

  • flatten and simplify some if structures;

  • write idiomatic code to assign default values to variables;

  • optimise some conditional statements;

among other things.

You can read about this in more detail in the docs or in this article I wrote with many examples from real code in the Python Std Library.

33 Upvotes

4 comments sorted by

5

u/glebulon Jun 03 '21

I think many know this as ternary/elvis operators that are coming from other languages, might want to throw in those phrases in somewhere.

2

u/RojerGS Jun 03 '21

"elvis operator"? Whut? Really? XD can you give me examples of languages where that name is used? Thanks for the tip, though!

5

u/glebulon Jun 03 '21

3

u/baristugh Jun 03 '21

I wasn't aware of the distinction and found the lil deep dive you sent me on most revealing! Good to know, thanks u/glebulon and OP for posting about it!!