Ahmed Kachkach <ahmed.kachkach@gmail.com> - ETIC / INSA de Lyon - Novembre 2013
Fonctions, classes, modules, ...
n = '42'
n = int(n)
n /= 2.5
Mutable: list / set / dict"Python", 'a', "a" -> str 12390, -52, 0 -> int
3.14, -1.0, 0.0 -> float
(1,2), ('a',-1.0,42) -> tuple
["Python", 3.14, 300, [1, 2] ] -> list
{2, 3, 3, 3, 4, 5, 3, 1} (== {2, 3, 4, 5, 1}) -> set {"Pizza au thon": 8.25, "Pizza pepperoni": 9.25} -> dict
ingredients = ['Oignon', 'Tomate', 'Steak']
ingredients.append('Oeuf')
# ['Oignon', 'Tomate', 'Steak', 'Oeuf']
ingredients += ['Sel', 'Cumin']
# ['Oignon', 'Tomate', 'Steak' , 'Oeuf', 'Sel', 'Cumin']
ingredients.pop(1)
# ['Oignon', 'Steak', 'Oeuf', 'Sel', 'Cumin']
liste_variee = ['Du texte', 42, ['Une', 'sous-liste'], (12, 0), 42]
mon_set = {'a', 'b', 'a', 'c', 'e', 'c'}
# {'a', 'b', 'c', 'e'}
mon_set = set([1, 2, 1, 1, 3, 2])
# {1, 2, 3}
mon_set.add(42)
# {1, 2, 3, 42}
mon_set.remove(42)
# {1, 2, 3}
mon_dico = dict()
mon_dico['canard'] = "Animal amphibien" mon_dico['poney'] = 42 mon_dico.items() # [('canard', "Animal amphibien"), ('poney', 42) ] mon_dico == {'canard': "Animal amphibien", 'poney' : 42} del mon_dico['poney'] # {'canard': "Animal amphibien"}
name = "Sésame Ouvre Toi"
name.lower() == "sésame ouvre toi"
name.replace("Sésame", "Porte") == "Porte Ouvre Toi"
"mon.nom@domain.com".split('@') == ["mon.nom", "domain.com"]
"ahmed.kachkach@insa-lyon.fr".endswith("@insa-lyon.fr") == True
"{} {}!".format("Hello", "world") == "Hello world!"
Conditions (sexistes !)x = 2.04
x += 1.1
alpha, beta = 'a', "b"
x = y = 0
un_dictionnaire = dict()
if (sexe == 'm' and salaire > 2500) or (sexe == 'f' and cuisine):
print "Tu es mariable !"
elif name in ["Emma Stone", "Brad Pitt", "Catherine Zeta-Jones"]: print "Mouais. Ça se discute."
else: print "Tu va mourir seul (ou avec tes 11 chats)."
ma_liste[i:j] # de l'élément d'indice i inclus à l'élém. d'indice j exclus
ma_liste[i:] # de l'élément d'indice i à la fin
ma_liste[:j] # du début à l'élément d'indice j exclus
nains = ["Timide", "Atchoum", "Joyeux", "Simplet"]
for nain in nains:
print "{} est un nain".format(nain)
for i, nain in enumerate(nains):
print "{} se trouve à la place {}".format(nain, i)
liste_prix = {'Tomate': 2.5, 'Oignon': 0.95, 'Cake': 3.2}
for produit, prix in liste_prix.items():
print "{} coûte {}€".format(produit, prix)
while len(nains) < 10:
nains.append("Nain #{}".format(len(nains)))
menu = ['oeuf mayo', 'spaghettis', 'oeufs durs', 'steak']
menu_sain = [plat.capitalize() for plat in menu if not 'oeuf' in plat]
# ['Spaghettis', 'Steak']
ipt = "aHmed@kAc##HkACh#.com;aKachkACh@i##nsA-LY#on.fR;InFo@clUB#iC.cOm"
emails = [mail.lower().replace('#', '') for mail in ipt.split(';')]
# ["ahmed@kachkach.com", "akachkach@insa-lyon.fr", "info@clubic.com"]
{email.split('@')[1] : email.split('@')[0] for email in emails}
# {'kachkach.com' : 'ahmed', 'insa-lyon.fr': 'akachakch', 'clubic.com': 'info' }
def une_fonction(arg_obligatoire, arg_optionnel=10): r = arg_obligatoire * arg_optionnel arg_obligatoire = 300 # ne sert à rien return r
une_fonction # <function une_fonction at 0x000000000022AD828> une_fonction.func_name # 'une_fonction' une_fonction(42) == une_fonction(42, arg_optionnel=10)
class Pipeau(object):
def __init__(self, puissance=5):
self.puissance = puissance
def jouer(self):
print "tututu" * self.puissance
class Saxophone(Pipeau):
attribut_de_classe = "Epic ___ Guy"
def __init__(self, puissance=20, matiere="Bronze"):
super(Saxophone, self).__init__(puissance)
self.matiere = matiere
def jouer(self):
print "popopo" * self.puissance
depart_if = Pipeau()
depart_gi = Saxophone(100, matiere="Carton")
# Lecture itérative fichier = open('notes_eleves') for ligne in fichier: print ligne fichier.close()
# Lecture en un coup fichier = open('autes_notes') print fichier.read() fichier.close()
# Écriture fichier = open('fichier_ecriture', 'w') fichier.write('Bla bla bla') fichier.close()
fichier = open('mon_fichier.txt', 'w+')
with open('mon_fichier.txt', 'w') as fichier:
fichier.write('a\n')
fichier.write('b\n')
try:
f = open('fichier_inexistant') except IOError as e: print "Le fichier '{}' n'existe pas".format(e.filename) print "Exception: {}".format(e)
poids = -25
if poids < 0:
raise ValueError("Poids négatif. Menteur !")
Riche librairie standard ("Python comes with batteries included") : networking, parsing, multiprocess, gestion de dossiers, appels système, etc.
import urllib2
print urllib2.urlopen('http://google.com').read()
# <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><title>Google</title>...
sudo apt-get install python-pip
# ou
sudo easy_install pip
2) Puis installez facilement n'importe quelle librairie
sudo pip install requests
sudo pip install flask
sudo pip install lxml
3) Profit !!!111§§§§§import lxml.html
url = "http://www.google.com/search?q={}"
query = raw_input("Que souhaitez vous chercher? ")
q_url = url.format(query)
print [n.text_content() for n in lxml.html.parse(q_url).xpath('//h3')]
Ahmed Kachkach <ahmed.kachkach@gmail.com> - ETIC / INSA de Lyon - Novembre 2013