Pure Programmer
Blue Matrix


Cluster Map

Operators

Every programming language provides built-in operators for performing arithmetic, logic and bitwise operations. You will also find operators to compare values and assign value to a variable, subscript arrays and invoke functions. Depending on the language you may find referencing/dereferencing, member selection, pattern matching, range or type casting operators. Many of these operators will be explored in this section, but some will be deferred until later sections where their use becomes necessary.

Typecasting

In untyped languages like Python we don't often need to convert a value of one type to a value of a different type. Often this is done automatically for us by the language. For example, converting an integer to a string or a string to an integer is done automatically based on the context.

One situation where we might need a typecast is when converting floating point values to an integer value. If we use the typecast to int we will get a truncation of the floating point value. Perhaps a better option is to use the floor() and ceil() math functions to either round down or round up as needed.

Ways to Convert Values
MethodDescription
i = math.trunc(fp)Round floating point toward zero
i = math.ceil(fp)Round floating point up to integer
i = math.floor(fp)Round floating point down to integer
i = int(x)Convert to int by truncating (number or string)
fp = float(x)Convert to floating point (number or string)
s = str(x)Convert to string

Arithmetic Operators

[[Arithmetic operations]] are one of the two major groups of operations that computers perform for us, the other being [[logical operations]]. Arithmetic operators include multiplication, division, remainder (modulus), addition, subtraction and negation (unary minus). Most of these operations should be familiar as they are the basic arithmetic operations taught in elementary school. Modulus is less familiar but it is simply the remainder after division. Remember those times studying long division where we ended up with a remainder? That remainder is the modulus.

The arithmetic operators are mostly similar to the symbols typically used in mathematics: addition (+), subtraction (-), division (/). Only multiplication (*) and modulus (%) differ from standard mathematical notation. Unlike standard mathematical notation where placing two symbols next to each other implies multiplication as in xyz (which means x × y × z), when writing code we must explicitly use the multiplication operator as in x * y * z.

Operators1.py
#!/usr/bin/env python3;
# Begin Main
a = 3
b = 5
c = 2
d = 3.1415926
e = 4.0

print("-b = " + str((-b)))
print("a + b = " + str((a + b)))
print("a + -b = " + str((a + -b)))
print("-a + b = " + str((-a + b)))
print("-a + -b = " + str((-a + -b)))
print("a - b = " + str((a - b)))
print("a - -b = " + str((a - -b)))
print("-a - b = " + str((-a - b)))
print("-a - -b = " + str((-a - -b)))
print("b * c = " + str((b * c)))
print("b * -c = " + str((b * -c)))
print("-b * c = " + str((-b * c)))
print("-b * -c = " + str((-b * -c)))
print("b / c = " + str((b / c)))
print("b / -c = " + str((b / -c)))
print("-b / c = " + str((-b / c)))
print("-b / -c = " + str((-b / -c)))
print("b // c = " + str((int(b / c))))
print("b // -c = " + str((int(b / -c))))
print("-b // c = " + str((int(-b / c))))
print("-b // -c = " + str((int(-b / -c))))
print("b % a = " + str((b % a)))
print("b % -a = " + str((b % -a)))
print("-b % a = " + str((-b % a)))
print("-b % -a = " + str((-b % -a)))
print("d + e = " + str((d + e)))
print("d - e = " + str((d - e)))
print("d * e = " + str((d * e)))
print("e / d = " + str((e / d)))
print("e // d = " + str((int(e / d))))

Output
$ python3 Operators1.py -b = -5 a + b = 8 a + -b = -2 -a + b = 2 -a + -b = -8 a - b = -2 a - -b = 8 -a - b = -8 -a - -b = 2 b * c = 10 b * -c = -10 -b * c = -10 -b * -c = 10 b / c = 2.5 b / -c = -2.5 -b / c = -2.5 -b / -c = 2.5 b // c = 2 b // -c = -2 -b // c = -2 -b // -c = 2 b % a = 2 b % -a = -1 -b % a = 1 -b % -a = -2 d + e = 7.1415926 d - e = -0.8584073999999999 d * e = 12.5663704 e / d = 1.2732395664542882 e // d = 1

String Concatenation

String concatenation is a special operator that is used to combine two strings into a single string. We use the plus (+) symbol to represent this special operation. For example:

Operators2.py
#!/usr/bin/env python3;
# Begin Main
a = "Hello, "
b = "world"
c = "Bruce"
d = "Sheriff Brody"
e = "!"
print(a + b + e)
print(a + c + e)
print(a + d + e)

Output
$ python3 Operators2.py Hello, world! Hello, Bruce! Hello, Sheriff Brody!

Comparison Operators

The comparison operators less than, greater than, equal, not equal, etc. allow us to determine how two values compare to each other. They are fundamentally arithmetic in nature. This is because comparisons are subtraction operations that then look at whether the difference is negative, positive or zero.

The symbol to check equality is (==). Note that there are two equal signs not just one which has a different meaning, namely assignment. The symbol to check if two values are not equal is (!=). The symbols for less than (<) and greater than (>) are as we would expect. The symbols for less than or equal (<=) and greater than or equal (>=) add the equal sign to the less than or greater than symbols. For these symbols the equal sign always appears on the right.

