0% ont trouvé ce document utile (0 vote)
35 vues9 pages

Presentationpython Ipynb

Ce document présente les principaux types de données et concepts de programmation en Python. Il introduit les nombres, chaînes de caractères, listes, tuples, dictionnaires, boucles et fonctions. Différentes opérations et méthodes sur ces types sont également montrées.

Transféré par

Pas DEN
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd
0% ont trouvé ce document utile (0 vote)
35 vues9 pages

Presentationpython Ipynb

Ce document présente les principaux types de données et concepts de programmation en Python. Il introduit les nombres, chaînes de caractères, listes, tuples, dictionnaires, boucles et fonctions. Différentes opérations et méthodes sur ces types sont également montrées.

Transféré par

Pas DEN
Copyright
© © All Rights Reserved
Nous prenons très au sérieux les droits relatifs au contenu. Si vous pensez qu’il s’agit de votre contenu, signalez une atteinte au droit d’auteur ici.
Formats disponibles
Téléchargez aux formats PDF, TXT ou lisez en ligne sur Scribd

Notebook [Link]

Des types de base

Nombres et opérations
In [2]: f = 34.78e-12 # flottant
c = 4+0.5j # complexe avec le suffixe j
i = -89 # entier notation décimale
ix = 0x100FF # entier notation hexadécimale
io = 0o7734 # entier notation octale
ib = 0b0101 # entier notation binaire
grand = 563272876763298724546328656232098919898326525729851563297862672
97632567816572898675
print("Un flottant:", f, "et un complexe:", c)
print("Des entiers:", i, ix, io, ib, sep=' ')
print(grand + 1)
print(4 * (c + 3.4j) ** 2)
print(1/2, 1//2, 1.0//2, 15%3, sep=' ')

Un flottant: 3.478e-11 et un complexe: (4+0.5j)


Des entiers: -89 65791 4060 5
56327287676329872454632865623209891989832652572985156329786267297632567
816572898676
(3.1600000000000037+124.8j)
0.5 0 0.0 0

Booléens
In [3]: vrai = True
faux = False
print("Valeurs booléennes:", vrai, faux)
expr = i < 0 and ix >-60000
print("expr:", expr)

Valeurs booléennes: True False


expr: True

Texte (str)
In [4]: s = """Caractère par son nom Unicode: \N{GREEK SMALL LETTER PI}
Caractère par son code Unicode: \u03A9"""
print(s)

Caractère par son nom Unicode: π


Caractère par son code Unicode: Ω

1 sur 9 03/02/2015 16:56


Notebook In [5]: s = "Du texte dans une PETITE chaine."
[Link]
print(s, " — longueur", len(s), "caractères")
print("upper:", [Link]())
print("lower:", [Link]())
print("title:", [Link]())
print("split:", [Link]())
print("find:", [Link]('une'), [Link]('absent'))

Du texte dans une PETITE chaine. — longueur 32 caractères


upper: DU TEXTE DANS UNE PETITE CHAINE.
lower: du texte dans une petite chaine.
title: Du Texte Dans Une Petite Chaine.
split: ['Du', 'texte', 'dans', 'une', 'PETITE', 'chaine.']
find: 14 -1

Fortement typé
In [6]: #print(34 + "12")
#print("34" + 12)

Des types Conteneurs


In [7]: lst = [ 1, 6, 9, -12, 78, 6 ] # liste (items indexés)
t = ( 7, 9, 14, 8 ) # tuple (items indexés, non mod
ifiable)
print(lst, t)

[1, 6, 9, -12, 78, 6] (7, 9, 14, 8)

In [8]: lst[2]

Out[8]: 9

In [9]: lst[2:4]

Out[9]: [9, -12]

In [10]: lst[::2]

Out[10]: [1, 9, 78]

In [11]: lst[::-1]

Out[11]: [6, 78, -12, 9, 6, 1]

In [12]: 9 in lst

Out[12]: True

In [13]: dico = {"un":1, "deux":2, "pi":3.14159, 12:"douze"}


print(dico)

2 sur 9 {'deux': 2, 'un': 1, 'pi': 3.14159, 12: 'douze'} 03/02/2015 16:56


Notebook In [14]: dico["pi"] [Link]

Out[14]: 3.14159

In [15]: 12 in dico

Out[15]: True

Contrôle de flux
In [16]: x = 2
while x < 12:
if x%3:
x += 1
continue
print(x, end=" ")
x += 1

3 6 9

In [19]: for val in lst:


print("Valeur:", val)
for i in range(len(lst)):
print(lst[i])
for i,val in enumerate(lst):
print(i,val)

Valeur: 1
Valeur: 6
Valeur: 9
Valeur: -12
Valeur: 78
Valeur: 6
1
6
9
-12
78
6
0 1
1 6
2 9
3 -12
4 78
5 6

