initiation_a_python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
initiation_a_python [2018/07/05 15:36] – [Boucle] serge | initiation_a_python [2021/08/21 13:41] (Version actuelle) – [PEP8] serge | ||
---|---|---|---|
Ligne 1: | Ligne 1: | ||
- | ======Initiation à python====== | + | ======Python: |
- | Ce tuto est très inspiré de: [[https:// | + | |
- | =====Python===== | + | |
- | ====Installation==== | + | |
- | Linux: c'est déjà installé. Win$ et Mac: débrouillez-vous ? | + | |
- | ====Interpréteur==== | + | <WRAP center round box 80% centeralign> |
- | Je décide de [[atelier_python_niveau_1# | + | **[[toutes_les_pages_sur_python|Toutes les pages sur Python]] sans les pages sur {{tagpage> |
+ | </ | ||
+ | |||
+ | <WRAP center round box 80% centeralign> | ||
+ | **{{tagpage> | ||
+ | </ | ||
+ | |||
+ | Cet atelier est animé comme un TD. Aucun cours théorique, que de la pratique avec des exemples fun 8-)\\ | ||
+ | Et surtout je ne commence pas par **Chapitre 1 ** POO Programmation Orienté Objet. | ||
+ | |||
+ | Ce tuto est très inspiré de Apprenez à programmer en Python de Vincent Le Goff [[http:// | ||
+ | |||
+ | * **[[https:// | ||
+ | * **[[https:// | ||
+ | |||
+ | =====Les sources complètes de ces TD===== | ||
+ | * https:// | ||
+ | * **[[https:// | ||
+ | |||
+ | =====Installation===== | ||
+ | * **[[python_installation]]** | ||
=====Quelques commandes===== | =====Quelques commandes===== | ||
+ | ====Tester dans un navigateur==== | ||
+ | * **[[https:// | ||
+ | {{ : | ||
+ | |||
+ | ===Un terminal quelconque=== | ||
+ | Ouvrir un terminator: | ||
+ | {{ : | ||
+ | | ||
+ | =====Premiers pas===== | ||
+ | Ouvrir un terminator | ||
+ | bpython3 | ||
<code python> | <code python> | ||
bpython version 0.16 on top of Python 3.5.3 / | bpython version 0.16 on top of Python 3.5.3 / | ||
Ligne 26: | Ligne 53: | ||
>>> | >>> | ||
</ | </ | ||
- | |||
- | <code python></ | ||
===int float string opération=== | ===int float string opération=== | ||
Ligne 48: | Ligne 73: | ||
===Mots clé=== | ===Mots clé=== | ||
+ | * https:// | ||
<code python> | <code python> | ||
- | and as class def elif else except | + | False |
- | lambda | + | None break except |
+ | True class finally | ||
+ | and continue | ||
+ | as | ||
+ | assert | ||
+ | async elif | ||
</ | </ | ||
- | ===Boolean et rien=== | ||
- | <code python> | ||
- | True False None | ||
- | </ | ||
=====Type de données===== | =====Type de données===== | ||
<code python> | <code python> | ||
1 # int | 1 # int | ||
3.14 # float | 3.14 # float | ||
- | "Labbomedia" | + | "Labomedia" |
[1, 2, 3] # list | [1, 2, 3] # list | ||
{" | {" | ||
</ | </ | ||
+ | |||
=====Fonction===== | =====Fonction===== | ||
- | |||
<code python> | <code python> | ||
>>> | >>> | ||
Ligne 73: | Ligne 100: | ||
Hello, World! | Hello, World! | ||
</ | </ | ||
- | |||
- | |||
=====Ouvrir Geany===== | =====Ouvrir Geany===== | ||
+ | ====Geany: un éditeur sympa multiplateforme==== | ||
+ | * **[[python_installation# | ||
+ | ====Premier pas avec geany==== | ||
Créer un nouveau fichier et l' | Créer un nouveau fichier et l' | ||
Ligne 99: | Ligne 127: | ||
print(d + e) | print(d + e) | ||
- | print(str(a) + e) | + | print(a + e) |
print(a+e) | print(a+e) | ||
+ | |||
+ | print(f" | ||
</ | </ | ||
+ | |||
+ | |||
+ | =====Les différents types de variable===== | ||
+ | ====Liste==== | ||
+ | <code python> | ||
+ | l = [1, 2, 3, 4, 5] | ||
+ | # On compte à partir de zéro | ||
+ | l[1] = 2 | ||
+ | </ | ||
+ | * [[http:// | ||
+ | * [[https:// | ||
+ | ====Dictionnaire==== | ||
+ | <code python> | ||
+ | d = {1: " | ||
+ | # Les clés doivent être immuables | ||
+ | d[3] = " | ||
+ | print(d) | ||
+ | </ | ||
+ | |||
+ | [[http:// | ||
+ | |||
+ | ====Tuples==== | ||
+ | <code python> | ||
+ | t = (" | ||
+ | print(t) | ||
+ | t = " | ||
+ | print(t) | ||
+ | </ | ||
+ | |||
+ | [[http:// | ||
+ | |||
+ | ====Set==== | ||
+ | Liste toutes les valeurs existantes, il n'y a pas de doublons. | ||
+ | <code python> | ||
+ | my_set = {1, 2, 3, 4, 2, 1} | ||
+ | print(my_set) | ||
+ | </ | ||
+ | |||
=====Condition===== | =====Condition===== | ||
+ | ====si oui si non==== | ||
<code python> | <code python> | ||
a = -6 | a = -6 | ||
Ligne 125: | Ligne 194: | ||
</ | </ | ||
+ | **Indentation: | ||
====Opérateur de comparaison==== | ====Opérateur de comparaison==== | ||
+ | * https:// | ||
<code python> | <code python> | ||
== != < > <= >= | == != < > <= >= | ||
Ligne 132: | Ligne 202: | ||
- | |||
- | =====Exercice Bissextile===== | ||
- | Trouver si une année est bissextile: | ||
- | <code text> | ||
- | Si une année n'est pas multiple de 4, elle n'est pas bissextile | ||
- | Si elle est multiple de 4, on regarde si multiple de 100 | ||
- | Si oui, on regarde si multiple de 400 | ||
- | Si oui, elle est bissextile | ||
- | Si non, elle n'est pas bissextile | ||
- | Si non, elle est bissextile | ||
- | </ | ||
- | |||
- | <file python bissextile.py> | ||
- | # Programme testant si une année est bissextile | ||
- | |||
- | # Demande de l' | ||
- | annee = input(" | ||
- | etc ...... | ||
- | </ | ||
- | |||
- | Deux réponses: **[[https:// | ||
=====Boucle===== | =====Boucle===== | ||
- | Table du 4: | + | **Table du 4** |
<code python> | <code python> | ||
print(" | print(" | ||
Ligne 162: | Ligne 211: | ||
print(" | print(" | ||
</ | </ | ||
- | Les répétitions sont très sales ! | + | **Les répétitions sont très sales !** |
<code python> | <code python> | ||
i = 0 | i = 0 | ||
Ligne 169: | Ligne 218: | ||
i += 1 | i += 1 | ||
</ | </ | ||
- | ou encore | + | **ou encore** |
<code python> | <code python> | ||
for i in range(10): | for i in range(10): | ||
Ligne 178: | Ligne 227: | ||
print(str(i) + " x 4 =", i * 4) | print(str(i) + " x 4 =", i * 4) | ||
</ | </ | ||
- | =====Itération===== | + | **Itération** |
+ | <code python> | ||
+ | chaine | ||
+ | for lettre in chaine: | ||
+ | print(lettre) | ||
+ | </ | ||
=====Fonctions===== | =====Fonctions===== | ||
+ | ====Pourquoi faire des fonctions ou des classes ?==== | ||
+ | * Pour éviter les répétitions, | ||
+ | * Pour structurer le projet. | ||
+ | * Pour tester des bouts de code individuellement. | ||
+ | * Pour éviter les problèmes avec les variables globales. | ||
+ | * Pour pouvoir réutiliser des bouts de codes. | ||
+ | * Permettre un travail en équipe en découpant un projet en bout de projet indépendant. | ||
- | ===Return=== | + | **Une fonction fait une chose. Une class fait une chose** |
+ | * [[http:// | ||
- | =====Module===== | + | ====Simple==== |
+ | <code python> | ||
+ | def ma_fonction(): | ||
+ | print(" | ||
- | =====Module get object===== | + | def ta_fonction(a): |
+ | print(a) | ||
- | [[https://github.com/sergeLabo/mylabotools/ | + | def sa_fonction(a, |
- | =====Package===== | + | while i < n: |
+ | print(a, i) | ||
+ | |||
+ | ma_fonction() | ||
+ | ta_fonction(" | ||
+ | ta_fonction(" | ||
+ | sa_fonction(5, | ||
+ | </code> | ||
+ | |||
+ | ====Arguments par défaut==== | ||
+ | <code python> | ||
+ | def fonct(a=1, b=2, c=3): | ||
+ | print(a, b, c) | ||
+ | |||
+ | fonct() | ||
+ | fonct(10) | ||
+ | fonct(b=10) | ||
+ | </code> | ||
+ | |||
+ | ====Return==== | ||
+ | Une fonction sans return retourne None | ||
+ | <code python> | ||
+ | def test1(): | ||
+ | """ | ||
+ | print(" | ||
+ | |||
+ | def test2(): | ||
+ | """ | ||
+ | print(" | ||
+ | return " | ||
+ | |||
+ | a = test1() | ||
+ | print(a) | ||
+ | |||
+ | b = test2() | ||
+ | print(b) | ||
+ | </ | ||
+ | |||
+ | La fonction s' | ||
+ | |||
+ | <code python> | ||
+ | def test(a): | ||
+ | if a < 0: | ||
+ | print(" | ||
+ | return 1 | ||
+ | else: | ||
+ | print(" | ||
+ | return 0 | ||
+ | print(" | ||
+ | |||
+ | test(1) | ||
+ | test(-1) | ||
+ | </code> | ||
+ | |||
+ | ====Fonctions prédéfinies==== | ||
+ | <code python> | ||
+ | print( abs(-20), | ||
+ | | ||
+ | | ||
+ | | ||
+ | | ||
+ | </code> | ||
+ | =====Module Package Import===== | ||
+ | ===def=== | ||
+ | Une ou des fonctions dans un fichier est un module. Plusieurs modules font un package. | ||
+ | |||
+ | ===Module simple=== | ||
+ | |||
+ | <file python called.py> | ||
+ | def je_suis_appeler(phrase): | ||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | <file python I_call.py> | ||
+ | from called import je_suis_appeler | ||
+ | |||
+ | p = "Une phrase exemple | ||
+ | je_suis_appeler(p) | ||
+ | </ | ||
+ | |||
+ | Exécuter: | ||
+ | python3 I_call.py | ||
+ | |||
+ | ===Bibliothèque standard=== | ||
+ | * **[[https:// | ||
+ | |||
+ | ===time=== | ||
+ | <code python> | ||
+ | import time | ||
+ | |||
+ | print(dir(time)) | ||
+ | print(" | ||
+ | </ | ||
+ | |||
+ | <code python> | ||
+ | import datetime | ||
+ | |||
+ | print(dir(datetime)) | ||
+ | print(" | ||
+ | </ | ||
=====Exception===== | =====Exception===== | ||
+ | <code python> | ||
+ | try: | ||
+ | resp = 1 / 0 | ||
+ | except: | ||
+ | print(" | ||
+ | |||
+ | try: | ||
+ | resp = 1 / 0 | ||
+ | except ZeroDivisionError as e: | ||
+ | print(e) | ||
+ | </ | ||
+ | |||
+ | **[[https:// | ||
+ | ===Pass=== | ||
+ | **Du sale** | ||
+ | <code python> | ||
+ | try: | ||
+ | resp = 1 / 0 | ||
+ | return resp | ||
+ | except: | ||
+ | pass | ||
+ | </ | ||
+ | **Du propre** | ||
+ | Ne jamais passer les erreurs sous silence, ou les faire taire explicitement. | ||
+ | <code python> | ||
+ | def exemple_propre(a): | ||
+ | try: | ||
+ | return 1 / a | ||
+ | except ZeroDivisionError as e: | ||
+ | print(e) | ||
+ | return None | ||
+ | except: | ||
+ | return None | ||
+ | </ | ||
+ | |||
+ | **Pass pour du code en construction** | ||
+ | <code python> | ||
+ | def je_multiplie(): | ||
+ | pass | ||
+ | | ||
+ | def j_imprime(): | ||
+ | pass | ||
+ | </ | ||
+ | |||
+ | =====Type===== | ||
+ | Python est fortement typé: il utilise le **[[https:// | ||
+ | |||
+ | <code python> | ||
+ | t = type({1, 2, 3, 4, 2, 1}) | ||
+ | print(t) | ||
+ | </ | ||
+ | =====Variables globales et locales, espaces de noms===== | ||
+ | Le fichier pi.py n'a rien à voir avec pi ou PI ou pi() | ||
+ | |||
+ | <code python pi.py> | ||
+ | def pi(): | ||
+ | return " | ||
+ | </ | ||
+ | |||
+ | <code python jeu.py> | ||
+ | from pi import pi as pipi | ||
+ | |||
+ | # Toutes les variables globales en majuscule | ||
+ | PI = 3.14 | ||
+ | |||
+ | # Ce pi est une variable globale | ||
+ | pi = pipi() | ||
+ | |||
+ | def print_pi(pi): | ||
+ | """ | ||
+ | print(pi) | ||
+ | | ||
+ | def print_a(a): | ||
+ | print(a) | ||
+ | | ||
+ | print_pi(3) | ||
+ | print_a(3) | ||
+ | print_pi(PI) | ||
+ | print_pi(pi) | ||
+ | print_pi() | ||
+ | </ | ||
+ | |||
+ | |||
+ | =====POO===== | ||
+ | |||
+ | ====Programmation Orientée Objet==== | ||
+ | **[[https:// | ||
+ | |||
+ | ====Pourquoi des class ?==== | ||
+ | **[[initiation_a_python# | ||
+ | |||
+ | ====Les class permettent de créer des objets==== | ||
+ | <code python> | ||
+ | class Subliminale: | ||
+ | pass | ||
+ | |||
+ | class Minimale: | ||
+ | print(" | ||
+ | |||
+ | class MyTest: | ||
+ | def my_test(self): | ||
+ | print(" | ||
+ | |||
+ | class Bicycle: | ||
+ | """ | ||
+ | |||
+ | def __init__(self, | ||
+ | """ | ||
+ | | ||
+ | self.color = color | ||
+ | self.kind = kind | ||
+ | |||
+ | s = Subliminale() | ||
+ | print(type(s)) | ||
+ | |||
+ | m = Minimale() | ||
+ | |||
+ | b = Bicycle(" | ||
+ | print(b.color) | ||
+ | print(b.kind) | ||
+ | |||
+ | </ | ||
+ | |||
+ | |||
+ | =====La philosophie Python===== | ||
+ | ====Zen of python==== | ||
+ | Dans l' | ||
+ | <code python> | ||
+ | import this | ||
+ | </ | ||
+ | <code text> | ||
+ | Préfère : | ||
+ | la beauté à la laideur, | ||
+ | l' | ||
+ | le simple au complexe | ||
+ | et le complexe au compliqué, | ||
+ | le déroulé à l' | ||
+ | l' | ||
+ | Prends en compte la lisibilité. | ||
+ | Les cas particuliers ne le sont jamais assez pour violer les règles. | ||
+ | Mais, à la pureté, privilégie l' | ||
+ | Ne passe pas les erreurs sous silence, | ||
+ | ... ou bâillonne-les explicitement. | ||
+ | Face à l' | ||
+ | Sache qu'il ne devrait y avoir qu'une et une seule façon de procéder, | ||
+ | même si, de prime abord, elle n'est pas évidente, à moins d' | ||
+ | Mieux vaut maintenant que jamais. | ||
+ | Cependant jamais est souvent mieux qu' | ||
+ | Si l' | ||
+ | Si l' | ||
+ | Les espaces de nommage ! Sacrée bonne idée ! Faisons plus de trucs comme ça. </ | ||
+ | ====PEP8===== | ||
+ | |||
+ | * **[[https:// | ||
+ | |||
+ | |||
+ | **Avec python, nous sommes toujours entre adultes responsables.** | ||
+ | * C'est toujours possible d’enfreindre une règle. | ||
+ | * Par contre, certaines règles sont obligatoires: | ||
+ | * [[https:// | ||
+ | |||
+ | |||
+ | =====Recherche web===== | ||
+ | Dans un moteur de recherche, toujours en anglais, par exemple: | ||
+ | python3 download web page | ||
+ | |||
+ | Une grande majorité des réponses sera sur **[[https:// | ||
- | =====Pass===== | ||
- | {{tag> | + | {{tag> |
- | {{tag> | + |
initiation_a_python.txt · Dernière modification : 2021/08/21 13:41 de serge