Operators3.py
#!/usr/bin/env python3;
# Begin Main
a = 3
b = 5
c = 3.1415926
d = 4.0
e = "apple"
f = "pear"

print("a < b : " + str((a < b)))
print("a <= b : " + str((a <= b)))
print("a > b : " + str((a > b)))
print("a >= b : " + str((a >= b)))
print("a == b : " + str((a == b)))
print("a != b : " + str((a != b)))

print("c < d : " + str((c < d)))
print("c <= d : " + str((c <= d)))
print("c > d : " + str((c > d)))
print("c >= d : " + str((c >= d)))
print("c == d : " + str((c == d)))
print("c != d : " + str((c != d)))

print("e < f : " + str((e < f)))
print("e <= f : " + str((e <= f)))
print("e > f : " + str((e > f)))
print("e >= f : " + str((e >= f)))
print("e == f : " + str((e == f)))
print("e != f : " + str((e != f)))

Output
$ python3 Operators3.py a < b : True a <= b : True a > b : False a >= b : False a == b : False a != b : True c < d : True c <= d : True c > d : False c >= d : False c == d : False c != d : True e < f : True e <= f : True e > f : False e >= f : False e == f : False e != f : True

Logical Operators

The logical operators allow us to perform [[Boolean]] arithmetic. We have the logical operators AND (and), OR (or) and NOT (not) that can be used to form any logical expression needed. The logical operators operate on and return the values False for falsity and True for truth.

ABA and B
FalseFalseFalse
FalseTrueFalse
TrueFalseFalse
TrueTrueTrue
Logical AND
 
ABA or B
FalseFalseFalse
FalseTrueTrue
TrueFalseTrue
TrueTrueTrue
Logical OR
 
Anot A
FalseTrue
TrueFalse
Logical NOT
Operators4.py
#!/usr/bin/env python3;
# Begin Main
a = True
b = False

print("a AND b : " + str((a and b)))
print("a OR b : " + str((a or b)))
print("NOT a : " + str((not a)))
print("NOT b : " + str((not b)))

Output
$ python3 Operators4.py a AND b : False a OR b : True NOT a : False NOT b : True

Bitwise Operators

We also have [[bitwise operators]] that work on the premise that each bit (0 or 1) in a value can be considered either False or True, respectively. Bitwise operators operate on integer values and perform their operation for each pair of bits (for binary operations) in the value. Some examples using 4-bit values are illustrated below.

ABA & B
000000000000
000001010000
001101010001
110001010100
111100110011
111111111111
Bitwise AND
 
ABA | B
000000000000
000001010101
001101010111
110001011101
111100111111
111111111111
Bitwise OR
 
ABA ^ B
000000000000
000001010101
001101010110
110001011001
111100111100
111111110000
Bitwise XOR
 
A~A
00001111
00111100
10100101
11110000
Compliment
Operators5.py
#!/usr/bin/env python3;
import Utils

# Begin Main
a = 0x5555AAAA
b = 0x036C36CF

print("Bitwise a AND b : {0:08x}".format((Utils.bitwiseAnd32(a, b))))
print("Bitwise a OR b : {0:08x}".format((Utils.bitwiseOr32(a, b))))
print("Bitwise a XOR b : {0:08x}".format((Utils.bitwiseXOr32(a, b))))
print("Compliment a : {0:08x}".format((Utils.complement32(a))))
print("Compliment b : {0:08x}".format((Utils.complement32(b))))

Output
$ python3 Operators5.py Bitwise a AND b : 0144228a Bitwise a OR b : 577dbeef Bitwise a XOR b : 56399c65 Compliment a : -5555aaab Compliment b : -36c36d0

Assignment Operators

Assignment operators allow us to change the value of a variable. The assignment operator is represented by a single equal sign (=). It should not be confused with the equivalence comparison operator which is represented by a double equal sign (==).

Operators6.py
#!/usr/bin/env python3;
# Begin Main
a = 3

a += 1
print("a += 1: " + str(a))
a -= 1
print("a -= 1: " + str(a))

a += 2
print("a += 2 : " + str(a))
a *= 3
print("a *= 3 : " + str(a))
a -= 4
print("a -= 4 : " + str(a))
a /= 5
print("a /= 5 : " + str(a))

Output
$ python3 Operators6.py a += 1: 4 a -= 1: 3 a += 2 : 5 a *= 3 : 15 a -= 4 : 11 a /= 5 : 2.2

Conditional Operator

The only ternary operator (takes three operands) is the conditional operator. Based on the truth of the first operator, it will yield either the value of the second or third operator. The expression B if A else C yields B if A is true and C if A is false.

Operators7.py
#!/usr/bin/env python3;
# Begin Main
a = 3
b = 5

print("a < b ? -1 : 1 => " + str((-1 if a < b else 1)))
print("b < a ? -1 : 1 => " + str((-1 if b < a else 1)))
print("a < b ? 'less' : 'greater' => " + ("less" if a < b else "greater"))
print("b < a ? 'less' : 'greater' => " + ("less" if b < a else "greater"))