In [20]: v = input("Combien?") # retourne str


v = int(v)
for i in range(v):
print(i, end=" ")

Combien?8
0 1 2 3 4 5 6 7

3 sur 9 03/02/2015 16:56


Notebook In [21]: for clef in dico: [Link]
print(clef, "===>", dico[clef])

deux ===> 2
un ===> 1
pi ===> 3.14159
12 ===> douze

Switch
In [22]: d = {"double": lambda x: x*2,
"carre": lambda x: x**2,
"cube": lambda x: x**3,
"triple": lambda x: x*3
}
print(d["cube"](4))
print(d["triple"](4))

64
12

Expressions pratiques
In [23]: carres = [ x ** 2 for x in range(2,100) if x%6==0] # Construction d'une
liste via boucle de calcul
print(carres)

[36, 144, 324, 576, 900, 1296, 1764, 2304, 2916, 3600, 4356, 5184, 6084
, 7056, 8100, 9216]

In [24]: sum((x ** 6 for x in range(1,100000))) # Valeurs générées au fur


et à mesure

Out[24]: 14285214290714285714119047619050000

Fonctions
In [27]: def moysous(sequence, seuil=100):
som, nbval = 0, 0
for val in sequence:
if val<seuil:
som += val
nbval += 1
res = som / nbval
return res
print(moysous([1,2,14,3,4,5], 10))
print(moysous([1,2,140,3,4,5]))
#print(moysous([], 10)) # bug division par zéro

3.0
3.0
4 sur 9 03/02/2015 16:56
Notebook [Link]

Fichiers et blocs gardés


In [28]: f = open("[Link]", "r", encoding="utf-8")
line = [Link]()
while line:
if "require" in line:
print(repr(line))
line = [Link]()
[Link]()

' * first argument of require is a **list** that can contains seve


ral modules if needed.\n'
" // require(['custom/noscroll']);\n"
" // require(['custom/clean_start'])\n"
" // require(['custom/toggle_all_line_number'])\n"
" // require(['custom/gist_it']);\n"
" require(['custom/slidemode/main'],function(slidemode){\n"

In [29]: with open("[Link]", "r", encoding="utf-8") as f:


for line in f:
if "require" in line:
print(repr(line))

' * first argument of require is a **list** that can contains seve


ral modules if needed.\n'
" // require(['custom/noscroll']);\n"
" // require(['custom/clean_start'])\n"
" // require(['custom/toggle_all_line_number'])\n"
" // require(['custom/gist_it']);\n"
" require(['custom/slidemode/main'],function(slidemode){\n"

Définition de classe
In [30]: class AccumuleLongueur:
def __init__(self, val=0):
self._v = val
def __add__(self, s):
return AccumuleLongueur(self._v + len(s))
def __str__(self):
return "Longueur {}".format(self._v)
al = AccumuleLongueur()
print(al)
al = al + "Un début"
print(al)
al += "on ajoute une chaine."
print(al)
bl = al + "Et encore une autre mais que dans bl"
print(al, bl)

Longueur 0
Longueur 8
Longueur 29
Longueur 29 Longueur 65
5 sur 9 03/02/2015 16:56
Notebook [Link]

Duck Typing
In [31]: import sys
class FicUpper:
def write(self, s):
[Link]([Link]())
fic = FicUpper()
print("On affiche une chaîne", file=fic)
print("Et une autre.", file=fic)

ON AFFICHE UNE CHAÎNE


ET UNE AUTRE.

In [33]: import sys


class FicModifier:
def __init__(self, fct):
self._f = fct
def write(self, s):
[Link](self._f(s))
fic = FicModifier([Link])
print("On affiche une chaîne", file=fic)
print("Et une autre.", file=fic)
fic = FicModifier([Link])
print("On affiche une chaîne", file=fic)
print("Et une autre.", file=fic)

On Affiche Une Chaîne


Et Une Autre.
on affiche une chaîne
et une autre.

Outil port série


In [34]: import serial # Module pyserial
print(dir(serial)) # …Serial …FileLike
# port = [Link]('/dev/ttyS0', baudrate=9600) # il me faudrait
un device…

