When to use an operator vs a function?

In Python, most problems can be solved in several ways using different language constructs. For example, many operations have dedicated operators, but there are also functions or methods that achieve essentially the same result. This naturally raises the question: which approach should we choose in a given situation?

As is often the case, there’s no single right answer. However, the following questions may help guide your decision:

  • Which option makes the code more readable?
  • Which option carries a higher risk of errors?
  • Do you want to use the operation within an expression?
  • Do you want exceptions to be raised in certain cases?
  • Do you actually have a choice between alternatives?
  • Are you perhaps overusing language features just because you can?

The table below lists a few tasks along with their alternative implementations, and provides an assessment of each based on the considerations above.

Now, you’ll find an example where Solution I demonstrates an overuse of a language construct.

To understand why this constitutes overuse, let’s recall what an expression means in Python.
In Python, an expression is a construct made up of evaluable operations whose execution produces an object. That’s why expressions can appear on the right-hand side of an assignment.

What’s less often emphasized is that expressions are expected to have semantic meaning — we write them because their evaluation produces a value that matters. Consider it from the other side: does it make sense to write an expression that we know will always evaluate to the same constant value, such as None? Clearly, it doesn’t.

Language constructs that expect an expression can technically accept such constant-valued expressions, but that’s not what they’re designed for — their purpose is to work with meaningful expressions.

Python functions whose main purpose is to execute a sequence of statements rather than return a value typically yield a constant — most often None.
That’s why the e-book Python Knowledge Building Step by Step distinguishes these kinds of functions in the chapter titled „Daily routines – code reuse”, as they are, in essence, procedures rather than value-producing functions.

In the above example, the overuse occurs conceptually because the print() function is in fact a procedure. As such, it belongs in a conditional branch rather than a conditional expression.
Moreover, conditional branches can easily be extended with additional statements later, whereas conditional expressions are far more restrictive in this regard.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?