Skip to content

Instantly share code, notes, and snippets.

@alain-andre
Last active December 29, 2015 20:19
Show Gist options
  • Save alain-andre/7723286 to your computer and use it in GitHub Desktop.
Save alain-andre/7723286 to your computer and use it in GitHub Desktop.
Liste des commandes de base de Python

Décalarations

String

tring = "truc"

Integer

integer = 0

Lists

list = [1, 'truc', ['apple', 'orange', 'banana']]

>>> print list[0]
1

Slices

list = [1, 2, 3, 4]

>>> list[0:1]
[1]
>>> list[0:3]
[1, 2, 3]
>>> list[1:5]
[2, 3, 4]

Inclusion

list = ['apple', 'pear', 'orange']

>>> 'pear' in list
True
>>> 'grape' in list
False

>>> if 'pear' in list
>>>   print 'there is a pear'

Remove

list = ['apple', 'pear', 'orange']

>>> del list[0]
['pear', 'orange']

Dictionnary

d = { 'r':0, 'p':{}, 'z':[] }

>>> d['r']
0
>>> d['p']
{}
>>> d.keys()
['p', 'r', 'z']
>>> del(d['z'])
>>> d.keys()
['p', 'r']

Boucles

For

fruit = ['apple', 'orange', 'grape'] new_fruit = []

>>> for item in fruit :
>>>   print item
>>>   new_fruit.append(item)

>>> print new_fruit
['apple', 'orange', 'grape']

people = {'name':'Bob', 'hometown': "Palo Alto", 'favorite_color': 'red'}

>>> for key in people :
>>>>  print people[key]

While

fruit = ['apple', 'orange', 'grape']

>>> i = 0
>>> while (i < len(fruit)) :
>>>   print fruit[i]
>>>   i = i + 1 # i++ est illégal
apple
orange
grape

Embedded

<ul>
%for value in list
  <li>{{value}}</li>
</ul>

Try catch

>>> try :
>>>   print 5 / 0
>>> except :
>>>   print "exception ", sys.exc_info()[0]

Functions

fruit = ['apple', 'orange', 'grape', 'kiwi', 'orange', 'apple']

>>> def analyze_list(l) :
>>>   counts = {}
>>>   for item in l :
>>>     if item in counts :
>>>       counts[item] = counts[item] + 1
>>>     else :
>>>       counts[item] = 1
>>>   return counts

>>> print analyze_list(fruit)
{'orange': 2, 'kiwi': 1, 'grape': 1, 'apple': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment