4 Operators
October 7, 2014
Figure 1: BY-SA
1 Operators
Operators are special symbols that represent computations like addition and multiplication. The values
the operator uses are called operands.
1.1 Arithmetic operators
The base arithmetic operations are:
• Add: +
• Substract: -
• Multiply: *
• Divide: /
• Integer Division: //
• Reminder of an integer division: %
• Power: **
• Modulo: % (division reminder)
As a first step, let’s revise the result of the arithmetic present operations with integer numbers. First we
will define two variables:
In [1]: x = 10
y = 20
The results of the following operations are:
In [2]: print("Add {}+{}: {}".format(x, y, x+y))
print("Substract {}-{}: {}".format(x, y, x-y))
print("Multiply {}*{}: {}".format(x, y, x*y))
print("Division {}/{}: {}".format(x, y, x/y))
print("Power {}**{}: {}".format(x, y, x**y))
print("Integer division {}//{}: {}".format(x, y, x//y))
print("Modulo {}%{}: {}".format(x, y, x%y))
1
Add 10+20: 30
Substract 10-20: -10
Multiply 10*20: 200
Division 10/20: 0.5
Power 10**20: 100000000000000000000
Integer division 10//20: 0
Modulo 10%20: 10
We revise the diference between the standard division and integer divisions:
In [3]: x = 9
y = 2
print(x/y)
4.5
In the first case, the division / gives a result with decimal numbers.
In the second case:
In [4]: print(x//y)
The result has no decimals, but we can request the reminder using the modulo operation.
In [5]: print(x%y)
Since Python 3.x, the division always provides floating point or decimal results. It is important taking
into account that this result is specific from Python 3.x. In previous versions and other languages, the
division usually provides an integer result.
In other words, the result of the division depends on the language. √
1
Exercise: Having in mind that the square root can be written as x ≡ x 2 , try to calculate the second
degree equation roots:
ax2 + bx + c = 0
Roots:
√
−b+ b2 −4ac
x1 = √2a
−b− b2 −4ac
x2 = 2a
In [6]: # Create the variables
a=3.
b=2.
c=5.
# A test of the fractionary exponent:
print(c**(1/2))
2.23606797749979
2
Note: Another option is to implement the quadratic solution using the formulas:
√
q ≡ − 12 b + sgn(b) b2 − 4ac
x1 = aq
x2 = qc
This solution ensures stability when using floating point numbers.
1.2 Bit level operators
This operators work at bit level. Usually they are only used in interface and communication programs. In
some cases, they are also used in scientific programs.
• and: &
• or: |
• xor: ˆ
• not: ˜
• Shift left: <<
• Shift right: >>
1.2.1 And: calculates the logic “and” bit by bit
Op. Res.
0&0 =0
0&1 =0
1&0 =0
1&1 =1
In [7]: a = 1
b = 1
c = 2
print ("{} & {} = {}".format(bin(a), bin(b), bin(a&b)))
print ("{} & {} = {}".format(bin(a), bin(c), bin(a&c)))
0b1 & 0b1 = 0b1
0b1 & 0b10 = 0b0
1.2.2 Or: calculates the logic “or” bit by bit
Op. Res.
0|0 =0
0|1 =1
1|0 =1
1|1 =1
3
In [8]: a = 1 # 00000001
b = 1 # 00000001
c = 2 # 00000010
print ("{} | {} = {}".format(bin(a), bin(b), bin(a|b)))
print ("{} | {} = {}".format(bin(a), bin(c), bin(a|c)))
0b1 | 0b1 = 0b1
0b1 | 0b10 = 0b11
1.2.3 Xor: calculates the logic “exclusive or” bit by bit
Op. Res.
0ˆ0 =0
0ˆ1 =1
1ˆ0 =1
1ˆ1 =0
In [9]: a = 1
b = 1
c = 2
print ("{} ^ {} = {}".format(bin(a), bin(b), bin(a^b)))
print ("{} ^ {} = {}".format(bin(a), bin(c), bin(a^c)))
0b1 ^ 0b1 = 0b0
0b1 ^ 0b10 = 0b11
1.2.4 Not: negates the bits, also known as one’s complement
Op. Res.
˜0 =1
˜1 =0
In [10]: a = 1
b = 2
print ("~{} = {}".format(bin(a), bin(~a)))
print ("~{} = {}".format(bin(b), bin(~b)))
~0b1 = -0b10
~0b10 = -0b11
Remark: The negative sign before the 0b indicates that all the upper bits are 1. This is due to the
two’s complement coding.
4
1.2.5 Shift: the bits are shifted from right to left or vice versa
The bits that go to negative indexes are lost.
In [11]: a = 1
b = 2
print ("~{} << 1 = {}".format(bin(a), bin(a << 1)))
print ("~{} >> 1 = {}".format(bin(a), bin(a >> 1)))
print ("~{} << 1 = {}".format(bin(b), bin(b << 1)))
print ("~{} >> 1 = {}".format(bin(b), bin(b >> 1)))
~0b1 << 1 = 0b10
~0b1 >> 1 = 0b0
~0b10 << 1 = 0b100
~0b10 >> 1 = 0b1
• A left shift by n bits is equivalent to multiplication by 2n without overflow check.
• A right shift by n bits is equivalent to division by 2n without overflow check.
1.3 Operations on strings
Mathematical operations can not be applied on strings, even if the strings look like numbers:
In [12]: message = ’String’
print(message-1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-4b0ce0a10aa9> in <module>()
1 message = ’String’
2
----> 3 print(message-1)
TypeError: unsupported operand type(s) for -: ’str’ and ’int’
In [13]: print(’Hello’/123)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-49647fe75952> in <module>()
----> 1 print(’Hello’/123)
TypeError: unsupported operand type(s) for /: ’str’ and ’int’
In [14]: print(message*’Hello’)
5
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-e0b0b4a507e7> in <module>()
----> 1 print(message*’Hello’)
TypeError: can’t multiply sequence by non-int of type ’str’
In [15]: print(’15’+2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-15-a1c17c36f832> in <module>()
----> 1 print(’15’+2)
TypeError: Can’t convert ’int’ object to str implicitly
The + operator does work with strings, it represents concatenation, which means joining the two operands
by linking them end-to-end. For example:
In [16]: fruit = ’banana’
bakedGood = ’ nut bread’
print(fruit + bakedGood)
banana nut bread
The space before the word nut is part of the string, and is necessary to produce the space between the
concatenated strings.
The * operator also works on strings; it performs repetition.
In [17]: ’Fun’*3
Out[17]: ’FunFunFun’
This interpretation of + and * makes sense by analogy with addition and multiplication. Just as 43 is
equivalent to 4+4+4, we expect ’Fun’ 3 to be the same as ’Fun’+’Fun’+’Fun’.
1.4 Relational
The relational operators define when two elements are equal, unequal or its relationship in terms of greatness
or smallness:
• x == y ⇒ x is equal to y
• x != y ⇒ x is not equal to y
• x > y ⇒ x is greater than y
• x < y ⇒ x is less than y
• x >= y ⇒ x is greater than or equal to y
• x <= y ⇒ x is less than or equal to y
6
In [18]: print(3 > 4)
False
In [19]: print(4 != 5)
True
1.5 Boolean operators
The logical operators are also available:
• and
• or
• not
In [20]: x = True
print(x and False)
False
In [21]: print(x or False)
True
The following values are considered false:
• None
• False
• zero of any numeric type, for example, 0, 0.0, 0j.
• Any empty sequence, for example, ”.
• Any empty container
All other values are considered true — so objects of many types are always true.
• x or y: if x is false, then y, else x
• x and y: if x is false, then x, else y
• not x: if x is false, then True, else False
Notes:
or is a short-circuit operator, so it only evaluates the second argument if the first one is False.
and is a short-circuit operator, so it only evaluates the second argument if the first one is True.
not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and
a == not b is a syntax error.
In [22]: x = 5
print(x and 0)
In [23]: print(x and 7)
7
In [24]: print(x or 7)
In [25]: print(not 8)
False
In [26]: print(not 0)
True
Though many objects can be used with the boolean operators, it is recommended to use the boolean
types to make the comparisons and minimize the possible errors.