Operators#

Clarity in thought, like elegance in mathematics, arises not from abundance but from precision.
β Blaise Pascal
Slides/PDF#
Instructions#
In programming, code is written that has a formal syntax and semantics. This code is formally subdivided into:
A statement (English: statement) is a single directive formulated in the syntax of a programming language that is to be executed sequentially in the program.
An expression (English: expression) is a special form of a statement that always returns a value and thus has a data type.
An operator is a part of expressions and is a symbol or keyword that tells the compiler or interpreter to perform a specific operation on values.
In a simple variable assignment, for example, the expression appears on the right-hand side of the assignment operator and the variable name on the left-hand side, for example:
VariableName = Expression
Arithmetic Operators#
Arithmetic operators perform the standard mathematical operations. They are used with numeric values to perform general mathematical operations.
Operator |
Example |
Effect |
---|---|---|
Addition |
|
|
Subtraction |
|
|
Multiplication |
|
|
Division |
|
|
Integer Division |
|
|
Modulo Operator |
|
|
Exponentiation |
|
|
Assignment Operators#
Assignment operators assign values to variables. Python uses augmented assignment for all arithmetic operations; however, there is no increment or decrement like in other languages.
With the assignment x = y
, the value of the variable y
(right-hand side) is assigned to the variable x
(left-hand side). With short-hand (compound) assignments, an operation is performed on the value of a variable, and this new value is assigned back to the variable.
Operator |
Example |
Effect |
---|---|---|
Assignment |
|
Variable |
Augmented addition |
|
|
Augmented multiplication |
|
|
Augmented division |
|
|
Augmented floor division |
|
|
Augmented modulo |
|
|
Use of Assignment and Arithmetic Operators#
Operators are used in programming languages to combine two or more values or variables. The arithmetic operators *, -, *, /
from mathematics are also available in Python.
a = 1 + 1
print(a)
2
The operations work just as well with variables or mixed.
a = a + 1
print(a)
3
In this example, the first input variable a
is identical to the result variable. In this case, Python also offers the shorthand where the operator precedes the assignment operator =
.
a += 1
print(a)
4
a *= 2
print(a)
8
Here, parentheses also determine the order of operations, just as in mathematics, and can affect the result. Thus, are the following two expressions not identical:
c1 = (6 + a) * (-2)
print(c1)
-28
c2 = 6 + a * -2
print(c2)
-10
Comparison Operators#
Comparison operators compare two values and return true or false as a result. For example, a == b
tests whether a
is equal to b
, and returns true or false accordingly, while a != b
tests whether a
is not equal to b
.
Comparison operators compare two variables/values, and the result is evaluated as true or false.
With the assignment x = y
, the value of the variable y
(right-hand side) is assigned to the variable x
(left-hand side). For shorthand/compound assignments, an operation is performed on the value of a variable, and this new value is reassigned to the variable.
Operator |
Example |
Effect |
---|---|---|
Equals |
|
true if |
Not equal |
|
true if |
Greater than |
|
true if |
Less than |
|
true if |
Greater than or equal to |
|
true if |
Less than or equal to |
|
true if |
Identity Operators#
Identity operators compare objects. For example, if x = [1, 2, 3]
holds, i.e., x
is a list, then type(x) is list
evaluates to true, and type(x) is not list
is false. They check whether two objects refer to the same memory location. x is y
returns true when both variables refer to the same object, i.e., point to the same memory location.
Operator |
Example |
Effect |
---|---|---|
Is |
|
true if both variables refer to the same object. |
Is not |
|
true if the variables do not refer to the same object. |
Logical Operators#
Logical operators combine boolean expressions, which are then evaluated as true or false. For example, here the variable is_teenager = (alter > 13) and (alter < 19)
is evaluated as true when the value of the variable alter is equal to 14.
P
and Q
stand for logical expressions, e.g. P = (x > 10)
and Q = (x < 20)
.
Operator |
Example |
Effect |
---|---|---|
Logical AND |
|
Returns true (1) if both expressions |
Logical OR |
|
Returns true (1) if either expression |
Logical NOT |
|
Negates the expression |
Applications of Comparison and Logical Operators#
To determine if two variables have equal values, in most programming languages you do not use the equals sign =
, since it is typically defined there as the assignment operator (and would thus overwrite the first variable). In Python, therefore a double equals sign ==
is used (mathematically for exactly the same). In our example, c1
is not equal to c2
, so the following statement is false.
c1 == c2
False
In Python, the !=
operator is used for inequality.
c1 != c2
True
Also the mathematical operators for less than <
, less than or equal to β€
, greater than <
, and greater than or equal to β₯
are supported.
c1 < c2
True
c1 <= c2
True
c1 > c2
False
c1 >= c2
False
Boolean (logical) values in Python are not combined using the usual operators for AND &
, OR |
, NOT ~
, but are written out as and
, or
, not
. The greater-than-or-equal-to β₯
is, for example, identical to the condition
c1 > c2 or c1 == c2
False
Bitwise Operators#
Bitwise operators perform bitwise operations on integer operands. In other words, the operands are converted to their binary representations, e.g., x = 5 = 0101
, y = 3 = 0011
, and then each bit in operand x
is combined with the bit at the corresponding position in operand y
.
Operator |
Example |
Effect |
---|---|---|
Bitwise AND |
|
The resulting bit is 1 if both bits are 1. |
Bitwise OR |
`x |
y` |
Bitwise XOR (Exclusive OR) |
|
The resulting bit is 1 if exactly one of the bits is 1. |
Bitwise NOT |
|
Returns the oneβs complement of |
Right shift |
|
The bits in |
Left shift |
|
The bits in |
The usual logical operators AND &
, OR |
, and XOR ^
are reserved for bitwise operations. These are used only very rarely, in certain calculations or for masking.
a = 10 # binary 1010
b = 4 # binary 0100
c = a & b
print(c) # binary 0000
0
c = a | b
print(c) # binary 1110
14
With the left-shift <<
and right-shift operators >>
, very fast calculations can also be performed. For example, multiplying by 4 is a left shift by 2, while dividing by 4 is a right shift by 2. This is used internally by compilers to optimize calculations.
c = a << 2
print(c)
40
d = c >> 2
print(d)
10
Operator Overloading#
The arithmetic operators +
and -
are in Python overloaded, i.e., you can also apply them to non-numeric data types. To concatenate multiple strings, for example you can write:
sentence = "Der "+ "Ball " + "ist " + "rund."
print(sentence)
Der Ball ist rund.
This also works for lists.
list1 = [1,2,3]
list2 = [2,3,4]
list12 = list1 + list2
print(list12)
[1, 2, 3, 2, 3, 4]
or as set difference.
set1 = {1, 2, 3}
set2 = {2, 3, 4}
set12 = set1 - set2
print(set12)
{1}
Furthermore, in Python both operands must always have the same data type. As in Java or JavaScript, you cannot combine a string and a number; you must first convert the number to a string (casting).
"Der Wert ist " + 1 # doesn't work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[22], line 1
----> 1 "Der Wert ist " + 1 # doesn't work
TypeError: can only concatenate str (not "int") to str
"Der Wert ist " + str(1) # works
'Der Wert ist 1'
This is because certain statements would otherwise be ambiguous. Here it is unclear whether the result should be a string or a number.
"1" + 1 # does not work
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[24], line 1
----> 1 "1" + 1 # does not work
TypeError: can only concatenate str (not "int") to str
Casting the values to the correct type makes the statement unambiguous.
int("1") + 1 # works
2
Membership operators#
Membership operators check whether an object is a member of a list, e.g., 4 in [1,2,3]
checks whether 4 is contained in the list.
x
here stands for an arbitrary object, and list
for a collection.
Operator |
Example |
Effect |
---|---|---|
in |
|
True if x is in the list |
not in |
|
True if x is not in the list |
Tips for Use#
Mathematical operators also have a shorthand form that can appear before the assignment operator =
: e.g., a += 1
corresponds to a = a + 1
, and a *= 2
is equivalent to a = a*2
.
i = 1
i *= 2
i *= 3
i # 6
6
Logical operations usually work as expected. In particular, >
, <
, >=
, and <=
. As in many other languages, equality is tested with the double equals sign ==
. Inequality can be tested with !=
, and the logical negation is not
:
a = 1
a > 1 # False
a >= 1 # True
a == 1 # True
a != 1 # False
not a == 1 # False
False
Python also supports somewhat less common, yet extremely practical reusable comparison operations, for example
0 < a < 2 # true
True