en and fr python3 courses

This commit is contained in:
gwen
2018-08-21 10:25:44 +02:00
committed by Benjamin Bohard
parent 323b4f6685
commit 0d286b85a0
228 changed files with 49353 additions and 0 deletions

View File

@ -0,0 +1,159 @@
Base types
==========
- types_
.. _types: https://realpython.com/python-data-types/
Python is dynamically typed
----------------------------
it means
- variables don't have fixed type, the types can change
- the variable's type is specified at runtime during the assignment
>>> a = 1
>>> type(a)
<class 'int'>
>>> a = 2.
>>> a
2.0
>>> type(a)
<class 'float'>
>>> b = "b"
>>> type(b)
<class 'str'>
>>> c = "3"
>>> type(c)
<class 'str'>
>>> int(c)
3
>>> c2 = int(c)
>>> c2
3
>>> type(c2)
<class 'int'>
>>>
Some builtin types
------------------
base types:
- integer,
- float,
- string,
- boolean
base container types:
- list,
- dictionnary,
- set
list type sample::
>>> l = range(10)
>>> l
range(0, 10)
>>> for i in l:
... print(i)
...
0
(...)
9
dictionary type sample::
>>> d = dict(a=2, b=5)
>>> d
{'b': 5, 'a': 2}
>>> type(d)
<class 'dict'>
a dict **is not** a ordered type. If you need an ordered dict, use a more
advanced collection type like an ordered dict
>>> from collections import OrderedDict
>>> d = OrderedDict({'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2})
>>> d
OrderedDict([('orange', 2), ('apple', 4), ('banana', 3), ('pear', 1)])
>>>
set sample::
>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
a set **is not** ordered
>>> s = set(range(10))
>>> 3 in s
True
Mutable types and non-mutable types
-------------------------------------
A set is immutable, whereas a list is mutable::
>>> s = set([1,2])
>>> l = [1,2]
>>> l.append(3)
>>> list(l)
[1, 2, 3]
>>> s.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'append'
>>>
A string is immutable. If you want to modify it, build another string:
>>> s = "hello"
>>> s.replace('ll', 'bb')
'hebbo'
>>> s+"you"
'helloyou'
>>> s
'hello'
you can see that s hasn't changed.
Even base types are objects
---------------------------
It means that in python, classes are types (let's understand it like that at first glance)
>>> a = 2
>>> isinstance(a, int)
True
>>> s = "a"
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
(...)
'__init__', '__iter__', '__le__', '__len__', '__lt__', ]
`s` has methods. It's an objects. The type of s is the class `int`.
>>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
>>> isinstance(d, dict)
True
>>>
special methods: the iterator sample
>>> l = range(10)
>>> for i in l:
... print(i)
We can use the `for` statement only because the `list` type has a special `__iter__`
method::
>>> l.__iter__()
<range_iterator object at 0x7f28b76e1e10>
>>>
we will see the special methods later.

View File

@ -0,0 +1,76 @@
Let's play with builtin types
=============================
- type int, float, bool, str
- type sequence list, tuple
- type dict
- list.append
- dict...
- strings_
- formating_
.. _strings: https://realpython.com/python-strings/
.. _formating: https://realpython.com/python-string-formatting/
The prompt is a calculator
---------------------------
>>> x = 1
>>> y =2
>>> x > y
False
>>> x == y
False
>>> x != y
True
The strings
-----------
>>> s = "bla bla"
'bla bla'
>>> s = 'bla bla'
'bla bla'
>>> s = " 'bli bli' "
>>> s
" 'bli bli' "
>>> s = """ sdfsdf "bla bla" sdfsdf"""
>>> s
' sdfsdf "bla bla" sdfsdf'
>>>
>>> s = "bla bla"
>>> m = "hu hu"
>>> s + m
'bla blahu hu'
>>> m * 3
'hu huhu huhu hu'
>>>
>>> len(m)
5
>>>
>>> m[3]
'h'
>>> m[3:5]
'hu'
>>>
play with `lower()`, `upper()`, `strip()`, `title()`
`index()`, `find()`, `replace()`
String templating
-----------------
>>> s = "ssdfsdf {0} sdfsdfsdf {1}".format("blah", "blih")
>>> s= 'a'
>>> t = "abc"
>>> t.startswith("a")
True
>>> l = ['a', 'b', 'c']
>>> "-".join(l)
'a-b-c'
>>>

View File

@ -0,0 +1,31 @@
A simple cipher
===============
.. currentmodule:: src
.. module:: cipher
The :mod:`cipher` module
------------------------
.. data:: domain
Set domain = string.digits if you want to work with
integers instead of printable letters -- or experiment
with other domains
.. function:: mkcode
Return a string containing the elements in domain
randomly permuted
.. function:: mkdict
Turns domain + secretkey into a dictionary of
substitution pairs
:src:`cipher`

View File

@ -0,0 +1,20 @@
Coding standards
================
Standard programming recommendations
---------------------------------------
pep8_
.. _pep8: https://pep8.org/
https://www.python.org/dev/peps/pep-0008/
You can validate against the coding standards in your editor or with the pep8 executable.
::
pep8 <mon_fichier.py>

View File

@ -0,0 +1,6 @@
Dict types
==========

View File

@ -0,0 +1,85 @@
Technical an user documentation
================================
- documenting_
.. _documenting: https://realpython.com/documenting-python-code/
The sphinx_ tool is a subset of docutils_
.. _sphinx: http://sphinx-doc.org/
.. _docutils: http://docutils.sf.net
Documenting a function
------------------------
**Info field lists**
Inside Python object description directives, reST field lists with these fields are recognized and formatted nicely:
- param, parameter, arg, argument, key, keyword: Description of a parameter.
- type: Type of a parameter. Creates a link if possible.
- raises, raise, except, exception: That (and when) a specific exception is raised.
- var: Description of a variable.
- vartype: Type of a variable. Creates a link if possible.
- returns, return: Description of the return value.
- rtype: Return type. Creates a link if possible.
The field names must consist of one of these keywords and an argument (except for returns and rtype, which do not need an argument). This is best explained by an example:
::
.. py:function:: send_message(sender, recipient, message_body, [priority=1])
Send a message to a recipient
:param str sender: The person sending the message
:param str recipient: The recipient of the message
:param str message_body: The body of the message
:param priority: The priority of the message, can be a number 1-5
:type priority: integer or None
:return: the message id
:rtype: int
:raises ValueError: if the message_body exceeds 160 characters
:raises TypeError: if the message_body is not a basestring
This will render like this with spinx-doc:
.. py:function:: send_message(sender, recipient, message_body, [priority=1])
Send a message to a recipient
:param str sender: The person sending the message
:param str recipient: The recipient of the message
:param str message_body: The body of the message
:param priority: The priority of the message, can be a number 1-5
:type priority: integer or None
:return: the message id
:rtype: int
:raises ValueError: if the message_body exceeds 160 characters
:raises TypeError: if the message_body is not a basestring
It is also possible to combine parameter type and description, if the type is
a single word, like this::
:param int priority: The priority of the message, can be a number 1-5
Container types such as lists and dictionaries can be linked automatically
using the following syntax::
:type priorities: list(int)
:type priorities: list[int]
:type mapping: dict(str, int)
:type mapping: dict[str, int]
:type point: tuple(float, float)
:type point: tuple[float, float]
Multiple types in a type field will be linked automatically if separated by
the word “or”::
:type an_arg: int or None
:vartype a_var: str or int
:rtype: float or str

View File

@ -0,0 +1,9 @@
duration
=========
The "timeit" module lets you measure the execution
time of small bits of Python code
.. literalinclude:: ../src/duration.py

View File

@ -0,0 +1,9 @@
Functions
=========
Function argument unpacking
.. literalinclude:: ../src/functype.py

View File

@ -0,0 +1,134 @@
Getting started
===============
Installation
-------------
Have a look at the python_ website.
.. _python: http://www.python.org
Hello world
-----------
::
python -c "print 'hello'"
Opening a python prompt::
>>> print("hello world")
hello world
.. code-block:: python
:caption: hello.py
:name: hello-py
import sys
name = sys.argv[1]
print("Hello, {0}".format(name))
starting a web server::
python3 -m http.server 8080
importing a module
>>> import this
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
use the builtin help
>>> help(function)
Configure your prompt
---------------------
Set your path or install a good prompt like `ipython <https://ipython.org/ipython-doc/2/install/install.html>`_
.. envvar:: PYTHONPATH
defaults on the current directory
you can add a path to point to some other library
put this in your `.bashrc` (under linux), under windows... I don't know:
::
export PYTHONPATH:`pwd`
export PYTHONPATH=$PYTHONPATH:'/usr/share':'/toto/titi/tata'
alias pyenv='export PYTHONPATH=`pwd`:$PYTHONPATH'
export PYTHONSTARTUP='/home/gwen/.pystartup'
.. envvar:: PYTHONSTARTUP
the pystartup enables us to set the
- autocompletion
- the history of the commands
example of `.pystartup`
::
# Store the file in ~/.pystartup, and set an environment variable to point to
# it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the full
# path to your home directory.
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
readline.read_history_file(histfile)
except IOError:
pass
import atexit
atexit.register(readline.write_history_file, histfile)
del os, histfile
# enhanced completion
#import rlcompleter2
#rlcompleter2.setup()
Editors
---------
IDLE
https://docs.python.org/3/library/idle.html
un framework de développement intégré : :term:`IDLE`
.. glossary::
IDLE
IDLE_ is an IDE (Integrated Development Environnement)
.. _IDLE: http://docs.python.org/3/library/idle.html
Thonny_
.. _Thonny: https://thonny.org/
Otherwise, your preferred editor...

View File

@ -0,0 +1,57 @@
.. default-role:: literal
.. meta::
:description: python tutorial
:keywords: python, tutorial
.. title:: pyfundoc
The tasting of python
=======================
.. figure:: _static/python-logo-large.png
:alt: The python software fundation's logo
(The *python software fundation's* logo)
Here are short Python code snippets focusing on teaching purposes.
Python is fun.
.. toctree::
:maxdepth: 1
:caption: The snippets:
getting-started
base-type
base-type2
functype
introspection
sdl
documenting
utilities
codingstandards
cipher
Indices and tables
==================
* `All modules for which code is available <_modules/index.html>`_
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. note:: The pyfun code is licensed under the `LGPL licence`_
and this documentation is licensed under the `Creative Commons
Attribution-ShareAlike 3.0 Unported License`_\ .
.. _`Creative Commons Attribution-ShareAlike 3.0 Unported License`: http://creativecommons.org/licenses/by-sa/3.0/deed.en_US
.. _`LGPL licence`: http://www.gnu.org/licenses/lgpl.html

View File

@ -0,0 +1,232 @@
Instrospection
==============
Python's introspection capabilites. First, we shall use the prompt.
The prompt
-----------
Type `python3` in the prompt. It gives you a prompt, which is the python prompt::
>>>
The prompt enables us to deeply analyse the fundamentals of the language.
It is interesting for a good understanding of the concepts.
For example, **introspection**. Introspection means finding informations
about each element you want to manipulate::
>>> locals()
{'__name__': '__main__', '__package__': None, '__doc__': None,
'__builtins__': <module 'builtins' (built-in)>, (...) }
>>>
.. glossary::
locals
The `locals()` builtin function lists the variables that lives in the
current namespace.
globals
The `globals()` builtin function lists the variables that lives in the
general namespace.
`locals()` in the global namespace and `locals()`` in a local namespace
(a function's namespace)::
>>> def myfunc(x):
... a = 2
... print(locals())
...
>>> locals()
{'__package__': None, '__spec__': None, (...)'__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>}
>>> # we can see that there's no "a" variable
>>> myfunc("toto")
{'x': 'toto', 'a': 2}
>>> # in the function there is a "a" variable
When we open a prompt, the general namespace and the local namespace are the same.
.. glossary::
builtins
The `__builtins__`` module is a special module :
it is the only namespace which is automaticaly imported.
It means that the variables function that are in the builtins are always
accessible. You can always call them.
For example, you can use the function `dir` which is directly accessible
without importing any module::
>>> dir()
['__builtins__', '__cached__', '__doc__', '__loader__', '__name__', ...]
>>>
In fact, the `dir()` function lives in the `__builtins__`::
>>> __builtins__.dir()
['__builtins__', '__cached__', '__doc__', '__loader__', '__name__', ...]
type::
>>> help(dir)
to have help on a given function or module.
`__doc__`: this namespace's docstring
`__package__`: the current namespace
`__name__` is the name of the current namespace, which is `__main__`::
>>> __name__
'__main__'
>>>
why is it `__main__` ? Because we are located in the global namespace.
Modules
-------
A module is a namespace, it is a pyhton file that you can import in another module.
A python file is intended to become a library, but you can use it as a script.
If you want to use module as a script, the good pratice is to fix its behavior with::
if __name__ == '__main__':
do_this()
It means that if you launch the module in the global namespace, then the module
is not used as a library but as a standalone script.
The good practice in a module is to do nothing.
If you launch::
do_this()
without the test condition::
if __name__ == '__main__':
when you import the module::
import mymodule
it will launch the `do_this` function, wich is not a intended behavior for a library.
A library is just a set of function/classes that are available in a given namespace.
A script is intended to do something when launched, not a library.
What are scripts ?
Scripts are executable file, they have a she bang::
#!/usr/bin/env python3
You can import some other libraries in your script, and it becomes an application::
import my_second_module
or::
from my_second_module import my_function
or::
from my_second_module import my_function as my_function_alias
or::
import my_second_module as my_second_module_alias
Assinging a variable
---------------------
::
>>> a = 42.
>>> type(a)
<class 'float'>
what is dynamic typing ? You can set some other value to the `a` variable that
has nothing to do with the previous type::
>>> a = 42j
>>> type(a)
<class 'complex'>
>>>
Functions
----------
This function::
>>> def my_function(a, b):
... """this is my func docstring"""
...
is equivalent to::
>>> def my_function(a, b):
... """this is my func docstring"""
... return None
There are no procedures in python (a procedure returns nothing). It means that
a function return always someting. Even if you don't *return* something: it
returns `None`, which is something::
>>> result = my_function(1, 2)
>>> print(result)
None
>>> print(my_function(1, 2))
None
**In python, a function is... an object**. Yes. What is a docstring's function
? A Docstring is the `__doc__` attribute of the `my_function` object::
>>> my_function.__doc__
'this is my func docstring'
>>>
In python, absolutely everything is an object... even the functions::
>>> type (my_function)
<class 'function'>
>>>
A function is an instance of the `function` class.
Unnamed arguments in a function::
>>> def my_fonction(*args, **kwargs):
... print("arguments : ", str(args))
... print("named argumments : ", str(kwargs))
...
>>> my_fonction("toto", "titi", tutu=2, tata=3)
arguments : ('toto', 'titi')
named argumments : {'tata': 3, 'tutu': 2}
>>>
The *samouraï* rule
~~~~~~~~~~~~~~~~~~~~
A function shall return the expected result, or... kill itself
(that is, raise and exception).
>>> def function_raise(x):
... if not type(x) == int:
... raise TypeError("Not the right type")
... else:
... return x + 1
...
>>> try:
... e = function_raise("une string")
... except TypeError, e:
... print e
...
Not the right type
>>

View File

@ -0,0 +1,7 @@
stands for **example**
ipython and pandas examples here
jupyter notebook Pandas.ipynb

View File

@ -0,0 +1,13 @@
The standard library
====================
.. glossary::
standard library
"There must be an obvious way to do it".
One of the basic rules. That's why you must have a look at the SDL_
.. _`SDL`: http://docs.python.org/3/library/index.html

View File

@ -0,0 +1,13 @@
Utilities
=========
duration
--------
The :mod:`timeit` module lets you measure the execution
time of small bits of Python code
.. literalinclude:: ../src/duration.py