Output
$ python3 Operators7.py a < b ? -1 : 1 => -1 b < a ? -1 : 1 => 1 a < b ? 'less' : 'greater' => less b < a ? 'less' : 'greater' => greater
Operators8.py
#!/usr/bin/env python3;
import Utils

# Begin Main
sFloat = "3.1415926"
sInt = "3"
sLong = "123456789123456789"
a = Utils.stodWithDefault(sFloat, 0.0)
b = Utils.stoiWithDefault(sInt, 0)
c = Utils.stoiWithDefault(sLong, 0)
strA = str(a)
strB = str(b)
strC = str(c)

print("sFloat as double: {0:f}".format(a))
print("sInt as int: {0:d}".format(b))
print("sLong as long: {0:d}".format(c))
print("a as string: {0:s}".format(strA))
print("b as string: {0:s}".format(strB))
print("c as string: {0:s}".format(strC))

Output
$ python3 Operators8.py sFloat as double: 3.141593 sInt as int: 3 sLong as long: 123456789123456789 a as string: 3.1415926 b as string: 3 c as string: 123456789123456789

Precedence

For simple expressions that contain only one operator, it is easy to see how it will be evaluated. But more complex expressions that contain multiple operators could lead to ambiguity and unpredictable results unless we had some rules in place to help us out. These rules to eliminate ambiguity are the rules of precedence illustrated below. In this table, operators which have higher precedence appear closer to the top. Operators with lower precedence appear closer to the bottom. In a situation where two operators are potentially operating on a value, the operator that is higher in the table takes precedence over a lower operator. If the two operators are on the same level of precedence then the associativity of the operators helps us to determine which takes precedence.

For example, the expression 5 * 3 + 1 could be ambiguous. Without rules of precedence it wouldn't be clear weather the multiplication or the addition should be performed first. If the multiplication takes precedence we would have (5 * 3) + 1 == 16 whereas if the addition takes precedence we would have 5 * (3 + 1) == 20. But we do have rules of precedence so there is only one correct way to interpret that expression. Because multiplication appears in the table on a level above addition, we know that the first interpretation yielding 16 is the correct one. If we instead wanted the expression to be evaluated the second way to yield 20, we would have to use parenthesis to explicitly override the rules of precedence. Many of the rules of precedence come from standard arithmetic and logical notation so they should seem familiar.

Rules of precedence don't guarantee any particular order of evaluation, but they do help resolve issues when two operators are applied to the same value. This subtlty is not obvious because in most expressions there is only one order of evaluation that follows the rules of precedence. Consider (10 - 6) - (3 - 1). At first glance it would appear that the parenthesis cause this expression to be evaluated in only one way. But it turns out that there are two ways to evaluate this expression without violating the rules of precedence, namely to compute (10 - 6) first or to compute (3 - 1) first. So there are two ways to order the evaluation of this expression without violating the rules of precedence. In this case as in most cases, the end result will be the same, but it illustrates that the rules of precedence still leave some leeway in how the computer carries out the evaluation of the expression.

Consider the expression 10 * 6 - 4 / 2. Two of the values have operators on both the left and the right side requiring us to use the rules of precedence. Two values do not. Use parenthesis to show how the rules of precedence require us to interpret this expression.
Answer: ((10 * 6) - (4 / 2)) == (60 - 2) == 58
Note: It is equally correct for (10 * 6) to be evaluated first or for (4 / 2) to be evaluated first. Because the expressions do not have any side effects, the result will be the same either way.

Consider the expression A + B << 2 * 3 & 0xff. Two of the values have operators on both the left and the right side requiring us to use the rules of precedence. Two values do not. Use parenthesis to show how the rules of precedence require us to interpret this expression.
Answer: (((A + B) << (2 * 3)) & 0xff)

Python Operator Rules of Precedence
Operator Description Associativity
() [] {} Tuple, List, Dictionary/SetLeft-to-Right
() [] . Function call, Subscript, Member selectionLeft-to-Right
**ExponentiationRight-to-Left
+ - ~Unary plus and minus, Bitwise complimentN/A
* / // %Multiplication, division, floor division and remainderLeft-to-Right
+ -Addition and subtractionLeft-to-Right
<< >>Bitwise arithmetic left and right shiftLeft-to-Right
&Bitwise ANDLeft-to-Right
^Bitwise XOR (exclusive OR)Left-to-Right
|Bitwise OR (inclusive OR)Left-to-Right
< <=Comparison operators < and ≤Left-to-Right
> >=Comparison operators > and ≥
== !=Equivalence = and ≠
in not inCollection membership
is is notObject identity
notLogical NOTN/A
andLogical ANDLeft-to-Right
orLogical ORLeft-to-Right
if – elseConditional expressionN/A
lambdaLambda expressionN/A

As we have seen, we can use parenthesis to change how an expression is to be interpreted. Using parenthesis can also make an expression easier to read. Adding parenthesis to an equation doesn't incur any performance penalty even if the expression would have been interpreted the desired way without the parenthesis.

TODO: Precision and rounding errors in operations 1/3

Questions

Projects

More ★'s indicate higher difficulty level.

References