En pratique : Différence entre versions
De TARENTINO
Aller à la navigationAller à la recherche| Ligne 23 : | Ligne 23 : | ||
== Exercices == | == Exercices == | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
=== Python Niveau 2 (Alex) === | === Python Niveau 2 (Alex) === | ||
<table> | <table> | ||
Version du 26 mars 2020 à 18:05
Array
Réferences: Doctor Python Pythonnerie sdz.tdct.org Python en ligne
En pratique
- Appliquons maintenant la théorie à la pratique.
- Tout n'est pas encore intégré
Infos utiles
- Connaitre la version de Python
1 import sys
2 print(sys.version_info)
Index des modules d'extension Python
Exercices
Python Niveau 2 (Alex)
Exercice Hello Word
1 #!/usr/bin/env python3
2 print("Hello, world ! bientôt l'été")
Hello, world ! bientôt l'été
Exercice Hello Word compatible Python 2 et Python 31 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 from __future__ import print_function
4 print("hello, world ! bientôt l'été")
Hello, world ! bientôt l'été
Python 2: print "bonjour"
Python 3: print("bonjour")
Python 2 Python 3
print "Bonjour" → print("Bonjour")
print "Bonjour", variable1 → print("Bonjour", variable1)
print "\n".join([x, y]) → print(x, y, sep="\n")
print >> sys.stderr, "erreur" → print("Erreur", file=sys.stderr)
print "une ligne ", → print("une ligne", end="")
ExceptionsPython 2 Python 3
raise IOError, "file error" → raise IOError("file error")
raise "Erreur 404" → raise Exception("Erreur 404!")
raise TypeError, msg, tb → raise TypeError.with_traceback(tb)
Changement de nom de modulesPython 2 Python 3 _builtin__ → builtins ConfigParser → configparser copy_reg → copyreg cPickle → pickle Queue → queue repr → reprlib SocketServer → socketserver Tkinter → tkinter _winreg → winreg thread → _thread dummy_thread → _dummy_thread markupbase → _markupbase RéorganisationPython 2 Python 3 xrange() → range() reduce() → functools.reduce() intern() → sys.intern() unichr() → chr() basestring() → str() long() → int() itertools.izip() → zip() itertools.imap() → map() itertools.ifilter() → filter() itertools.ifilterfalse() → itertools.filterfalse() cookielib → http.cookiejar Cookie → http.cookies htmlentitydefs → html.entities HTMLParser → html.parser httplib → http.client Dialog → tkinter.dialog FileDialog → tkinter.FileDialog ScrolledText → tkinter.scolledtext SimpleDialog → tkinter.simpledialog Tix → tkinter.tix Tkconstants → tkinter.constants Tkdnd → tkinter.dnd tkColorChooser → tkinter.colorchooser tkCommonDialog → tkinter.commondialog tkFileDialog → tkinter.filedialog tkFont → tkinter.font tkMessageBox → tkinter.messagebox tkSimpleDialog → tkinter.simpledialog robotparser → urllib.robotparser urlparse → urllib.parse cStringIO.StringIO() → io.StringIO UserString → collections.UserString UserList → collections.UserList Nombres 1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 nb_entier = 42
4 print(type(nb_entier))
5 nb_long = 300000000000
6 print(type(nb_long))
7 nb_complexe = 2+4j
8 print(type(nb_complexe))
9 # Changement dynamique de type
10 for nb in range(20):
11 nb2 = nb ** nb
12 print(nb2, type(nb2))
13 # Modulo
14 print("9 % 5 =", 9 % 5)
15 # Puissance
16 print("2 ** 4 =", 2 ** 4)
17 print('=' * 20)
18 # Constructeurs
19 nb = int("42")
20 print(nb, type(nb))
21 nb = float("42.123")
22 print(nb, type(nb))
23 nb = complex("2+5j")
24 print(nb, type(nb))
25 print('=' * 20)
26 print(hex(456))
27 print(oct(456))
28 print(bin(456))
29 print('=' * 20)
30 print(chr(65))
31 print(ord('A'))
Chaine 1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 ch = "Une chaine double quote peut contenir des ' "
4 ch2 = 'Une chaine simple quote peut contenir des " '
5 ch3 = """Une chaine
6 qui s'etend
7 sur
8 plusieurs lignes"""
9 ch4 = "on peut mettre antislash pour afficher une \" dans une chaine double quote"
10 print(ch, type(ch))
11 print(ch2, type(ch2))
12 print(ch3, type(ch3))
13 print(ch4, type(ch4))
14 print('=' * 20)
15 # Unicode
16 ch_sans_unicode = "été"
17 ch_avec_unicode = "été"
18 print(ch_sans_unicode, type(ch_sans_unicode))
19 print(ch_avec_unicode, type(ch_avec_unicode))
20 print("Taille de la chaine ch_sans_unicode:", len(ch_sans_unicode))
21 print("Taille de la chaine ch_avec_unicode:", len(ch_avec_unicode))
22 print('=' * 20)
23 # Chaine raw
24 ch_sans_raw = 'une chaine\tavec\ndes caractères spéciaux'
25 ch_avec_raw = r'une chaine\tavec\ndes caractères spéciaux'
26 print(ch_sans_raw, type(ch_sans_raw))
27 print(ch_avec_raw, type(ch_avec_raw))
28 print('=' * 20)
29 ch = "bonjour tout le monde"
30 print("ch:", ch)
31 # Indicage
32 print("ch[2]:", ch[2])
33 print("ch[-2]:", ch[-2])
34 # Tranches de valeurs
35 print("ch[3:5]:", ch[3:5])
36 print("ch[-8:-2]:", ch[-8:-2])
37 print("ch[3:-2]:", ch[3:-2])
38 print("ch[3:]:", ch[3:])
39 print("ch[:-2]:", ch[:-2])
40 # Multiplication d'une chaine par un entier
41 ch2 = 'hello' * 4
42 print(ch2)
43 # On peut itérer sur une séquence
44 for car in ch:
45 print(car)
46 # Concaténation
47 ch3 = ch + ch2
48 print(ch3)
49 # Appartenance
50 print("'xyz' in 'bonjour' ?", 'xyz' in 'bonjour')
51 print("'njo' in 'bonjour' ?", 'njo' in 'bonjour')
52 print('=' * 20)
53 # Masque d'affichage
54 notes = "Eleve: %-10s Age: %2d Note: %5.2f"
55 print("Masque:", notes)
56 print("Note Bart:", notes % ('Bart', 10, 5.55))
57 # Masque d'affectation
58 note_lisa = notes % ('Lisa', 12, 18.42)
59 print("note_lisa:", note_lisa)
60 print('=' * 20)
61 liste = [ ('Bart', 10, 1.23),
62 ('Lisa', 12, 19.99),
63 ('Homer', 42, 0.1)
64 ]
65 for prenom, age, note in liste:
66 print(notes % (prenom, age, note))
67 print('=' * 20)
68 for var in liste:
69 print(var, type(var))
70 #print(notes % (var[0], var[1], var[2]))
71 print(notes % var)
72 # Test d'égalité : ==
73 ch = 'hello'
74 ch2 = 'hello'
75 print("ch == ch2 ?", ch == ch2)
76 # S'agit-il du même objet en mémoire : is
77 print("ch is ch2 ?", ch is ch2)
78 print('=' * 20)
79 # La classe chaine de caractères fournit un ensemble de méthodes
80 print("ch.upper():", ch.upper())
81 print("ch.center(40):", ch.center(40,'*'))
82 print('=' * 20)
83 # split
84 ch = "bonjour tout le monde"
85 print("ch.split()", ch.split())
86 print("ch.split(' ')", ch.split(' '))
87 print("ch.split('o')", ch.split('o'))
88 print('=' * 20)
89 # replace
90 ch2 = ch.replace('o', 'X')
91 print("ch2:", ch2)
92 print("ch (non modifiée):", ch)
93 ch2 = ch.replace('jour', 'soir')
94 print("ch2:", ch2)
95 print('=' * 20)
96 # find
97 print("'ou' apparait a la position:", ch.find('ou'))
98 print('=' * 20)
99 # format
100 print("info: {0} {1} {2} {1} {0}".format('a', 'b', 'c'))
101 print('=' * 20)
102 # Espace de noms du programme principal
103 print(dir())
104 print('=' * 20)
105 # Attributs et méthodes d'une classe d'objet, ex. une chaine
106 print(dir(''))
107 print('=' * 20)
108 # Les chaines documentaires
109 def fct():
110 "Ceci est la documentation de ma fonction"
111 pass
112 print("Doc de la fonction fct():", fct.__doc__)
113 print('=' * 20)
114 print("Documentation de la classe str():", str.__doc__)
115 print('=' * 20)
116 print("Documentation de la méthode split de la classe str():", str.split.__doc__)
117 print('=' * 20)
118 print("Documentation de la méthode find de la classe str():", str.find.__doc__)
|
Python Niveau 3 (Jean François)
Loto
1 # loto_01.py
2 import random
3 nb_boules=49
4 boules = [ x for x in range(1,nb_boules+1) ]
5 tirage = []
6 for boule in range(5):
7 une_boule = boules[ random.randint(1,len( boules )) - 1 ]
8 tirage.append( une_boule )
9 boules.remove(une_boule)
10 chance = random.randint(1,10)
11 print(tirage, chance)
12 tirage.sort()
13 print(tirage)
Un tirage est composé de : - Un numéro de tirage - Les 5 boules - Le numéro Chance
1 # loto_02.py
2 # v2: on utilise une Classe
3 """ Un module pour gerer des tirages de Loto """
4 import random
5
6 class Loto:
7 """ Permet d'instancier des tirages de Loto """
8 nb_boules=49
9 les_tirages = []
10
11 def __init__(self, num_tirage):
12 """ Cree un tirage [num, les 5 boules, numero change]) """
13 tirage_5_boules = []
14 boules = [ x for x in range(1,Loto.nb_boules+1) ]
15 for boule in range(5):
16 une_boule = boules[ random.randint(1,len( boules )) - 1 ]
17 tirage_5_boules.append( une_boule )
18 boules.remove(une_boule)
19
20 chance = random.randint(1,10)
21 tirage_5_boules .sort()
22 self.num = num_tirage
23 self.cinqBoules = tirage_5_boules
24 self.chance = chance
25 Loto.les_tirages.append( self )
26
27 def __str__(self):
28 """ conversion d'un tirage en chaine """
29 ch = "Numero: " + str(self.num) + " ,5 boules: "
30 for i in range(5): ch += str( self.cinqBoules[i] ) + " - "
31 ch += " ,Numero chance: "+ str(self.chance)
32 return ch
33
34 @classmethod
35 def getUnTirage(cls, num ):
36 """ Exemple de methode de classe """
37 for t in cls.les_tirages:
38 if t.num == num: return t
39 return None
40
41 if __name__ == "__main__":
42 num = 100
43 for i in range(5):
44 un_tirage = Loto(num+i)
45 le_dernier_tirage = un_tirage
46 for t in Loto.les_tirages:
47 print( t.num, t.cinqBoules, t.chance)
48
49 print("Dernier: %s\n" % (str(le_dernier_tirage) ))
50 try:
51 num = int( input("Numero de tirage ? ") )
52 except:
53 print("ERREUR: saisie incorrect")
54 else:
55 print("Tirage 103: %s\n" % (str( Loto.getUnTirage( num ) ) ) )
Probabilité course lièvre/tortue
1 import lievre.py
2 nb_coup:int=1000000
3 i:int=0
4 while i < nb_coup:
5 lievre.py
6 i=i+1
1 ###### lievre2.py: le lievre et la tortue
2 from random import *
3 total= 0
4 unGagnant = False
5 gagnant = None
6 while not unGagnant:
7 de = randint(1,6)
8 print ("Valeur du lance: ", de )
9 total = total + de
10 if de == 6 :
11 gagnant = "Lievre"
12 unGagnant = True
13 elif total >= 6:
14 gagnant = "Tortue"
15 unGagnant = True
16 print ("Gagnant: ", gagnant )
1 from random import *
2 lievre:int=0
3 i:int=1000000
4 dep=i
5 r:int=0
6 def golievre():
7 total= 0
8 while True:
9 de = randint(1,6)
10 if de == 6 :
11 r=1
12 break
13 total = total + de
14 if total >= 6:
15 r=0
16 break
17 return r
18 # START
19 while i > 0:
20 retour=golievre()
21 #print(retour)
22 if retour==1:
23 lievre+=1
24 i-=1
25 lievre_gagne=lievre
26 tortue_gagne=dep-lievre
27 pourcent=100*lievre_gagne/(tortue_gagne+lievre_gagne)
28 print(lievre, 'sur 1000000', pourcent)
|
Sauvegarde
- Je travaille sur un système Linux, je réinstalle quelques fois mon système.
- J'ai besoin pour cela de créer une sauvegarde.
Cahier des charges
- En utilisant au maximum Python, et de façon sécurisée.
- voici les différentes parties à sauvegarder sur un autre support:
- /etc
- /var
- /home
- /root
- Établir la liste de tous les programmes installés pour les réinstaller.
- Sauvegarder les crontab.