Operators#

Midjourney: Caligraphic Equations

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:

πŸ“˜ Definition: Statement

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.

πŸ“˜ Definition: Expressions

An expression (English: expression) is a special form of a statement that always returns a value and thus has a data type.

πŸ“˜ Definition: Operator

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

x + y

10 + 3 (Result: 13)

Subtraction

x - y

10 - 3 (Result: 7)

Multiplication

x * y

10 * 3 (Result: 30)

Division

x / y

10 / 3 (Result: 3.33)

Integer Division

x // y

10 // 3 (Result: 3)

Modulo Operator

x % y

10 % 3 (Result: 1)

Exponentiation

x ** y

10 ** 3 (Result: 1000)

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

x = y

Variable x receives the value y

Augmented addition

x += 4

x = x + 4 # Variable x is increased by 4

Augmented multiplication

x *= 4

x = x * 4 # Variable x is multiplied by 4

Augmented division

x /= 4

x = x / 4 # Variable x is divided by 4

Augmented floor division

x //= 4

x = x // 4 # Variable x is floor-divided by 4

Augmented modulo

x %= 4

x = x % 4 # The remainder of dividing variable x by 4

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

x == y

true if x is equal to y

Not equal

x != y

true if x is not equal to y

Greater than

x > y

true if x is greater than y

Less than

x < y

true if x is less than y

Greater than or equal to

x >= y

true if x is greater than or equal to y

Less than or equal to

x <= y

true if x is less than or equal to y

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

x is y

true if both variables refer to the same object.

Is not

x is not y

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

P and Q

Returns true (1) if both expressions P and Q are true.

Logical OR

P or Q

Returns true (1) if either expression P or Q is true.

Logical NOT

not P

Negates the expression P: true becomes false, false becomes true.

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

x & y

The resulting bit is 1 if both bits are 1.

Bitwise OR

`x

y`

Bitwise XOR (Exclusive OR)

x ^ y

The resulting bit is 1 if exactly one of the bits is 1.

Bitwise NOT

~x

Returns the one’s complement of x.

Right shift

x >> n

The bits in x are shifted to the right by n positions.

Left shift

x << n

The bits in x are shifted to the left by n positions.

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}
⚠️ Attention: It should be noted that operators change their semantic meaning depending on which data types are combined. For example, the addition of two strings `str` is formally a `concat` into a new string. For lists, `+` means copying the first list into a new one, which is then expanded with the contents of the next list using `expand`. For both, the subtraction operator `-` is not defined. For a set, `+` is not defined, but `-` is used to determine the difference (set difference).

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

x in list

True if x is in the list list.

not in

x not in list

True if x is not in the list 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

Quiz#

