[Tutor] terminology about operators and operands

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri May 2 16:49:02 2003


> For "3 + 5", 3 is the left operator, 5 is the right operator and + is
> the binary operator.


Hi everyone,


Minor terminology quibble: instead of using the word 'operator' for the
things on the left and right sides of the add, we often use the word
"operand". An "operand" is the thing being operated on by our operator, so
we should say instead that "3 is the left operand, 5 is the right operand,
and + is the binary operator".


By the way, in mathematics, the term "binary operator" has a special
meaning: it says that the left operand and the right operand have to be of
the same type.  Furthermore the result of the operation needs to be of the
type of the two operands.

    http://mathworld.wolfram.com/BinaryOperator.html



Python, for the most part, follows the mathematical definition of a binary
operator.  Once we understand the terminology, some of the Python error
messages won't seem as mysterious.  For example:

###
>>> 3 + "4"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand types for +: 'int' and 'str'
###


which says that the '+' operator just doesn't know how to add an integer
left operand to the string right operand.



The one Python operator that immediately comes to mind which doesn't
follow the mathy definition closely is 'string multiplication':

###
>>> def printHeader(title):
...     print '=' * 42
...     print title
...     print '=' * 42
...
>>> printHeader("Hello World!")
==========================================
Hello World!
==========================================
###


But for the most part, Python's binary operators only work on pairs of
things of the same types.




> It's called binary operator since it wants two operands.

Ok, never mind; you corrected yourself.  *grin*




> Python has no ternary operator (yet) but many other languages have one
> (but only one).

Magnus is referring to a feature that's being argued on the
comp.lang.python list, the "If-then-else expression" Python Enhancement
Proposal:

    http://www.python.org/peps/pep-0308.html




Talk to you later!