Python. Mémo

Variable, types

entier

In [1]:
a = 5
In [2]:
type(a)
Out[2]:
int

flottant

In [3]:
b = 110.2
In [4]:
type(b)
Out[4]:
float

chaîne de caractères

In [5]:
c = 'bonjour'    #chaine de caracteres (string)
In [6]:
type(c)
Out[6]:
str

liste

In [7]:
d = [5,4,8,9]    # liste (tableau)
type(d)
Out[7]:
list

booléen

In [8]:
e = ( 5 == 4+1 )    # booleen
print(e)
True
In [9]:
type(e)
Out[9]:
bool
In [10]:
print(not e)    # negation
False
In [11]:
print( (4 <= 5) or (4 > 7))    # ou
True
In [12]:
print( (4 <= 5) and (4 > 7))    # et
False

Entrée

int convertit la saisie en un entier (sinon la saisie est une chaine).

In [13]:
age = int(input('Saisir votre âge : '))
Saisir votre âge : 25

Si ... alors ... sinon

In [14]:
if age < 18:
    print('Tu es mineur')
else:
    print('Vous êtes majeur')
Vous êtes majeur

Tant que ... faire ...

In [15]:
k = 0
while k < 5:
    print(k)
    k = k+1
print('fin')
    
0
1
2
3
4
fin

Pour i de ... à ...

In [16]:
for i in range(5):
    print(i)
0
1
2
3
4

Listes

In [17]:
L1 = []        # liste vide
L2 = [0]*4
L3 = [4, 500, 8, 10]
L4 = [[1,2,300,4] , [5,6,7,8]]
print(L1)
print(L2)
print(L3[1])
print(len(L3))
print(len(L4))
print(L4[0][2])
[]
[0, 0, 0, 0]
500
4
2
300

Fonctions

In [18]:
def f(x):
    return x+10

f(7)
Out[18]:
17
In [19]:
def g(a,b):
    if a>b :
        return a
    else:
        return b
    
g(4,7)
        
Out[19]:
7

Calculs

In [20]:
4 + 3*10
Out[20]:
34
In [21]:
2**10     # puissance
Out[21]:
1024
In [22]:
5/3    # division
Out[22]:
1.6666666666666667
In [23]:
5//3    #division entiere (quotient de la division euclienne de 5 par 3)
Out[23]:
1
In [24]:
5 % 3    #reste de la division euclidienne de 5 par 3
Out[24]:
2
In [25]:
from math import sqrt     #racine carree
sqrt(2)
Out[25]:
1.4142135623730951
In [26]:
from math import floor     #partie entière
floor(2.35)
Out[26]:
2