--- shuffleQuestions: true shuffleAnswers: true --- ### What are Binary Numbers? > Multiple answers are possible. Binary derives from binarius, which translates to "twofold" or "double." This is about numbers. - [x] The smallest possible (useful) system of symbols - [x] Possible representations of binary code - [x] A numeral system that consists only of 1 and 0 - [x] In some programming languages with the truth values "False" (0) and "True" (1) > Binary numbers are a numeral system with only the digits 0 and 1 and thus the smallest possible numeral system. In programming languages they are often used as representations of binary code and expressed by the truth values "False" (0) and "True" (1). ### What is Binary Code? > Binary derives from binarius, meaning twofold/double. This is about code. - [x] A code that can be represented by binary numbers - [x] A code that can be represented by boolean values (True/False) > A binary code is a code in which information is represented by sequences of two different symbols (for example 1/0 or True/False). - [x] Machine code of a computer program - [ ] A numeral system with 10 symbols (0 to 9) - [ ] A representation of text in natural language - [ ] A representation of graphic files ### What is the AND Operation? What is the result of the operation for the following input combinations on A and B? <br> ![AND table](../_images/03a_Operatoren/Logic_AND.svg) > Translated as the AND operation and behaves like the AND in propositional logic. 1. [x] False (0), False (0) (0), False (0) (0), True (0) > The AND operation (AND operation) is a fundamental logical operation in digital electronics and Boolean algebra. The AND operation yields "1" (True) as a result when both input signals are "1." Otherwise it yields "0" (False). 1. [ ] False (0), True (0), True (0), True (0) 1. [ ] False (0), True (0), True (0), False (0) 1. [ ] True (0), True (0), True (0), False (0) ### What is the OR Operation? What is the result of the operation for the following input combinations on A and B? <br> ![OR table](../_images/03a_Operatoren/Logic_OR.svg) > Translated as the OR operation and behaves like the OR in propositional logic. 1. [ ] False (0), False (0) (0), False (0) (0), True (0) 1. [x] False (0), True (0), True (0), True (0) > The OR operation (OR operation) is a fundamental logical operation in Boolean algebra and digital technology. The OR operation yields the result "1" (True) when at least one of the input signals is "1." It yields "0" (False) when both input signals are "0." 1. [ ] False (0), True (0), True (0), Falsch (0) 1. [ ] True (0), True (0), True (0), Falsch (0) 1. [ ] True (0), False (0) (0), False (0) (0), False (0) ### What is the XOR Operation? What is the result of the operation for the following input combinations on A and B? <br> ![XOR table](../_images/03a_Operatoren/Logic_XOR.svg) > Translated as the Exclusive OR operation and corresponds exclusively to the One or the Other in propositional logic. 1. [ ] False (0), False (0) (0), False (0) (0), True (0) 1. [ ] False (0), True (0), True (0), True (0) 1. [x] False (0), True (0), True (0), False (0) > The XOR operation (Exclusive OR operation) is another fundamental logical operation in Boolean algebra and digital technology. In contrast to the OR operation, which yields True (1) when at least one input signal is True, the XOR operation only yields True when exactly one input signal is True. If both input signals are True or both are False, the XOR operation yields False. 1. [ ] True (0), True (0), True (0), False (0) 1. [ ] True (0), False (0) (0), False (0) (0), False (0) ### What is the NOT Operation? What is the result of the operation for the following input sequence on A? <br> ![NOT table](../_images/03a_Operatoren/Logic_NOT.svg) > Translated as the NOT operation and corresponds to negation. 1. [ ] False (0), False (0) 1. [ ] False (0), True (0) 1. [x] True (0), False (0) > The NOT operation (also called "NOT operation" or "inversion operation") is a fundamental logical operation in Boolean algebra and digital technology. The NOT operation inverts the state of the input signal. If "A" is True (1), then "NOT A" is False (0), and if "A" is False (0), then "NOT A" is True (1). 1. [ ] True (0), True (0) ### What is the NAND Operation? What is the result of the operation for the following input combinations on A and B? <br> ![NAND table](../_images/03a_Operatoren/Logic_NAND.svg) > Corresponds to the negated AND operation. 1. [ ] False (0), False (0) (0), False (0) (0), True (0) 1. [ ] False (0), True (0), True (0), True (0) 1. [ ] False (0), True (0), True (0), False (0) 1. [x] True (0), True (0), True (0), False (0) > The NAND operation is a fundamental logical operation in Boolean algebra and digital technology. The name "NAND" stands for "NOT AND," which indicates that the NAND operation is a combination of the AND operation and the NOT operation and outputs the opposite of the result of the AND operation. The NAND operation yields "1" (True), unless both input signals are "1." In that case it yields "0" (False). 1. [ ] True (0), False (0) (0), False (0) (0), False (0) ### What is the NOR Operation? What is the result of the operation for the following input combinations on A and B? <br> ![NOR table](../_images/03a_Operatoren/Logic_NOR.svg) > Translates to the negated OR operation. 1. [ ] False (0), False (0) (0), False (0) (0), True (0) 1. [ ] False (0), True (0), True (0), True (0) 1. [ ] False (0), True (0), True (0), Falsch (0) 1. [ ] True (0), True (0), True (0), Falsch (0) 1. [x] True (0), False (0) (0), Falsch (0) (0), Falsch (0) > The NOR operation is a fundamental logical operation in Boolean algebra and digital technology. The name "NOR" stands for "NOT OR," which indicates that the NOR operation is a combination of the OR operation and the NOT operation and is the opposite of the result of the OR operation. The NAND operation yields "1" (True), unless both input signals are "1." In this case it yields "0" (False). ### What is the XNOR Operation? What is the result of the operation for the following input combinations on A and B? <br> ![XNOR table](../_images/03a_Operatoren/Logic_XNOR.svg) > Translates to the negated Exclusive OR operation. 1. [ ] False (0), False (0) (0), False (0) (0), True (0) 1. [ ] False (0), True (0), True (0), True (0) 1. [ ] False (0), True (0), True (0), Falsch (0) 1. [ ] True (0), True (0), True (0), Falsch (0) 1. [x] True (0), False (0) (0), Falsch (0) (0), True (0) > The XNOR operation (also known as the equivalence operation) is a logical operation in Boolean algebra and digital technology. The name "XNOR" stands for "NOT XOR" and indicates that it is a combination of the XOR operation and the NOT operation and yields the opposite of the XOR result. The XNOR operation yields "1" (True) when both input signals are the same (either both "0" or both "1"). It yields "0" (False) when the input signals are different (one "0" and the other "1"). ### How do you combine multiple logical conditions in Python? - [x] With `AND`, `OR`, `NOT` - [ ] With `&&`, `||`, `!` - [ ] With `+`, `-`, `*` - [ ] With `COMBINE`, `MERGE`, `JOIN` - [ ] With `IF`, `ELSE`, `THEN`