Operators

Now that we know that functions are a way of taking a number of inputs and producing an output, we should look again at what happens when we write:

x = 2 + 3
print(x)

5

This is just a pretty way of calling an “add” function. Things would be more symmetrical if add were actually written

x = +(2, 3)

Where ‘+’ is just the name of the name of the adding function.

In python, these functions do exist, but they’re actually methods of the first input: they’re the mysterious __ functions we saw earlier (Two underscores.)

x.__add__(7)

12

We call these symbols, +, - etc, “operators”.

The meaning of an operator varies for different types:

"Hello" + "Goodbye"

‘HelloGoodbye’

[2, 3, 4] + [5, 6]

[2, 3, 4, 5, 6]

Sometimes we get an error when a type doesn’t have an operator:

7 - 2

5

For example:

[2, 3, 4] - [5, 6]

—————————————————————————

TypeError Traceback (most recent call last)

<ipython-input-38-4627195e7799> in <module>()

—-> 1 [2, 3, 4] - [5, 6]

TypeError: unsupported operand type(s) for -: ‘list’ and ‘list’

The word “operand” means “thing that an operator operates on”!

Or when two types can’t work together with an operator:

[2, 3, 4] + 5

—————————————————————————

TypeError Traceback (most recent call last)

<ipython-input-39-84117f41979f> in <module>()

—-> 1 [2, 3, 4] + 5

TypeError: can only concatenate list (not “int”) to list

Just as in Mathematics, operators have a built-in precedence, with brackets used to force an order of operations:

print(2 + 3 * 4)

14

print((2 + 3) * 4)

20

Supplementary material: http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html

Next: Experience - Practical: Using Functions