We know many operators from school. They are things like addition
-, and so on.
In this chapter, we’ll concentrate on aspects of operators that are not covered by school arithmetic.
Terms: “unary”, “binary”, “operand”
Before we move on, let’s grasp some common terminology.
- An operand – is what operators are applied to. For instance, in the multiplication of
5 * 2there are two operands: the left operand is
5and the right operand is
2. Sometimes, people call these “arguments” instead of “operands”.
- An operator is unary if it has a single operand. For example, the unary negation
-reverses the sign of a number:
An operator is binary if it has two operands. The same minus exists in binary form as well:
In the above examples, we formally have two different operators sharing the same symbol: the negation operator, a unary operator reversing the sign, and the subtraction operator, a binary operator subtracting one number from another.
String concatenation, binary +
Usually, the plus operator
+ sums numbers.
But, if the binary
+ is applied to strings, it merges (concatenates) them:
Note that if one of the operands is a string, the other one is converted to a string too.
See, it doesn’t matter whether the first operand is a string or the second. The rule is simple: if either operand is a string, the other operand is also converted to a string. Note, though, that operations are running from left to right. If there are two numbers followed by a string, before converting to a list, the numbers will be added:
String concatenation and conversion is a special feature of the binary plus
+. Other arithmetic operators work only with numbers and always convert their operands to numbers.
For instance, subtraction and division:
The addition operator
+ (addition) operator is used for both addition and concatenation of strings.
For example, adding two variables is easy:
The addition operator is used to combine strings with strings, strings with numbers, and numbers with strings:
Use the signs minus-), (asterisk (*) and slash (/) to subtract, multiply and divide two numbers.
Advanced mathematical operators