Commit 92266351 authored by paugier's avatar paugier
Browse files

Update notebooks before day 1

parent 8810b565
Pipeline #75745 passed with stage
in 52 seconds
......@@ -109,7 +109,7 @@
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
......@@ -123,9 +123,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}
......@@ -8,7 +8,7 @@
}
},
"source": [
"# Python training UGA 2017\n",
"# Python training UGA 2021\n",
"\n",
"**A training to acquire strong basis in Python to use it efficiently**\n",
"\n",
......@@ -276,7 +276,7 @@
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
......@@ -290,9 +290,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}
%% Cell type:markdown id: tags:
# Python training UGA 2017
# Python training UGA 2021
**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)
# First steps
%% Cell type:markdown id: tags:
## Why Python ?
- A very nice and well-thought programming language.
- **Generalist**: good for several applications, [used with success in many fields](http://brochure.getpython.info/).
- For academic purposes (teaching, research): **great scientific ecosystem**.
%% Cell type:markdown id: tags:
## Python: a language, an interpreter
Python is a programming language.
It is first an **interpreted** language (like Bash, Matlab, and in contrast with Fortran, C or C++), so we need an interpreter, i.e. a binary parsing Python code and running computer instructions.
Open a terminal. There are usually different python commands: `python`, `python2` and `python3`.
%% Cell type:markdown id: tags:
### Remark Python 2 / Python 3
2 languages, 2 interpreters, different commands (python, python2, python3, ...)
- https://python3statement.org/
- https://pythonclock.org/
%% Cell type:markdown id: tags:
## How to get Python?
- On Linux, there are the system python binaries.
- On Windows, Mac (and Linux), you can install and use
* https://www.python.org/downloads/
* [Anaconda or Miniconda](https://www.continuum.io/downloads)
- On Unix, [pyenv](https://github.com/pyenv/pyenv) is also very convenient!
- In some systems (cluster), there are modules:
```bash
module load python
```
See also [advice on how to install a good scientific Python environment](http://fluiddyn.readthedocs.io/en/latest/get_good_Python_env.html).
%% Cell type:markdown id: tags:
### Do it yourself: execute a script with the command `python3`
Go into the root directory of the repository of the training.
Run a script with `python3` (pyfiles/helloworld.py is *just* a text file):
```bash
cat pyfiles/helloworld.py
python3 pyfiles/helloworld.py
```
(`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/)
The command `ipython3` launch the program [ipython](https://ipython.org/), which is used for interactive python.
- In ipython, you can execute a first interactive instruction:
%% Cell type:code id: tags:
``` python
2 + 2
```
%%%% Output: execute_result
4
%% Cell type:code id: tags:
``` python
3 / 4
```
%%%% Output: execute_result
0.75
%% Cell type:markdown id: tags:
- Run the script from ipython.
%% Cell type:code id: tags:
``` python
run ../pyfiles/helloworld.py
```
%%%% Output: stream
Hello world
My name is Pierre
%% Cell type:code id: tags:
``` python
# name is defined in ../pyfiles/helloworld.py
print(name)
```
%%%% Output: stream
Pierre
%% Cell type:markdown id: tags:
- Help on an object can be displayed with the question mark (try it):
```ipython
name?
```
- Try to type "name." and to press on tab... The tab key is used to tell you how what you typed can be completed.
- Try to use the top and bottom arrows...
%% Cell type:markdown id: tags:
### Python in an IDE ([Spyder](https://pythonhosted.org/spyder/))
Launch the application Spyder, a Python IDE (Integrated development environment).
- a quite good code editor with:
- syntax coloring,
- code analysis powered by pyflakes and pylint,
- introspection capabilities such as code completion.
- Ipython console
- variable inspector
- ...
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), or [Visual Studio Code](https://code.visualstudio.com/docs/languages/python)).
%% Cell type:markdown id: tags:
### Python in the browser ([Jupyter](https://jupyter.readthedocs.io))
The presentations of this python training are made with Jupyter (demonstration).
This is a very powerful tool to present results (see these [examples](http://nbviewer.jupyter.org/)).
......
......@@ -8,7 +8,7 @@
}
},
"source": [
"# Python training UGA 2017\n",
"# Python training UGA 2021\n",
"\n",
"**A training to acquire strong basis in Python to use it efficiently**\n",
"\n",
......@@ -426,7 +426,10 @@
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
"collapsed": true,
"jupyter": {
"outputs_hidden": true
}
},
"outputs": [],
"source": [
......@@ -440,7 +443,10 @@
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
"collapsed": true,
"jupyter": {
"outputs_hidden": true
}
},
"outputs": [],
"source": [
......@@ -457,7 +463,10 @@
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
"collapsed": true,
"jupyter": {
"outputs_hidden": true
}
},
"outputs": [],
"source": [
......@@ -557,7 +566,7 @@
"metadata": {
"celltoolbar": "Slideshow",
"kernelspec": {
"display_name": "Python 3",
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
......@@ -571,9 +580,9 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
"version": "3.9.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
"nbformat_minor": 4
}
%% Cell type:markdown id: tags:
# Python training UGA 2017
# Python training UGA 2021
**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)
# Characteristics of the Python language
%% Cell type:markdown id: tags:
## Characteristics of the Python language
- Open-source language, interpreters and ecosystem
- Interpreted (but there are tools to compile Python code)
- Automatic memory management
- Dynamically strongly typed
%% Cell type:markdown id: tags:
## Dynamically and strongly typed: objects and variables
The function `type` returns the type of an **object**:
%% Cell type:code id: tags:
``` python
type('hello')
```
%%%% Output: execute_result
str
%% Cell type:code id: tags:
``` python
type(2)
```
%%%% Output: execute_result
int
%% Cell type:code id: tags:
``` python
type(2.)
```
%%%% Output: execute_result
float
%% Cell type:code id: tags:
``` python
type(2 + 2)
```
%%%% Output: execute_result
int
%% Cell type:code id: tags:
``` python
type(2 + 2.)
```
%%%% Output: execute_result
float
%% Cell type:code id: tags:
``` python
type(True)
```
%%%% Output: execute_result
bool
%% Cell type:markdown id: tags:
## Dynamically and strongly typed: objects and variables
**Variables** are just tags pointing towards objects. New variables can be used when needed. They are not associated with a type but only with an object (which has a type)...
%% Cell type:code id: tags:
``` python
myvar = 1
print(myvar, type(myvar))
```
%%%% Output: stream
1 <class 'int'>
%% Cell type:code id: tags:
``` python
myvar = 'hello'
print(myvar, type(myvar))
```
%%%% Output: stream
hello <class 'str'>
%% Cell type:markdown id: tags:
## Spaces for objects and variables (names)
Objects and variables (names) are two very different concepts:
- Objects live in one "object space". They have an address in the memory.
- Names live in namespaces.
It is often interesting to represent the execution of a Python program in an **"object space - namespaces" diagram**.
The Zen of Python says "Namespaces are one honking great idea -- let's do more of those!". A namespace is created for every module (file) and for every function execution,
%% Cell type:markdown id: tags:
## Characteristics of the Python language
- Open-source language, interpreters and ecosystem
- Interpreted (but there are tools to compile Python code)
- Automatic memory management
- Dynamically strongly typed
--------
- Gradual learning curve
- Only few [keywords](https://hg.python.org/cpython/file/3.6/Lib/keyword.py) and [built-in functions](https://docs.python.org/3/library/functions.html)
%% Cell type:markdown id: tags:
## Keywords
%% Cell type:code id: tags:
``` python
help("keywords")
```
%%%% Output: stream
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
%% Cell type:markdown id: tags:
plus 69 [built-in functions](https://docs.python.org/3/library/functions.html)... plus few [built-in constants](https://docs.python.org/3/library/constants.html)... plus [built-in exceptions](https://docs.python.org/3/library/exceptions.html)!
%% Cell type:markdown id: tags:
#### [Built-in functions](https://docs.python.org/3/library/functions.html) and [built-in exceptions](https://docs.python.org/3/library/exceptions.html):
%% Cell type:code id: tags:
``` python
import builtins
types = [type, type(sum)]
for type_ in types:
names = [
name for name in dir(builtins)
if isinstance(getattr(builtins, name), type_)
]
print(f'\n {len(names)} "{type_.__name__}" objects:\n{names}')
```
%%%% Output: stream
93 "type" objects:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'NotADirectoryError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__loader__', 'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'enumerate', 'filter', 'float', 'frozenset', 'int', 'list', 'map', 'memoryview', 'object', 'property', 'range', 'reversed', 'set', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'zip']
42 "builtin_function_or_method" objects:
['__build_class__', '__import__', 'abs', 'all', 'any', 'ascii', 'bin', 'breakpoint', 'callable', 'chr', 'compile', 'delattr', 'dir', 'divmod', 'eval', 'exec', 'format', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'isinstance', 'issubclass', 'iter', 'len', 'locals', 'max', 'min', 'next', 'oct', 'open', 'ord', 'pow', 'print', 'repr', 'round', 'setattr', 'sorted', 'sum', 'vars']
%% Cell type:markdown id: tags:
## Characteristics of the Python language
- Open-source language, interpreters and ecosystem
- Interpreted (but there are tools to compile Python code)
- Automatic memory management
- Dynamically strongly typed
--------
- Gradual learning curve
- Only few [keywords](https://hg.python.org/cpython/file/3.6/Lib/keyword.py) and [built-in functions](https://docs.python.org/3/library/functions.html)
--------
- A philosophy: the [Zen of Python](https://www.python.org/dev/peps/pep-0020/)
- Very clean and readable
- Indentation defines the blocks
- Style coding is important: [pep8](https://www.python.org/dev/peps/pep-0008/)
%% Cell type:markdown id: tags:
## PEP8 (Python Extension Proposal)
https://www.python.org/dev/peps/pep-0008/
- Code layout
- Imports
- Whitespace in expressions and statements
- Comments
- Documentation strings
- Naming conventions
- Programming recommendations
%% Cell type:markdown id: tags:
## PEP8: examples of bad and good style practices
%% Cell type:code id: tags:
``` python
# bad (spaces between operator)
number=0
# ok
number = 0
```
%% Cell type:code id: tags:
``` python
# bad (indentation with 2 spaces, has to be 4)
if number == 0:
number = 1
# ok
if number == 0:
number = 1
```
%% Cell type:code id: tags:
``` python
# bad (space after ,)
mylist = [1,2,3]
# ok
mylist = [1, 2, 3]
```
%% Cell type:markdown id: tags:
## You have to use a good editor!!
Python:
- (most of the time) interpreted (no compilation)
- very dynamic
- pep8 (style).
- indentation defines the blocks
The editor can and has to help you!!
- syntax coloring
- automatic indentation
- code analysis (code analysis powered by pyflakes and pylint)
- introspection capabilities such as code completion
%% Cell type:markdown id: tags:
## Do it yourself: PEP8 checker with Spyder editor
In Spyder, open the file `./pyfiles/wrong.py` and see what append.
Activate the "Real time code style analysis (PEP 8)" (Preferences -> Editor -> Code Introspection/Analysis).
Correct the file to remove the warnings.
%% Cell type:markdown id: tags:
## Characteristics of the Python language
- Open-source language, interpreters and ecosystem
- Interpreted (but there are tools to compile Python code)
- Automatic memory management
- Dynamically strongly typed
--------
- Gradual learning curve
- Only few [keywords](https://hg.python.org/cpython/file/3.6/Lib/keyword.py) and [built-in functions](https://docs.python.org/3/library/functions.html)
--------
- A philosophy: the [Zen of Python](https://www.python.org/dev/peps/pep-0020/)
- Very clean and readable
- Indentation defines the blocks
- Style coding is important: [pep8](https://www.python.org/dev/peps/pep-0008/)
--------
- Errors should never pass silently
- Multi-paradigm (sequential, object-oriented, functional)
- "Batteries Included": [the standard library](https://docs.python.org/3/tutorial/stdlib.html)
......
This diff is collapsed.
This diff is collapsed.
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