['ASYNC_SPD_CUST', 'ASYNC_SPD_MASK', 'CR', 'EIGHTBITS', 'FCNTL', 'FIVEB


ITS', 'FileLike', 'LF', 'PARITY_EVEN', 'PARITY_MARK', 'PARITY_NAMES', '
PARITY_NONE', 'PARITY_ODD', 'PARITY_SPACE', 'PosixPollSerial', 'PosixSe
rial', 'SEVENBITS', 'SIXBITS', 'STOPBITS_ONE', 'STOPBITS_ONE_POINT_FIVE
', 'STOPBITS_TWO', 'Serial', 'SerialBase', 'SerialException', 'SerialTi
meoutException', 'TERMIOS', 'TIOCCBRK', 'TIOCINQ', 'TIOCMBIC', 'TIOCMBI
S', 'TIOCMGET', 'TIOCMSET', 'TIOCM_CAR', 'TIOCM_CD', 'TIOCM_CTS', 'TIOC
M_DSR', 'TIOCM_DTR', 'TIOCM_DTR_str', 'TIOCM_RI', 'TIOCM_RNG', 'TIOCM_R
TS', 'TIOCM_RTS_str', 'TIOCM_zero_str', 'TIOCSBRK', 'VERSION', 'XOFF',
'XON', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__
', '__name__', '__package__', '__path__', '__spec__', 'baudrate_constan
ts', 'device', 'errno', 'fcntl', 'io', 'os', 'plat', 'portNotOpenError'
, 'protocol_handler_packages', 'select', 'serial_for_url', 'serialposix
', 'serialutil', 'set_special_baudrate', 'struct', 'sys', 'termios', 't
ime', 'to_bytes', 'writeTimeoutError']
6 sur 9 03/02/2015 16:56
Notebook [Link]

Outils manipulations octets


In [35]: import array
a = [Link]('H', range(10, 1000))
print("Taille d'un élément:", [Link])
a2 = a[:10]
print([Link]())
[Link]()
print([Link]())

Taille d'un élément: 2


b'\n\x00\x0b\x00\x0c\x00\r\x00\x0e\x00\x0f\x00\x10\x00\x11\x00\x12\x00\
x13\x00'
b'\x00\n\x00\x0b\x00\x0c\x00\r\x00\x0e\x00\x0f\x00\x10\x00\x11\x00\x12\
x00\x13'

In [36]: import struct


fmt = "!bbxxL" # !=network=big endian, b=signed char, x=pad byte, L=uns
igned long
print("Taille:", [Link](fmt))
s = [Link](fmt, 2, 9, 14849)
print("Pack => ", s, "Octets:", list(s))
v = [Link](fmt, s)
print("Unpack =>", v)

Taille: 8
Pack => b'\x02\t\x00\x00\x00\x00:\x01' Octets: [2, 9, 0, 0, 0, 0, 58,
1]
Unpack => (2, 9, 14849)

In [37]: import wave


f = [Link]("[Link]", "rb")
print([Link]())
for i in range(10):
print(list([Link](1)), end=" ")
[Link]()

_wave_params(nchannels=1, sampwidth=2, framerate=8000, nframes=110491,


comptype='NONE', compname='not compressed')
[7, 0] [251, 255] [4, 0] [250, 255] [1, 0] [251, 255] [4, 0
] [251, 255] [2, 0] [251, 255]

Appel fonction C
// malib.c #include double mafct(double a, int b); double mafct(double a, int b) { return a * b; } // $ cc -shared
-Wl,-soname,malib -o [Link] -fPIC malib.c

7 sur 9 03/02/2015 16:56


Notebook In [38]: import ctypes [Link]
import os, [Link]
lib = [Link]([Link]([Link](), "[Link]"))
print(lib)
f = [Link]
print(f)
[Link] = [ctypes.c_double, ctypes.c_int]
[Link] = ctypes.c_double
res = f(3.8, 4)
print("Résultat:", res)

<CDLL '/home/laurent/ownCloud/python-reseau-electroniciens/[Link]', h
andle 15e87b0 at 7fb868654be0>
<_FuncPtr object at 0x7fb86868e4f8>
Résultat: 15.2

Outils calcul / visu


In [39]: import numpy as np
%matplotlib inline
import [Link] as plt
from [Link] import jn # Bessel function of the first kind
of real order v
x = [Link](0, 4 * [Link])
for i in range(6):
[Link](x, jn(i, x))

In [40]: from [Link] import widgets


from [Link] import interact

In [41]: def f(a):


x = [Link](-1, a, 200)
y = [Link]([Link] * x) / ([Link] * x)
[Link]('Sinus Cardinal')
[Link](True)
[Link](x,y)

8 sur 9 03/02/2015 16:56


Notebook In [42]: interact(f, a=(0,20)) [Link]

In [44]: import dis


def f(x):
res = x * 2
return res
[Link](f)

3 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (2)
6 BINARY_MULTIPLY
7 STORE_FAST 1 (res)

4 10 LOAD_FAST 1 (res)
13 RETURN_VALUE

In [45]: !ls

[Link] [Link] [Link] [Link]


[Link] __pycache__
Annonce_Python.pdf [Link] malib.c PresentationImpr
[Link] [Link] [Link]

In [47]:

9 sur 9 03/02/2015 16:56

Vous aimerez peut-être aussi