Operators ========= .. admonition:: Precap Operators are used for assignments and expressions. They can be divided into the following groups. * `Assignment <#assignment>`__: ``=`` * `Compound assigment <#compound-assignment>`__: ``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=`` * `Arithmetic <#arithmetic>`__: ``+``, ``-``, ``*``, ``/``, ``//``, ``%``, ``**`` * `Comparison <#comparison>`__: ``<``, ``<=``, ``==``, ``>=``, ``>``, ``!=`` * Binary: ``&``, ``|``, ``~``, ``^``, ``<<``, ``>>`` * Identity: ``is``, ``is not`` * Membership: ``in``, ``not in`` Assignment ---------- A single ``=`` sign is used to assign a literal value or expression to its left to a variable to its right. .. interactive_code_block:: :caption: The assignment operator '=' # An assignment with a literal value celsius = 100 print('Water boils at {} degree Celsius.'.format(celsius)) # An assignment with an expression fahrenheit = celsius * 9 / 5 + 32 print('{} degree Celsius equals {} degree Fahrenheit.'.format(celsius, fahrenheit)) # Single values can be assigned to multiple variables in a single statement width = depth = height = 10 print('The volume of the cube is {}.'.format(width * depth * height)) # Multiple values can be assigned to multiple variables in a single statement width, depth, height = 10, 20, 30 print('The volume of the rectangular cuboid is {}.'.format(width * depth * height)) Compound assignment ------------------- Compound assignments are *short versions* of frequent assignments with a simple expression. E.g. ``counter = counter + 1`` can also be written as ``counter += 1``. All arithmetic ``+``, ``-``, ``*``, ``/``, ``//``, ``%``, ``**`` and (almost) all bitwise operators ``&``, ``|``, ``^``, ``<<``, ``>>`` can be used (= all except ``~``). .. interactive_code_block:: :caption: Compound assignment operators counter = 10 # Without a compound assignment a simple expression has to be used to add a value to the value of a variable. counter = counter + 1 print(counter) # Compound operators are short versions for those situations counter += 1 print(counter) # They work with all arithmetic operators counter *= 2 print(counter) # And all bitwise operators except '~' (bitwise NOT) # NOTE: Feel free to ignore the next three statements, if You are not familiar with the binary representation of numbers and the concept of bitwise operations. byte = 0b11110000 byte &= 0b11000011 print(bin(byte)) In some *other* programming languages (e.g. JavaScript or C) an even shorter version for incrementing (= adding 1) and decrementing (= subtracting 1) exists: ``++`` and ``--``. They are called `unary operations `__ and are *not supported* in Python. .. interactive_code_block:: :caption: Unary operators for incrementing or decrementing DO NOT WORK in Python but throw an error counter = 10 # Instead of writing counter += 1 to add the value 1 an even shorter version exists in some other programming languages counter++ print(counter) Arithmetic ---------- Arithmetic operators are most commonly used within basic arithmetic expressions. It's important to know that the data type of the result depends on the data type(s) of the numbers used. There are 3 simple rules to be kept in mind: * If the data type of both numbers is ``int``, then the data type of the result is ``int`` * If the data type of one of the two numbers is ``float``, then the data type of the result is ``float`` And since Python 3: * If the operator is ``/`` (division), then the data type of the result is always ``float`` .. table:: :width: 100% ========= ====================== =============== ======================= ======================= Operator Name Examples Result --------- ---------------------- --------------- ----------------------------------------------- |br| *Python 2* *Python 3* ========= ====================== =============== ======================= ======================= **+** *Addition* 1 + 2 3 3 |br| 1 + 2.0 |br| 3.0 |br| 3.0 **-** *Subtraction* 2 - 3 -1 -1 |br| 2 - 3.0 |br| -1.0 |br| -1.0 **\*** *Multiplication* 3 * 4 12 12 |br| 3 * 4.0 |br| 12.0 |br| 12.0 **/** *Division* 4 / 2 2 2.0 |br| 5 / 3 |br| 1 |br| 1.6666666666666667 |br| 5 / 3.0 |br| 1.6666666666666667 |br| 1.6666666666666667 **//** *Floor division* 5 // 3 1 1 |br| 5 // 3.0 |br| 1.0 |br| 1.0 **%** *Modulo (= remainder)* 5 % 3 2 2 |br| 5 % 3.0 |br| 2.0 |br| 2.0 **\*\*** *Exponentiation* 2 \*\* 3 8 8 |br| 2 \*\* 3.0 |br| 8.0 |br| 8.0 ========= ====================== =============== ======================= ======================= .. interactive_code_block:: :caption: Arithmetic operators with numeric data types 'int' and 'float' in Python 3 # If the data type of both numbers is 'int' the result's data type is also 'int' print(1 + 2, '\\n') # If the data type of one of the two numbers is 'float', then the result's data type is also 'float' print(2 - 3.0, '\\n') # The data type of the result of a division is always 'float' print(4 / 2) print(5 / 3) print(5 / 3.0, '\\n') # The result of a floor division is rounded down print(5 // 3, '\\n') # The result of a modulo operation is the remainder of a division print(5 % 3, '\\n') # Double asterisks are used for exponentiation print(2 ** 3, '\\n') # Instead of the operator '**' the built-in function 'pow()' can be used alternativly print(pow(2, 3)) The two arithmetic operators ``+`` and ``*`` also work with sequence data types. .. interactive_code_block:: :caption: Arithmetic operators with sequence data types 'str', 'tuple', 'list' # Strings, tuples and lists can be concatenated (= joined) with the '+' operator print('Star' + 'fish') # 'str' print(('Time', 'flies') + ('like', 'an', 'arrow')) # 'tuple' print(['Fruit', 'flies'] + ['like', 'a', 'banana'], '\\n') # 'list' # Strings, tuples and lists can be multiplied with the '*' operator print('Beetlejuice! ' * 3) # 'str' print(('Beetlejuice!', ) * 3) # 'tuple' print(['Beetlejuice!'] * 3) # 'list' Comparison ---------- .. table:: :width: 100% ========= ========================== ===================== =========== Operator Name Examples Result ========= ========================== ===================== =========== **<** *Less than* 1 < 1 False |br| 1 < 2 |br| True **<=** *Less than or equal to* 1 <= 1 True |br| 1 <= 2 |br| True **==** *Equal to* 1 == 1 True |br| 1 == 2 |br| False **>=** *Greater than or equal to* 1 >= 1 True |br| 1 >= 2 |br| False **>** *Greater than* 1 > 1 False |br| 1 > 2 |br| False **!=** *Not equal to* 1 != 1 False |br| 1 != 2 |br| True ========= ========================== ===================== =========== .. |br| 1 != 1.0 |br| False |br| 1 == 1.0 |br| True |br| 'Abc' == 'abc' |br| False |br| [1, 2] == [1, 2] |br| True |br| [2, 3] == [3, 2] |br| False |br| 'Abc' != 'abc' |br| True |br| [1, 2] != [1, 2] |br| False |br| [2, 3] != [3, 2] |br| True .. interactive_code_block:: :caption: Comparison operators with numeric data types 'int' and 'float' # The data types 'int' and 'float' can be mixed print(1 == 1) print(1 == 1.0) print(1.0 == 2, '\\n') # Comparison operators can be chained (the next two statements are equivalent) print(1 < 23 < 4.0) print(1 < 23 and 23 < 4.0) .. print('Abc' == 'abc') print([1, 2] == [1, 2]) print([2, 3] == [3, 2], '\\n') # Not equal print(1 != 1) print(1 != 1.0) print(1 != 2) print('Abc' != 'abc') print([1, 2] != [1, 2]) print([2, 3] != [3, 2], '\\n') .. interactive_code_block:: :caption: Comparison operators with sequence data types 'str', 'tuple' and 'list' # String comparisons are case sensitive print('Abc' == 'abc', '\\n') # 'A' > 'a' yields False since the Unicode code points of each letter will be compared print('A' > 'a') print('The Unicode code points for A = {} and a = {}.\\n'.format(ord('A'), ord('a'))) # The Unicode code points are the primary criteria, length is a secondary criteria print('Abcd' > 'abc') print('abcd' > 'abc') .. Assignment ---------- .. table:: :width: 100% ======== ====== ======= Operator Name Example ======== ====== ======= *=* Assign a = 1 ======== ====== =======