Operations
Operations
▪ None, bool
▪ basic operations
▪ strings
▪ += and friends
NoneType
▪ The type None has only one value: None
Type bool
▪ The type bool only has two values: True and False
"string"[3] = "i"
[2, 5, 6, 7][2] = 6
Questions – What is [7,3,5][[1,2,3][1]] ?
a) 1
b) 2
c) 3
d) 5
e) 7
f) Don’t know
Operations on int and float
Result is float if and only if at least one argument is float,
except ** with negative exponent always gives a float
▪ +, -, * addition multiplication, e.g. 3.0*2 = 6.0
▪ ** and pow(x, y) power, e.g. 2**3=pow(2,3)=8, 2**-2=0.25
▪ // integer division = x / y Python shell
e.g. 15.0//4= 3.0. Note: -8//3=-3 > 0.4 // 0.1
| 4.0
▪ / division returns float, 6/3=2.0 > 0.4 / 0.1
| 4.0
▪ abs(x) absolute value > 0.3 // 0.1
| 2.0
▪ % integer division remainder (modulo) > 0.3 / 0.1
| 2.9999999999999996
11%3 =2 > 10**1000 / 2
4.7%0.6=0.5000000000000003 | OverflowError: integer division
result too large for a float
Running time for 3 ** x // 3 ** x
for i in range(42):
x = 3 ** i // 2 ** i
start = time()
result = 3 ** x // 3 ** x # the computation we time
end = time()
t = end - start
print('i =', i, 'x =', x, 'Result =', result, 'time(sec) =', t)
bits.append(x)
compute_time.append(t)
sqrt, sin, cos, tan, asin, acos, atan, log(natural), log10, exp, ceil, floor, ...
▪ To use all the functions from the math module use import math
Functions are now available as e.g. math.sqrt(10) and math.ceil(7.2)
▪ To import selected functions you instead write from math import sqrt, ceil
▪ The library also contains some constants, e.g.
math.pi = 3.141592... and math.e = 2.718281... Python shell
> (0.1 + 0.2) * 10
▪ Note: x ** 0.5 significantly faster than sqrt(x) | 3.0000000000000004
> math.ceil((0.1 + 0.2) * 10)
| 4
docs.python.org/3/library/math.html
module statistics contains basic functions like mean and variance, see docs.python.org/3/library/statistics.html
Python shell
> import math
> math.sqrt(8)
| 2.8284271247461903
> from math import pi, sqrt
> pi
| 3.141592653589793
> sqrt(5)
| 2.23606797749979
> from math import sqrt as kvadratrod
> kvadratrod(3)
| 1.7320508075688772
> import timeit
> timeit.timeit("1e10**0.5")
| 0.021124736888936863
> timeit.timeit("sqrt(1e10)", "from math import sqrt")
| 0.1366314052865789
> timeit.timeit("math.sqrt(1e10)", "import math")
| 0.1946660841634582
docs.python.org/3.6/library/timeit.html
Rounding up Python shell
> from math import ceil
integer fractions > from timeit import timeit
> 13 / 3
▪ Python: ⸢x/y⸣ = -(-x//y) | 4.333333333333333
> 13 // 3
-(-13/3) |4
Python Java C > -13 // 3
| -5
-(-13//3) -(-13/3) -(-13/3) > -(-13 // 3)
= 5 = 4 = 4 |5
> ceil(13 / 3)
|5
> -(-22222222222222222223 // 2)
▪ The intermediate result x/y in | 11111111111111111112
math.ceil(x/y) > ceil(22222222222222222223 / 2)
| 11111111111111110656
is a float with limited precision
> timeit('ceil(13 / 3)', 'from math import ceil')
▪ Alternative computation: | 0.2774667127609973
> timeit('-(-13 // 3)') # negation trick is fast
⸢x/y⸣ = (x+(y-1))//y | 0.05231945830200857
floats : Overflow, inf, -inf, nan Python shell
> 1e250 ** 2
| OverflowError:
(34, 'Result too large')
▪ There exists special float values > 1e250 * 1e250
inf, -inf, nan | inf
representing “+infinity”, “-infinity” and > -1e250 * 1e250
| -inf
“not a number” > import math
> math.inf
▪ Can be created using e.g. | inf
float('inf') > type(math.inf)
or imported from the math module | <class 'float'>
> math.inf / math.inf
▪ Some overflow operations generate an | nan
> type(math.nan)
OverflowError, other return inf | <class 'float'>
and allow calculations to continue ! > math.nan == math.nan
| False
▪ Read the IEEE 754 standard if you want to > float('inf') - float('inf')
know more details... | nan
Operations on bool
▪ The operations and, or, and not behave as expected when the arguments are False/True.
▪ The three operators also accept other types, where the following values are considered false:
(see The Python Standard Library > Built-in Types > True Value Testing for more false values)
▪ Short-circuit evaluation: The rightmost argument of and and or is only evaluated if the result
cannot be determined from the leftmost argument alone. The result is either the leftmost or
rightmost argument (see truth tables), i.e. the result is not necessarily False/True.
True or 7/0 is completely valid since 7/0 will never be evaluated
(which otherwise would throw a ZeroDivisionError exception)
x x or y x x and y x not x
false y false x false True
otherwise x otherwise y otherwise False
Questions – What is "abc" and 42 ?
a) False
b) True
c) "abc"
d) 42
e) TypeError
f) Don’t know
Comparison operators (e.g. int, float, str)
Python shell
> 3 == 7
== test if two objects are equal, returns bool | False
> 3 == 3.0
not to be confused with the assignment | True
operator (=) > "-1" != -1
| True
!= not equal > "abc" == "ab" + "c"
| True
> > 2 <= 5
| True
>= > -5 > 5
< | False
> 1 == 1.0
<= | True
> 1 == 1.0000000000000001
| True
> 1 == 1.000000000000001
| False
Chained comparisons
▪ A recurring condition is often
x < y and y < z
▪ If y is a more complex expression, we would like to avoid computing y twice, i.e. we often
would write
tmp = complex expression
x < tmp and tmp < z
▪ In Python this can be written as a chained comparisons (which is shorthand for the above)
x < y < z
a) True
b) False
c) 0
d) 1
e) 6
f) ZeroDivisionError
g) Don’t know
Binary numbers and operations
▪ Binary number = integer written in base 2: 1010102 = 4210
s = 'abwwdexy___lwtopavghevt_xypxxyattx_hxwoadnxxx'
a) 'wwdexy___lwtopavghevt_xypxxyattx_hxwoadn'
b) 'we_love_python'
c) 'we_love_java'
d) Don’t know
Strings are immutable
▪ Strings are non-scalar, i.e. for s = "abcdef", s[3] will return "d"
▪ Strings are immutable and cannot be changed once created.
I.e. the following natural update is not possible (but is e.g. allowed in C)
s[3] = "x"
▪ To replace the "d" with "x" in s, instead create the new string
s = s[:3] + "x" + s[4:]
Precedence
Operators (low to high)
or
Precedence rules & Associativity and
not x
Example: * has higher precedence than + in not in
is is not
2 + 3 * 4 ≡ 2 + (3 * 4) → 14 and (2 + 3) * 4 → 20 == < <=
!= > >=
All operators in same group are evaluated left-to-right
|
2 + 3 - 4 - 5 ≡ ((2 + 3) - 4) - 5 → -4 ^
&
except for **, that is evaluated right-to-left
<< >>
2**2**3 ≡ 2**(2**3) → 256 + -
* @
Rule: Use parenthesis whenever in doubt of precedence! / // %
+x -x ~x
docs.python.org/3/reference/expressions.html **
Long expressions
▪ Long expressions can be broken over several Python shell
lines by putting parenthesis around it > (1
+ 2 +
▪ The PEP8 guidelines recommend to limit all 3)
lines to a maximum of 79 characters |6
https://www.python.org/dev/peps/pep-0008/#maximum-line-length
+= and friends
▪ Recurring statement is
x = x + value