Commit 3f7d1271 authored by Loic Huder's avatar Loic Huder
Browse files

Added a link to Python doc for floating point arithmetics

parent 28ca6ad1
Pipeline #32790 passed with stage
in 1 minute and 2 seconds
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Python training UGA 2017 # Python training UGA 2017
**A training to acquire strong basis in Python to use it efficiently** **A training to acquire strong basis in Python to use it efficiently**
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre) Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# Standard types and basic statements # Standard types and basic statements
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Function calls ## Function calls
There are [built-in functions](https://docs.python.org/3/library/functions.html) and the developers can of course define other functions. To call a function: There are [built-in functions](https://docs.python.org/3/library/functions.html) and the developers can of course define other functions. To call a function:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print("hello") print("hello")
``` ```
%% Output %% Output
hello hello
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Some functions return a result. Some functions return a result.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
round(1.2) round(1.2)
``` ```
%% Output %% Output
1 1
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
It's common to store the result in a variable: It's common to store the result in a variable:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
my_var = round(1.2) my_var = round(1.2)
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
which can then be used: which can then be used:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(my_var) print(my_var)
``` ```
%% Output %% Output
1 1
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Few standard types ## Few standard types
- Simple types (`int`, `float`, `bool`, `complex`) - Simple types (`int`, `float`, `bool`, `complex`)
- Standard type `str` - Standard type `str`
- Standard type `list` - Standard type `list`
- Standard type `tuple` - Standard type `tuple`
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### `int` (integers) ### `int` (integers)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 4 a = 4
c = -10 c = -10
# binary notation (base 2) # binary notation (base 2)
b = 0b010 b = 0b010
# octal notation (base 8) # octal notation (base 8)
o = 0o011 o = 0o011
# hexadecimal (base 16) # hexadecimal (base 16)
h = 0x1cf0 h = 0x1cf0
a = int('1') # base 10 a = int('1') # base 10
a = int('111', 2) # base 2 a = int('111', 2) # base 2
a = int('70', 8) # base 8 a = int('70', 8) # base 8
a = int('16', 16) # base 16 a = int('16', 16) # base 16
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Remark: `int` in Python 3 are impressive! No limit! See https://docs.python.org/3.1/whatsnew/3.0.html#integers Remark: `int` in Python 3 are impressive! No limit! See https://docs.python.org/3.1/whatsnew/3.0.html#integers
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Arithmetic operations ## Arithmetic operations
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(10 + 3) print(10 + 3)
print(10 - 3) print(10 - 3)
print(10 * 3) print(10 * 3)
print(10 / 3) # float division print(10 / 3) # float division
print(10 // 3) # integer division print(10 // 3) # integer division
print(10 % 3) print(10 % 3)
``` ```
%% Output %% Output
13 13
7 7
30 30
3.3333333333333335 3.3333333333333335
3 3
1 1
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### `bool` (booleans) ### `bool` (booleans)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
b = bool('1') b = bool('1')
b = False b = False
b = True b = True
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
##### Comparison operations (bool) ##### Comparison operations (bool)
- `==` equal - `==` equal
- `!=` différent - `!=` différent
- `<` inferior - `<` inferior
- `<=` inferior or equal - `<=` inferior or equal
- `>` superior - `>` superior
- `>=` superior or equal - `>=` superior or equal
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
##### Keyword `is`: check identity ##### Keyword `is`: check identity
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = None a = None
print(a is None) print(a is None)
print(a is not None) print(a is not None)
``` ```
%% Output %% Output
True True
False False
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
##### Keywords `and` and `or` ##### Keywords `and` and `or`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
True and True True and True
``` ```
%% Output %% Output
True True
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
True and False True and False
``` ```
%% Output %% Output
False False
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
False and False False and False
``` ```
%% Output %% Output
False False
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
True or True True or True
``` ```
%% Output %% Output
True True
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
True or False True or False
``` ```
%% Output %% Output
True True
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
False or False False or False
``` ```
%% Output %% Output
False False
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### `float` (real, double precision) and `complex` ### `float` (real, double precision) and `complex`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# float # float
a = float('1') a = float('1')
a = 1.234 a = 1.234
a = 1e2 a = 1e2
a = -1e-2 a = -1e-2
a = .2 a = .2
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# complex (2 floats) # complex (2 floats)
c = complex('1') c = complex('1')
c = 1 + 2j c = 1 + 2j
print(c, c.real, c.imag) print(c, c.real, c.imag)
``` ```
%% Output %% Output
(1+2j) 1.0 2.0 (1+2j) 1.0 2.0
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Remark: notation `var_name.attr_name` to access to an attribute of an object. Remark: notation `var_name.attr_name` to access to an attribute of an object.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Warning about floating-point arithmetic and numerical errors! ## Warning about floating-point arithmetic and numerical errors!
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
b = 1e16 b = 1e16
c = 1.2 + b c = 1.2 + b
d = c - b d = c - b
print(d) print(d)
``` ```
%% Output %% Output
2.0 2.0
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Very general issue (not Python): Very general issue (not Python):
see https://en.wikipedia.org/wiki/Floating-point_arithmetic See https://en.wikipedia.org/wiki/Floating-point_arithmetic and https://docs.python.org/3/tutorial/floatingpoint.html
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Standard type `str` ### Standard type `str`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'hello' s = 'hello'
s = "hello" s = "hello"
s = ('How is it possible to write a very very ' s = ('How is it possible to write a very very '
'very long string with lines limited to 79 characters?') 'very long string with lines limited to 79 characters?')
s = """Strings on s = """Strings on
more thand more thand
one line. one line.
""" """
print(s) print(s)
``` ```
%% Output %% Output
Strings on Strings on
more thand more thand
one line. one line.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Warning: big difference between Python 2 and Python 3. In Python 3, `str` are unicode and there is another type `bytes`. Warning: big difference between Python 2 and Python 3. In Python 3, `str` are unicode and there is another type `bytes`.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Methods of the type `str` #### Methods of the type `str`
Objects of built-in types have methods associated with their type (object oriented programming). The built-in function `dir` returns a list of name of the attributes. For a string, these attributes are python system attributes (with double-underscores) and several public methods: Objects of built-in types have methods associated with their type (object oriented programming). The built-in function `dir` returns a list of name of the attributes. For a string, these attributes are python system attributes (with double-underscores) and several public methods:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'abcdef' s = 'abcdef'
print(dir(s)) print(dir(s))
``` ```
%% Output %% Output
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
To access an attribute of an object (here, the method `str.startswith`), we use the dot: To access an attribute of an object (here, the method `str.startswith`), we use the dot:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s.startswith('a') s.startswith('a')
``` ```
%% Output %% Output
True True
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### standard type `str` ### standard type `str`
#### function `str.format` #### function `str.format`
```text ```text
Docstring: Docstring:
S.format(*args, **kwargs) -> str S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs. Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}'). The substitutions are identified by braces ('{' and '}').
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 1.23456789 a = 1.23456789
'a = {}'.format(a) 'a = {}'.format(a)
``` ```
%% Output %% Output
'a = 1.23456789' 'a = 1.23456789'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
'a = {:.4f}'.format(a) 'a = {:.4f}'.format(a)
``` ```
%% Output %% Output
'a = 1.2346' 'a = 1.2346'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
'a = {:8.4f}'.format(a) 'a = {:8.4f}'.format(a)
``` ```
%% Output %% Output
'a = 1.2346' 'a = 1.2346'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
'a = {:.4e} (scientific notation)'.format(a) 'a = {:.4e} (scientific notation)'.format(a)
``` ```
%% Output %% Output
'a = 1.2346e+00 (scientific notation)' 'a = 1.2346e+00 (scientific notation)'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print('{}\t{}\t{}'.format(1, 2, 3)) print('{}\t{}\t{}'.format(1, 2, 3))
``` ```
%% Output %% Output
1 2 3 1 2 3
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### standard type `str` ### standard type `str`
#### New in Python 3.6: format strings #### New in Python 3.6: format strings
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 1.23456789 a = 1.23456789
f'a = {a}' f'a = {a}'
``` ```
%% Output %% Output
'a = 1.23456789' 'a = 1.23456789'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
f'a = {a:.4f}' f'a = {a:.4f}'
``` ```
%% Output %% Output
'a = 1.2346' 'a = 1.2346'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
f'a = {a:8.4f}' f'a = {a:8.4f}'
``` ```
%% Output %% Output
'a = 1.2346' 'a = 1.2346'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
f'a = {a:.4e} (scientific notation)' f'a = {a:.4e} (scientific notation)'
``` ```
%% Output %% Output
'a = 1.2346e+00 (scientific notation)' 'a = 1.2346e+00 (scientific notation)'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(f'{1}\t{1+1}\t{2+1}') print(f'{1}\t{1+1}\t{2+1}')
``` ```
%% Output %% Output
1 2 3 1 2 3
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### standard type `str` ### standard type `str`
Strings are immutable **["sequences"](https://docs.python.org/3/library/stdtypes.html)**. Strings are immutable **["sequences"](https://docs.python.org/3/library/stdtypes.html)**.
- lookup - lookup
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'abcdef' s = 'abcdef'
print('a' in s) print('a' in s)
print('hello' not in s) print('hello' not in s)
``` ```
%% Output %% Output
True True
True True
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- We can get an element of a string (**index starts from 0**): - We can get an element of a string (**index starts from 0**):
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print(s[0]) print(s[0])
``` ```
%% Output %% Output
a a
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- since strings are immutable, they can not be modified inplace. If we try, we get an error: - since strings are immutable, they can not be modified inplace. If we try, we get an error:
```python ```python
s[0] = 'b' s[0] = 'b'
``` ```
```text ```text
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
TypeError Traceback (most recent call last) TypeError Traceback (most recent call last)
<ipython-input-5-55620f378bce> in <module>() <ipython-input-5-55620f378bce> in <module>()
----> 1 s[0] = 'b' ----> 1 s[0] = 'b'
TypeError: 'str' object does not support item assignment TypeError: 'str' object does not support item assignment
``` ```
- since strings are sequences, they can be "sliced" (we will soon study in details this powerful notation): - since strings are sequences, they can be "sliced" (we will soon study in details this powerful notation):
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s[1:3] s[1:3]
``` ```
%% Output %% Output
'bc' 'bc'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- it is very simple to manipulate strings in many ways: - it is very simple to manipulate strings in many ways:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
print((s.capitalize() + ' ' + s.upper() + '\n') * 4 ) print((s.capitalize() + ' ' + s.upper() + '\n') * 4 )
``` ```
%% Output %% Output
Abcdef ABCDEF Abcdef ABCDEF
Abcdef ABCDEF Abcdef ABCDEF
Abcdef ABCDEF Abcdef ABCDEF
Abcdef ABCDEF Abcdef ABCDEF
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Slicing ### Slicing
Very general, can be used on all sequences as `str`, `list`, etc... Not simple for beginners but very powerfull (see [here](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) and [here](http://avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html)). Very general, can be used on all sequences as `str`, `list`, etc... Not simple for beginners but very powerfull (see [here](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) and [here](http://avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html)).
Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements. Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements.
```text ```text
Index from rear: -6 -5 -4 -3 -2 -1 Index from rear: -6 -5 -4 -3 -2 -1
Index from front: 0 1 2 3 4 5 Index from front: 0 1 2 3 4 5
+---+---+---+---+---+---+ +---+---+---+---+---+---+
| a | b | c | d | e | f | | a | b | c | d | e | f |
+---+---+---+---+---+---+ +---+---+---+---+---+---+
Slice from front: 0 1 2 3 4 5 6 Slice from front: 0 1 2 3 4 5 6
Slice from rear: -6 -5 -4 -3 -2 -1 None Slice from rear: -6 -5 -4 -3 -2 -1 None
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'abcdef' s = 'abcdef'
# s[start:stop:step] # s[start:stop:step]
s[2:6:2] s[2:6:2]
``` ```
%% Output %% Output
'ce' 'ce'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# s[start:stop] # s[start:stop]
s[2:6] s[2:6]
``` ```
%% Output %% Output
'cdef' 'cdef'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# s[start:] # s[start:]
s[1:] s[1:]
``` ```
%% Output %% Output
'bcdef' 'bcdef'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# s[:stop] # s[:stop]
s[:2] s[:2]
``` ```
%% Output %% Output
'ab' 'ab'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# step = -1: goes through the string in reverse order # step = -1: goes through the string in reverse order
s[::-1] s[::-1]
``` ```
%% Output %% Output
'fedcba' 'fedcba'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
Suppose we have a string representing a header line of the form: Suppose we have a string representing a header line of the form:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = ' wind;temperature;;pressure ' s = ' wind;temperature;;pressure '
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- Remove leading and ending blanks (see `str.replace` and `str.strip`) - Remove leading and ending blanks (see `str.replace` and `str.strip`)
- Extract the first field (e.g. using `find` method and slicing) - Extract the first field (e.g. using `find` method and slicing)
- Extract the last field (e.g. using `rfind` method and slicing) - Extract the last field (e.g. using `rfind` method and slicing)
- Check for empty field (e.g. `find` ";;" pattern) - Check for empty field (e.g. `find` ";;" pattern)
- Remove empty field (e.g. using replace method) - Remove empty field (e.g. using replace method)
- BONUS : Extract the second field (tip :`find` can take an argument that tells where to start the search) - BONUS : Extract the second field (tip :`find` can take an argument that tells where to start the search)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = ' wind;temperature;;pressure ' s = ' wind;temperature;;pressure '
# remove leading blanks # remove leading blanks
s = s.strip() s = s.strip()
print("--{}--".format(s)) print("--{}--".format(s))
# extract the first field # extract the first field
idx = s.find(";") idx = s.find(";")
s0 = s[0:idx] s0 = s[0:idx]
print(s0) print(s0)
# extract the second field # extract the second field
idx1 = s.find(";", idx+1) # start the search after the first ";" idx1 = s.find(";", idx+1) # start the search after the first ";"
s1 = s[idx+1:idx1] s1 = s[idx+1:idx1]
print(s1) print(s1)
# extract the last field # extract the last field
idx2 = s.rfind(";") idx2 = s.rfind(";")
s2 = s[idx2+1:] s2 = s[idx2+1:]
print(s2) print(s2)
idx_first_empty_field = s.find(";;") idx_first_empty_field = s.find(";;")
print(idx_first_empty_field) print(idx_first_empty_field)
# remove empty field # remove empty field
s_no_empty = s.replace(";;", ";") s_no_empty = s.replace(";;", ";")
print(s_no_empty) print(s_no_empty)
``` ```
%% Output %% Output
--wind;temperature;;pressure-- --wind;temperature;;pressure--
wind wind
temperature temperature
pressure pressure
16 16
wind;temperature;pressure wind;temperature;pressure
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### standard type `list` ### standard type `list`
A list is a **mutable sequence of (possibly inhomogeneous) elements**. A list is a **mutable sequence of (possibly inhomogeneous) elements**.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
type([0, 'a']) type([0, 'a'])
``` ```
%% Output %% Output
list list
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# create an empty list # create an empty list
l = [] l = []
# fill the list (with the function append) # fill the list (with the function append)
l.append('2') l.append('2')
# fill the list (with the function extend) # fill the list (with the function extend)
l.extend([6, 3.]) l.extend([6, 3.])
print(l) print(l)
``` ```
%% Output %% Output
['2', 6, 3.0] ['2', 6, 3.0]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# concatenate lists with the operator + # concatenate lists with the operator +
print(l + ['hello', 3]) print(l + ['hello', 3])
``` ```
%% Output %% Output
['2', 6, 3.0, 'hello', 3] ['2', 6, 3.0, 'hello', 3]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# get values # get values
print(l[0], l[2], l[-2]) print(l[0], l[2], l[-2])
# slicing # slicing
print(l[0:2]) print(l[0:2])
``` ```
%% Output %% Output
2 3.0 6 2 3.0 6
['2', 6] ['2', 6]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### standard type `tuple` ### standard type `tuple`
A tuple is a **immutable sequence of (possibly inhomogeneous) elements**. A tuple is a **immutable sequence of (possibly inhomogeneous) elements**.
Remark: when you need a sequence that won't be modified, tuple is usually more efficient than list. Remark: when you need a sequence that won't be modified, tuple is usually more efficient than list.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
t = 0, 'a', 1.2 t = 0, 'a', 1.2
t1 = (5, 'hello') t1 = (5, 'hello')
t2 = tuple([1.1, 2]) t2 = tuple([1.1, 2])
type(t) type(t)
``` ```
%% Output %% Output
tuple tuple
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
t[1] # indexing t[1] # indexing
``` ```
%% Output %% Output
'a' 'a'
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
t[1:] # slicing t[1:] # slicing
``` ```
%% Output %% Output
('a', 1.2) ('a', 1.2)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a, b = t1 # tuple assigment a, b = t1 # tuple assigment
print(b) print(b)
``` ```
%% Output %% Output
hello hello
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Mutable and immutable objects ## Mutable and immutable objects
The objects of type `str`, `int`, `float`, `bool` are immutable. They can not be modified. Of course, a name that points towards an integer can point towards a different integer. The objects of type `str`, `int`, `float`, `bool` are immutable. They can not be modified. Of course, a name that points towards an integer can point towards a different integer.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
i = 1 i = 1
i = i + 2 # (or i += 2) i = i + 2 # (or i += 2)
print(i) print(i)
i = 10 i = 10
print(i) print(i)
``` ```
%% Output %% Output
3 3
10 10
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Here, the objects `1` and `3` have not been modified. Here, the objects `1` and `3` have not been modified.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Mutable and immutable objects ## Mutable and immutable objects
An object of type `list` is mutable: An object of type `list` is mutable:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = [0, 5] l = [0, 5]
print(l) print(l)
l.append('hello') l.append('hello')
print(l) print(l)
``` ```
%% Output %% Output
[0, 5] [0, 5]
[0, 5, 'hello'] [0, 5, 'hello']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Here, the object list tagged by the name `l` has been modified inplace. Here, the object list tagged by the name `l` has been modified inplace.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## References and `del` keyword ## References and `del` keyword
`del` removes a reference. If an object in not binded to any names, Python can delete it from its internal memory. `del` removes a reference. If an object in not binded to any names, Python can delete it from its internal memory.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = ['a', 'b'] l = ['a', 'b']
del l[1] del l[1]
print(l) print(l)
``` ```
%% Output %% Output
['a'] ['a']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### More on slicing ### More on slicing
Very general, can be used on all sequences as `str`, `list`, etc... Not simple for beginners but very powerfull (see [here](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) and [here](http://avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html)). Very general, can be used on all sequences as `str`, `list`, etc... Not simple for beginners but very powerfull (see [here](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) and [here](http://avilpage.com/2015/03/a-slice-of-python-intelligence-behind.html)).
Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements. Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements.
```text ```text
Index from rear: -6 -5 -4 -3 -2 -1 Index from rear: -6 -5 -4 -3 -2 -1
Index from front: 0 1 2 3 4 5 Index from front: 0 1 2 3 4 5
+---+---+---+---+---+---+ +---+---+---+---+---+---+
| a | b | c | d | e | f | | a | b | c | d | e | f |
+---+---+---+---+---+---+ +---+---+---+---+---+---+
Slice from front: 0 1 2 3 4 5 6 Slice from front: 0 1 2 3 4 5 6
Slice from rear: -6 -5 -4 -3 -2 -1 0 Slice from rear: -6 -5 -4 -3 -2 -1 0
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'abcdef' s = 'abcdef'
# s[start:stop:step] # s[start:stop:step]
s[2:6:2] s[2:6:2]
``` ```
%% Output %% Output
'ce' 'ce'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### More on slicing ### More on slicing
#### Assigment to mutable object #### Assigment to mutable object
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = [0, 1, 2, 3, 4, 5] l = [0, 1, 2, 3, 4, 5]
l1 = l # assigment to a new name l1 (no copy of the object). l1 = l # assigment to a new name l1 (no copy of the object).
# the names l and l1 points towards the same object. # the names l and l1 points towards the same object.
l1.append('a') l1.append('a')
print(l1) print(l1)
print(l) print(l)
``` ```
%% Output %% Output
[0, 1, 2, 3, 4, 5, 'a'] [0, 1, 2, 3, 4, 5, 'a']
[0, 1, 2, 3, 4, 5, 'a'] [0, 1, 2, 3, 4, 5, 'a']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### Shallow copy #### Shallow copy
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = [0, 1, 2, 3, 4, 5] l = [0, 1, 2, 3, 4, 5]
l1 = l[:] # shallow copy of l l1 = l[:] # shallow copy of l
l1.append('a') l1.append('a')
print(l1) print(l1)
print(l) print(l)
``` ```
%% Output %% Output
[0, 1, 2, 3, 4, 5, 'a'] [0, 1, 2, 3, 4, 5, 'a']
[0, 1, 2, 3, 4, 5] [0, 1, 2, 3, 4, 5]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### More on slicing ### More on slicing
Other examples of slices for a six-element list. Indexes enumerate the elements, slices enumerate the spaces between the elements. Other examples of slices for a six-element list. Indexes enumerate the elements, slices enumerate the spaces between the elements.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = [0, 1, 2, 3, 4, 5] a = [0, 1, 2, 3, 4, 5]
all([ all([
len(a) == 6, len(a) == 6,
a[1:] == [1, 2, 3, 4, 5], a[1:] == [1, 2, 3, 4, 5],
a[:5] == [0, 1, 2, 3, 4], a[:5] == [0, 1, 2, 3, 4],
a[0] == 0, a[0] == 0,
a[:-2] == [0, 1, 2, 3], a[:-2] == [0, 1, 2, 3],
a[5] == 5, a[5] == 5,
a[1:2] == [1], a[1:2] == [1],
a[-1] == 5, a[-1] == 5,
a[1:-1] == [1, 2, 3, 4], a[1:-1] == [1, 2, 3, 4],
a[-2] == 4, a[-2] == 4,
]) ])
``` ```
%% Output %% Output
True True
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
Suppose we have the string containing header line. Suppose we have the string containing header line.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'wind;temperature;pressure' s = 'wind;temperature;pressure'
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- Extract the list of items (i.e. "wind", "temperature", "pressure"; see `str.split`). - Extract the list of items (i.e. "wind", "temperature", "pressure"; see `str.split`).
- Add "Snow level" to the list of items (e.g. using append) - Add "Snow level" to the list of items (e.g. using append)
- Build a new header such that items are capitalized (e.g. using the methods `str.join` and `str.capitalize` and iterating on the list) - Build a new header such that items are capitalized (e.g. using the methods `str.join` and `str.capitalize` and iterating on the list)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
s = 'wind;temperature;pressure' s = 'wind;temperature;pressure'
list_items = s.split(";") list_items = s.split(";")
print(list_items) print(list_items)
list_items.append("snow level".capitalize()) list_items.append("snow level".capitalize())
list_items[0] = list_items[0].capitalize() list_items[0] = list_items[0].capitalize()
list_items[1] = list_items[1].capitalize() list_items[1] = list_items[1].capitalize()
list_items[2] = list_items[2].capitalize() list_items[2] = list_items[2].capitalize()
print(list_items) print(list_items)
";".join(list_items) ";".join(list_items)
``` ```
%% Output %% Output
['wind', 'temperature', 'pressure'] ['wind', 'temperature', 'pressure']
['Wind', 'Temperature', 'Pressure', 'Snow level'] ['Wind', 'Temperature', 'Pressure', 'Snow level']
'Wind;Temperature;Pressure;Snow level' 'Wind;Temperature;Pressure;Snow level'
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### The function `range` ### The function `range`
The function returns a range object: The function returns a range object:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# start, stop, step # start, stop, step
range(1, 8, 2) range(1, 8, 2)
``` ```
%% Output %% Output
range(1, 8, 2) range(1, 8, 2)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
We can make a list with the range object: We can make a list with the range object:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# start, stop, step # start, stop, step
list(range(1, 8, 2)) list(range(1, 8, 2))
``` ```
%% Output %% Output
[1, 3, 5, 7] [1, 3, 5, 7]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# start, stop (step=1) # start, stop (step=1)
list(range(2, 8)) list(range(2, 8))
``` ```
%% Output %% Output
[2, 3, 4, 5, 6, 7] [2, 3, 4, 5, 6, 7]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# stop argument (start=0, step=1) # stop argument (start=0, step=1)
list(range(8)) list(range(8))
``` ```
%% Output %% Output
[0, 1, 2, 3, 4, 5, 6, 7] [0, 1, 2, 3, 4, 5, 6, 7]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
Build a list of odd numbers in decreasing order. Build a list of odd numbers in decreasing order.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Conditions: `if`, `elif`, `else` ## Conditions: `if`, `elif`, `else`
```python ```python
if expression: if expression:
statement(s) statement(s)
else: else:
statement(s) statement(s)
``` ```
The statement contains the block of code that executes if the conditional expression in the if statement resolves to 1 or a TRUE value. The statement contains the block of code that executes if the conditional expression in the if statement resolves to 1 or a TRUE value.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 0 a = 0
if a == 0: if a == 0:
print('a is equal to 0.') print('a is equal to 0.')
``` ```
%% Output %% Output
a is equal to 0. a is equal to 0.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
a = 1 a = 1
if a < 0: if a < 0:
print('a is negative.') print('a is negative.')
elif a == 0: elif a == 0:
print('a is equal to 0.') print('a is equal to 0.')
elif a > 0: elif a > 0:
print('a is positive.') print('a is positive.')
else: else:
print("I don't know.") print("I don't know.")
``` ```
%% Output %% Output
a is positive. a is positive.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Loops ## Loops
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Loops with the keyword `while` ### Loops with the keyword `while`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
i = 0 i = 0
while i < 4: while i < 4:
i += 1 i += 1
print('i =', i) print('i =', i)
``` ```
%% Output %% Output
i = 4 i = 4
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
i = 0 i = 0
while i < 4: while i < 4:
i += 1 i += 1
print('i =', i) print('i =', i)
``` ```
%% Output %% Output
i = 1 i = 1
i = 2 i = 2
i = 3 i = 3
i = 4 i = 4
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
- Edit a script with the spyder editor that calculates the average of a set of numbers. For example `numbers = [67, 12, 2, 9, 23, 5]` - Edit a script with the spyder editor that calculates the average of a set of numbers. For example `numbers = [67, 12, 2, 9, 23, 5]`
* using the functions `sum` and `len` * using the functions `sum` and `len`
* manually, using the keyword `while` * manually, using the keyword `while`
- Run the script - Run the script
* in spyder, * in spyder,
* in a ipython session opened from another terminal, * in a ipython session opened from another terminal,
* with the command `python`. * with the command `python`.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
numbers = [67, 12, 2, 9, 23, 5] numbers = [67, 12, 2, 9, 23, 5]
local_sum = 0 local_sum = 0
i = 0 i = 0
while i < len(numbers): while i < len(numbers):
local_sum = local_sum + numbers[i] local_sum = local_sum + numbers[i]
i = i+1 i = i+1
avg = local_sum / len(numbers) avg = local_sum / len(numbers)
print(avg) print(avg)
``` ```
%% Output %% Output
19.666666666666668 19.666666666666668
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Loops with the keyword `for` ### Loops with the keyword `for`
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for index in range(5): for index in range(5):
print(index, end=', ') print(index, end=', ')
``` ```
%% Output %% Output
0, 1, 2, 3, 4, 0, 1, 2, 3, 4,
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
cities = ["grenoble", "paris", "berlin", "london"] cities = ["grenoble", "paris", "berlin", "london"]
for city in cities: for city in cities:
print(city, end=", ") print(city, end=", ")
``` ```
%% Output %% Output
grenoble, paris, berlin, london, grenoble, paris, berlin, london,
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# the built-in function enumerate is very useful # the built-in function enumerate is very useful
for index, city in enumerate(cities): for index, city in enumerate(cities):
print('({}, {})'.format(index, city)) print('({}, {})'.format(index, city))
cities[index] = city.capitalize() cities[index] = city.capitalize()
``` ```
%% Output %% Output
(0, grenoble) (0, grenoble)
(1, paris) (1, paris)
(2, berlin) (2, berlin)
(3, london) (3, london)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
cities cities
``` ```
%% Output %% Output
['Grenoble', 'Paris', 'Berlin', 'London'] ['Grenoble', 'Paris', 'Berlin', 'London']
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Loops: keywords `continue` and `break` ### Loops: keywords `continue` and `break`
- `continue`: passes the block in the loop and continues the loop. - `continue`: passes the block in the loop and continues the loop.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for x in range(1, 8): for x in range(1, 8):
if x == 5: if x == 5:
continue continue
print(x, end=', ') print(x, end=', ')
``` ```
%% Output %% Output
1, 2, 3, 4, 6, 7, 1, 2, 3, 4, 6, 7,
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
- `break`: stop the loop. - `break`: stop the loop.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for x in range(1, 11): for x in range(1, 11):
if x == 5: if x == 5:
break break
print(x, end=', ') print(x, end=', ')
``` ```
%% Output %% Output
1, 2, 3, 4, 1, 2, 3, 4,
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
- Simplify your script by using a `for` loops. - Simplify your script by using a `for` loops.
- In ipython, try to understand how the function `enumerate` works. Use it in your script. - In ipython, try to understand how the function `enumerate` works. Use it in your script.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = [67, 12, 2, 9, 23, 5] l = [67, 12, 2, 9, 23, 5]
local_sum = 0 local_sum = 0
for e in l: for e in l:
local_sum += e local_sum += e
avg = local_sum / len(l) avg = local_sum / len(l)
print(avg) print(avg)
``` ```
%% Output %% Output
19.666666666666668 19.666666666666668
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself ### Do it yourself
We build a list: We build a list:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
from random import shuffle, randint from random import shuffle, randint
n = 20 n = 20
i = randint(0, n-1) i = randint(0, n-1)
print('integer remove from the list:', i) print('integer remove from the list:', i)
l = list(range(n)) l = list(range(n))
l.remove(i) l.remove(i)
shuffle(l) shuffle(l)
print('shuffled list: ', l) print('shuffled list: ', l)
``` ```
%% Output %% Output
integer remove from the list: 9 integer remove from the list: 9
shuffled list: [13, 16, 15, 14, 5, 17, 12, 8, 11, 1, 18, 2, 10, 19, 4, 7, 0, 6, 3] shuffled list: [13, 16, 15, 14, 5, 17, 12, 8, 11, 1, 18, 2, 10, 19, 4, 7, 0, 6, 3]
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
One element has been removed: One element has been removed:
- Find this element (given that you can change the ordering of `l`). - Find this element (given that you can change the ordering of `l`).
- Find this element (given that you cannot change the ordering of `l`). - Find this element (given that you cannot change the ordering of `l`).
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# we can change ordering, let's sort # we can change ordering, let's sort
print(l) print(l)
l_sorted = sorted(l) l_sorted = sorted(l)
print(l_sorted) print(l_sorted)
found = None found = None
for idx, elem in enumerate(l_sorted): for idx, elem in enumerate(l_sorted):
if elem != idx: if elem != idx:
found = idx found = idx
break break
if found is None: if found is None:
found = len(l) found = len(l)
print("missing ", idx) print("missing ", idx)
``` ```
%% Output %% Output
[13, 16, 15, 14, 5, 17, 12, 8, 11, 1, 18, 2, 10, 19, 4, 7, 0, 6, 3] [13, 16, 15, 14, 5, 17, 12, 8, 11, 1, 18, 2, 10, 19, 4, 7, 0, 6, 3]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
missing 9 missing 9
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# we cannot sort -> higher complexity # we cannot sort -> higher complexity
for elem in range(len(l)+1): for elem in range(len(l)+1):
if elem not in l: if elem not in l:
break break
print("missing ", elem) print("missing ", elem)
``` ```
%% Output %% Output
missing 9 missing 9
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# another solution # another solution
actual_sum = sum(l) actual_sum = sum(l)
len_l = len(l) len_l = len(l)
original_sum = (len_l + 1) * (len_l) // 2 original_sum = (len_l + 1) * (len_l) // 2
print("missing ", original_sum - actual_sum) print("missing ", original_sum - actual_sum)
``` ```
%% Output %% Output
missing 9 missing 9
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Exceptions and `try`, `except` syntax ## Exceptions and `try`, `except` syntax
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Exceptions and errors are common in all codes. There is a good system to handle them in Python. Let's first see what gives such buggy code Exceptions and errors are common in all codes. There is a good system to handle them in Python. Let's first see what gives such buggy code
```python ```python
l = ['a'] l = ['a']
i = 1 i = 1
print(l[i]) print(l[i])
``` ```
When these lines are executed, Python stops its execution and print a traceback: When these lines are executed, Python stops its execution and print a traceback:
```text ```text
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
IndexError Traceback (most recent call last) IndexError Traceback (most recent call last)
<ipython-input-30-8df9cec1a0ec> in <module>() <ipython-input-30-8df9cec1a0ec> in <module>()
1 l = ['a'] 1 l = ['a']
2 i = 1 2 i = 1
----> 3 print(l[i]) ----> 3 print(l[i])
IndexError: list index out of range IndexError: list index out of range
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Exceptions and `try`, `except` syntax ## Exceptions and `try`, `except` syntax
Handling exception: Handling exception:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
l = ['a'] l = ['a']
i = 1 i = 1
try: try:
print(l[i]) print(l[i])
except IndexError as e: except IndexError as e:
print(e) print(e)
``` ```
%% Output %% Output
list index out of range list index out of range
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
Remark: never use Remark: never use
```python ```python
except: except:
``` ```
It means "except all errors and exceptions". A user Control-C is an exception (`KeyboardInterrupt`) so it would be caught and have no effect. It means "except all errors and exceptions". A user Control-C is an exception (`KeyboardInterrupt`) so it would be caught and have no effect.
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Full syntax ## Full syntax
```python ```python
try: try:
... ...
except <exception1> as e1: except <exception1> as e1:
... ...
except <exception2> as e2: except <exception2> as e2:
... ...
else: else:
... ...
finally: finally:
... ...
``` ```
[Non exhaustive error list](https://docs.python.org/3/library/exceptions.html): [Non exhaustive error list](https://docs.python.org/3/library/exceptions.html):
- ArithmeticError - ArithmeticError
- ZeroDivisionError - ZeroDivisionError
- IndexError - IndexError
- KeyError - KeyError
- AttributeError - AttributeError
- IOError - IOError
- ImportError - ImportError
- NameError - NameError
- SyntaxError - SyntaxError
- TypeError - TypeError
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
### Do it yourself: ### Do it yourself:
For each line of this string, append a variable of correct type in a list (i.e. "hello" should stay hello, For each line of this string, append a variable of correct type in a list (i.e. "hello" should stay hello,
2 should become an int and 1.5 a float). Do it by catching errors. 2 should become an int and 1.5 a float). Do it by catching errors.
**Hints:** **Hints:**
- int("a") and float("a") raise ValueError - int("a") and float("a") raise ValueError
- the above str_variable can be split using "\n" - the above str_variable can be split using "\n"
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
str_variables = """hello str_variables = """hello
1.5 1.5
2""" 2"""
the_list_you_should_get = ["hello", 1.5, 2] the_list_you_should_get = ["hello", 1.5, 2]
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
#### A possible solution: #### A possible solution:
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
split_list = [] split_list = []
for value in str_variables.split("\n"): for value in str_variables.split("\n"):
try: try:
value = int(value) value = int(value)
except ValueError: except ValueError:
print(value, "is not a int") print(value, "is not a int")
try: try:
value = float(value) value = float(value)
except ValueError: except ValueError:
print(value, 'is not a float') print(value, 'is not a float')
split_list.append(value) split_list.append(value)
print(split_list) print(split_list)
``` ```
%% Output %% Output
hello is not a int hello is not a int
hello is not a float hello is not a float
1.5 is not a int 1.5 is not a int
['hello', 1.5, 2] ['hello', 1.5, 2]
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment