Commit 0db3ea91 authored by Loic Huder's avatar Loic Huder
Browse files

Merge remote-tracking branch 'origin/master'

# Conflicts:
#	ipynb/pres080_oop_encapsulation.ipynb
parents db264654 cfcf632e
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
%% Cell type:markdown id: tags:
## Table of contents
......
......@@ -137,7 +137,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.4"
"version": "3.7.2"
}
},
"nbformat": 4,
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK) Loïc Huder (ISTerre)
# First steps
Repository containing the source of this training:
......@@ -86,11 +86,11 @@
```bash
cat pyfiles/helloworld.py
python3 pyfiles/helloworld.py
```
(`cat` is a Unix command to show the content of a text file.)
(`cat` is a Unix command that print the content of a text file.)
%% Cell type:markdown id: tags:
### Do it yourself: work interactively with [ipython](https://ipython.org/)
......@@ -109,16 +109,16 @@
4
%% Cell type:code id: tags:
``` python
3 + 4
3 / 4
```
%%%% Output: execute_result
7
0.75
%% Cell type:markdown id: tags:
- Run the script from ipython.
......@@ -163,11 +163,11 @@
Remarks:
- it is very important to use a good editor to code in Python (for example spyder, emacs or vi with [a good setup](https://bitbucket.org/fluiddyn/fluid_emacs.d)).
- a good modern open-source editor: [Visual Studio Code](https://code.visualstudio.com/docs/languages/python).
- a good modern open-source editor: [Visual Studio Code] (https://code.visualstudio.com/docs/languages/python).
%% Cell type:markdown id: tags:
### Python in the browser ([Jupyter](https://jupyter.readthedocs.io))
......
......@@ -2,11 +2,13 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK),
Loïc Huder (ISTerre)
# Characteristics of the Python language
%% Cell type:markdown id: tags:
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# More standard types and basic statements
%% Cell type:markdown id: tags:
......@@ -376,11 +376,11 @@
### standard type `str`
Strings are immutable **["sequences"](https://docs.python.org/3/library/stdtypes.html)**.
- loopup
- lookup
%% Cell type:code id: tags:
``` python
s = 'abcdef'
......@@ -973,11 +973,11 @@
local_sum = 0
i = 0
while i < len(numbers):
local_sum = local_sum + numbers[i]
i = i+1
avg = local_sum /len(numbers)
avg = local_sum / len(numbers)
print(avg)
```
%% Cell type:markdown id: tags:
......@@ -1109,10 +1109,20 @@
if elem not in l:
break
print("missing ", elem)
```
%% Cell type:code id: tags:
``` python
# another solution
actual_sum = sum(l)
len_l = len(l)
original_sum = (len_l + 1) * (len_l) // 2
print("missing ", original_sum - actual_sum)
```
%% Cell type:markdown id: tags:
## Exceptions and `try`, `except` syntax
%% Cell type:markdown id: tags:
......@@ -1194,11 +1204,16 @@
%% Cell type:markdown id: tags:
### Do it yourself:
For each line of this string, append a variable of correct type in a list. Do it by catching errors.
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.
**Hints:**
- int("a") and float("a") raise ValueError
- the above str_variable can be split using "\n"
%% Cell type:code id: tags:
``` python
str_variables = """hello
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# Functions
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code
reusing.
......@@ -22,13 +22,15 @@
%% Cell type:code id: tags:
``` python
def print_hello():
"hello printer"
print('hello')
def myprint(s):
"my hello printer"
print('I print', s)
# function calls
print_hello()
print_hello()
......@@ -41,10 +43,13 @@
## Simple function definitions and calls
- The first statement of a function can be the documentation string of the function, also called "docstring".
- The statement `return [expression]` exits a function, optionally passing back an expression to the caller. No return statement or a return statement with no arguments is the same as `return None`.
(Note: Wikipedia about duck typing: https://fr.wikipedia.org/wiki/Duck_typing)
%% Cell type:code id: tags:
``` python
def add(arg0, arg1):
"""Print and return the sum of the two arguments (duck typing)."""
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# Read / write files
%% Cell type:markdown id: tags:
......@@ -25,10 +25,19 @@
print(txt)
```
%% Cell type:markdown id: tags:
But what if something weird happens when the file is open (e.g. a division by O) ?
-> Exception is raised that could be catch and run some code that is not aware of the opening
file.
-> The file remains open
%% Cell type:markdown id: tags:
### Context, `with` keyword
For such objects that need to be closed, it is a good practice to use the keyword `with` (THIS IS MUCH BETTER than using the close function, USE `with`!). Like this, we are sure that the file will be closed even if there is an error:
%% Cell type:code id: tags:
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
## Practical session 0
File parsing and simple computations
......@@ -17,11 +17,11 @@
The goal of this session is to practice what we have seen in the first presentations:
- write code in scripts,
- use ipython and execute Python programs with the command python3,
- use objects of simple types (numbers, str, list, etc.),
- indexing, slicing,
- index and slice,
- use loops and conditions,
- try, except,
- read and write in text files.
We will write scripts that read a file (or a set of files) with a predefined format and compute simple quantities (sum, average, number) from the values in the files.
......@@ -92,13 +92,13 @@
```bash
python3 step0.2.py
file = "../data/file0.1.txt"
nb = 78 ; sum = 42.46 ; avg = 1.84
file = "../data/file0.2.txt"
nb = 100 ; sum = 53.29 ; avg = 1.88
nb = 100 ; sum = 53.29 ; avg = 0.53
file = "../data/file0.3.txt"
nb = 25 ; sum = 12.72 ; avg = 1.97
nb = 25 ; sum = 12.72 ; avg = 0.51
# total over all files:
nb = 203 ; sum = 108.47 ; avg = 0.53
```
%% Cell type:markdown id: tags:
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# Modules, `import` statement and the standard library
%% Cell type:markdown id: tags:
......@@ -98,10 +98,16 @@
from math import sqrt
# definition of functions and/or classes
def mysum(variables):
""" sum all the variables of the function and return it.
No type check
:param variables: (iterable) an iterable over elements
that can be summed up
:return: the sum of the variables
"""
result = 0
for var in variables:
result += var
return result
......
......@@ -2,11 +2,11 @@
# Python training UGA 2017
**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)
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
# [Data structures](https://docs.python.org/3.6/tutorial/datastructures.html)
%% Cell type:markdown id: tags:
......@@ -475,9 +475,35 @@
patterns = extract_patterns(text)
print("patterns = ", patterns)
patterns_count = count_elem(patterns)
print("patterns_counts = ", patterns_count)
print("guess for oo = ", guess("oo", patterns_count))
print("guess for eg = ", guess("eg", patterns_count))
```
%% Cell type:code id: tags:
``` python
text="Las Vegas Overlook Loop is a 6.3 mile loop trail located near Las Vegas"
def extract_patterns(text, n=3):
pat = [text[i:i+n] for i in range(len(text)-n+1)]
return pat
def guess(prefix, count):
"complete the prefix with the most probable pattern (according to count)"
# get all the pattern in keys of count that starts with prefix
compat_prefix = [(x, count[x]) for x in count.keys() if x.startswith(prefix)]
ordered_compat_pref = sorted(compat_prefix, key=lambda x: x[1],
reverse=True)
return ordered_compat_pref
patterns = extract_patterns(text)
print("patterns = ", patterns)
patterns_count = count_elem(patterns)
print("patterns_counts = ", patterns_count)
print("guess for oo = ", guess("oo", patterns_count))
print("guess for eg = ", guess("eg", patterns_count))
```
......
......@@ -424,5 +424,51 @@
## Introduction to Pandas: Python Data Analysis Library
Pandas is an open source library providing high-performance, easy-to-use data structures and data analysis tools for Python.
[Pandas tutorial](https://pandas.pydata.org/pandas-docs/stable/10min.html)
[Grenoble Python Working Session](https://github.com/iutzeler/Pres_Pandas/)
[Pandas for SQL Users](https://hackernoon.com/pandas-cheatsheet-for-sql-people-part-1-2976894acd0)
%% Cell type:markdown id: tags:
## Some Solutions of Practical 1 with Pandas
%% Cell type:code id: tags:
``` python
import pandas as pd
filename = "../TP/TP1_MeteoData/data/synop-2016.csv"
df = pd.read_csv(filename, sep = ',', encoding = "utf-8", header=0)
"""
max temperature
"""
print(df['Temperature'].max() - 273.15)
"""
mean temperature
"""
print(df['Temperature'].mean() - 273.15)
"""
total rainfall
"""
print(df['Rainfall 3 last hours'].sum())
"""
August max temperature
"""
print(df[df['Date'].str.startswith('2016-08')]['Temperature'].max()-273.15)
```
%% Cell type:code id: tags:
``` python
```
......
Markdown is supported
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