Atelier 2012-02-23 : Python : Atelier de base
Sommaire
-
Atelier 2012-02-23 : Python : Atelier de base
- INTRODUCTION
-
NOTIONS DE BASE
- Interpréteur
- Syntaxe
- Variables
- Types
- Built-in : fonctions built-in et structure du langage
- Objets et namespaces
- Introspection
- Conteneurs
- Itération
- Comparaisons et opérateurs logiques
- Conditionnel
- Fichiers
- Formattage de chaînes de caractères
- Compréhension de liste
- Scripts
- Fonctions
- Import
- Modules
- Permanence de l'information
- EXERCICE
- CONCLUSION
INTRODUCTION
- Objectifs :
- coder dans l'interpréteur et explorer les bases du langage
- écrire un script qu'on fera exécuter par l'interpréteur
- Documentation
- Environnement
- éditeur texte
- interpréteur python : python, ipython
- sources :
NOTIONS DE BASE
Interpréteur
- python, ipython
- interactivité / introspection
$ ipython
Syntaxe
* commentaire : # * variables : sans $ * instructions : sans ; * blocs : sans {} * style : PEP 8 http://www.python.org/dev/peps/pep-0008/ * bris de ligne : \
Variables
* nom, valeur, référence
a = 12 b = a id(a) id(b)
Types
* typage dynamique (pas besoin déclarer) * import types
n = None # NoneType : type spécial voulant dire... rien b = True # bool : booléen... True ou False n'oubliez pas les majuscules i = 15 # int : entier f = 15.5 # float : décimal s = "chaine" # str : chaine de caractère, instancié avec "" ou '' u = u"chaîne" # unicode : chaîne de caractère unicode, instancié avec u"" ou u'' l = [] # list : liste d'objets (ordonné) t = () # tuple : liste immuable d'objets d = {} # dict : dictionnaire de données (unique, non-ordonné) ens = set([]) # set : ensemble (unique, non-ordonné)
* unpacking
a, b = 34, 56
* fortement typé (pas de transtypage implicite) * transtypage str(), int(), float(), bool(), list(), tuple(), dict(), set()
float(a)
Built-in : fonctions built-in et structure du langage
http://docs.python.org/library/fonctions.html
type(objet) # retourne le type de l'objet dir(objet) # retourne les noms derrière l'objet help(objet) # retourne l'aide callable(objet) # dit si un objet est appelable, exécutable... bool(), int(), str()... # initialisation ou transtypage getattr() isinstance(objet, Type) # teste le classe (ou type) d'un objet issubclass() super() len() min() max() open() range() raw_input() print del
Objets et namespaces
* objet.attribut * objet.methode() * objet.attribut.methode()
Introspection
* variable. [+ tab] * variable?
* type() * dir() * help()
* exploration des types
* concaténation : s1 + s2
nom = "Davin Baragiotta" prenom, nom = nom.split() nom.upper() nom.lower() nom.ljust(30) nom = [prenom.lower(), nom.lower()] username = ".".join(nom) nom = "Davin Baragiotta" username = ".".join(nom.split()).lower()
users = [] users.append(username)
Conteneurs
* imbrication : l = 1,2,3],[4,'salut',6],[7,8,9 * index : l[2], d['nom'] * slicing : l[0:2] * personne = {'nom':'x', 'prenom':'y'} * personnes = []
Itération
for item in l:
- print item.upper()
while... while year < 2005: for
- 2 à la puissance n sur string sur list
Comparaisons et opérateurs logiques
false = 0, , (), [], {}, None and, or, not < > <= >= == != x < y <= z is, is not in, not in %
Conditionnel
if 5 in liste:
- print 'hourra 5'
elif 4 in liste:
- print 'hourra 4'
else:
- print 'pas hourra'
Fichiers
- read files : open(), f.close()
- for line in open(‘hello.py’):
- print line,
- for line in open(‘hello.py’):
Formattage de chaînes de caractères
* %
Compréhension de liste
* cible = 'egypte' * contexte = [ligne for ligne in f.readlines() if cible in ligne] l = [l for l in liste if l.startswith('#')]
Scripts
* code/script.py * shebang : #! /usr/bin/env python * encoding : # -*- encoding: utf-8 -*- * if name == 'main': * raw_input()
Fonctions
* convention de nommage * output : None par défaut * input : paramètres positionnels, nommés, *args, **kwargs * portée des variables
def ma_fonction(param1, param2, *args, **kwargs):
- """Ceci est ma fonction.""" output = True return output
Import
* import module * from module import nom * from module import nom as mon_nom
* built-in : pas besoin d'import * standard library (shipped in) : import sans install * packages : importable si installé dans le path $ import sys $ sys.path
Modules
* init.py * name : nom du module, nom de fichier si importé, 'main' si exécuté (utile pour tests)
Permanence de l'information
* fichiers * sérialisation : import pickle * DB : sqlite3, mysqldb, psycopg2 * ORM : sqlalchemy
EXERCICE
CONCLUSION
* documentation + interactivité + introspection * scripts + modules * enjoy!