3. Syntaxe de base¶
3.1. Assignation de variables¶
>>> number = 10
>>> number
10
>>> name = 'Dupont'
>>> name
'Dupont'
>>> a, b = 3, 5
>>>a
3
>>>b
5
3.2. Swap¶
>>> a = 10
>>> b = 20
>>> a, b = b, a
>>> a
20
>>> b
10
4. Types de base¶
chaines « John Doe »
nombres 1 3.8
listes [1, 4, 3, « John », variable
tuples (1, 4, 3, « John », variable)
dictionnaires { “first_name”: “John”, “last_name”: « Doe », “age”: 25}
4.1. Strings¶
>>> last_name = 'Dupont'
>>> first_name = "Jean"
>>> full_name = '''jean dupont'''
4.1.1. Multilignes¶
>>> long_str ="""une longue
... chaine
... de trois
... lignes"""
>>> long_str
'une longue\nchaine\nde trois\nlignes'
>>> print long_str
une longue
chaine
de trois
lignes
4.1.2. Échappement¶
>>> school = 'ecole d\'ingenieur'
>>> print school
ecole d'ingenieur
4.1.3. Formatage de chaine¶
>>> name = 'Joe'
>>> print ('Salut {0}'.format(name))
Salut Joe
>>> print ('hello %s' % name)
hello Joe
>>> "{0} is easier than {1}".format("python", "java")
'python is easier than java'
>>>name= "Jim"
>>> `Bonjour {name}, comment ça va ?`
'Bonjour Jim, comment ça va ?
4.2. Nombres¶
>>> age = 10
>>> price = 5.2
4.2.1. Incrémentation¶
>>> a+=1
>>> a-=2
** Attention à la précisions des flottants (cf IEE 754) * ## Booléens >>> a = True >>> b = False
4.3. Réassigner¶
>>> a = 20
>>> a = 'Dupont'
4.4. Noms de variables¶
minuscules
underscores
!= keywords python
Interdits
>>> import keyword
>>> print keyword.kwlist
Dangereux
>>> dir(__builtins__)
Notamment: dict, file, id, list, str, type, sum
4.5. Variables en détail¶
Les variables sont des étiquettes Obtenir l’id dune variable >>> id(a) 140654160195904
>>> a= 10
>>> id(a)
140654160195952
>>> c=a
>>> id(c)
140654160195952 # même id
4.5.1. Mutabilité¶
>>> a = 12
>>> id(a)
140654160195904 #id a changé
4.5.2. Le type¶
>>> a = 10
>>> type (a)
<type 'int'>
4.7. Obtenir les¶
dir()
>>> a = 5
>>> dir (a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
help()
>>> help(a)
Help on int object:
class int(object)
| int(x[, base]) -> integer
|
| Convert a string or number to an integer, if possible. A floating point
| argument will be truncated towards zero.....
4.8. String methods¶
>>> name = 'john doe'
>>> name.startswith('joh')
True
>>> name.startswith('josh')
False
>>> name.startswith(('john', 'bill'))
True
>>> 'doe' in name
True
5. Listes¶
>>> [1, 2, 3, 9, 'abc', 2.8, name ]
>>> [1, 2, 3, 9, ['abc', 2.8, name] ]
>>> l = [ 'a', 'b', 'c', 'd', 'e', 'f']
Indices
>>> l[0]
'a'
>>> l[5]
'f'
>>> l[-1]
'f'
>>> l[-6]
'a'
Slices
>>> l[1:5]
['b', 'c', 'd', 'e']
>>> l[:3]
['a', 'b', 'c']
>>> l[:-2]
['a', 'b', 'c', 'd']
>>> l[2] = "X"
>>> l
['a', 'b', 'X', 'd', 'e', 'f']
Syntaxe :
seq = l[start:stop:step]
Copier une liste
>>> other_list = l[:]
>>> another_list = list(l)
Concaténation
>>> k = ['q', 'r']
>>> l+k
['a', 'b', 'c', 'd', 'e', 'f', 'q', 'r']
Ajout
>>> l = ['a', 'b']
>>> l.append('c')
['a', 'b', 'c']
Tri
>>> l = [4, 7, 9, 0]
>>> l.sort()
>>> l
[0, 4, 7, 9]
Ordre
>>> l.reverse()
>>> l
['f', 'e', 'd', 'c', 'b', 'a']
6. Tuples¶
Listes immutables
>>> t = (1, 2, 3)
>>> t = tuple(l)
>>> t
('a', 'b', 'c', 'd', 'e', 'f')
>>> l = list(t)
>>> l
['a', 'b', 'c', 'd', 'e', 'f']
constructeur = comma
>>> t = (1)
>>> t
1
>>> t = (1,)
>>> t
(1,)
>>> t =1,
>>> t
(1,)
>>> t =1, 2
>>> t
(1, 2)
Swap : a, b = b, a
Assignation : x, y = 1, 2
7. Dictionnaires¶
<=> Hashtable key: immutables (numbers, str, tuples) values: whatever
>>> d = {'first_name' : 'john', 'last_name': 'doe'}
>>> d['first_name']
'john'
>>> d['age']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'age'
>>> d.get('age', 'Inconnu')
'Inconnu'
Delete
>>> del d['last_name']
>>> d
{'city': 'toulon', 'first_name': 'john'}
Méthodes utiles
>>> d.keys()
['first_name', 'last_name']
>>> d.values()
['john', 'doe']
>>> d.items()
[('first_name', 'john'), ('last_name', 'doe')]
Licence: CC-BY Providenz