Bienvenue ! Ceci est un notebook IPython.
1 + 3
4
IPython (Jupyter) est un système de présentation de documents scientifiques interactifs.
%%html
<p>Cette cellule <strong>contient du HTML</strong> !</p>
<p>Remarquez la <em>clef magique</em> <code>%%html</code>.</p>
Cette cellule contient du HTML !
Remarquez la clef magique %%html
.
Avec IPython sont aussi installés
...d'où Ju-Pyt-eR !
Le notebook est plus facile à utiliser si vous connaissez les raccourcis clavier. Echap
, puis h
pour les voir.
a = 1
a
1
type(a)
int
a = "toto"
a
'toto'
type(a)
str
On ne combine pas deux types différents
a + 1
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-7-a1bd27f4633f> in <module>() ----> 1 a + 1 TypeError: cannot concatenate 'str' and 'int' objects
Nous n'allons pas entrer dans les détails des langages orientés aux objets. En pratique,
a.upper()
'TOTO'
Dans la majorité des cas, les méthodes ne modifient pas l'objet, mais en créent un nouveau
b = a.upper()
b
'TOTO'
a
'toto'
Vous n'avez pas droit de laisser de l'espace blanc à gauche du code sans raison
a = 1
b = 2
File "<ipython-input-11-12c30cde097b>", line 2 b = 2 ^ IndentationError: unexpected indent
Vous n'avez pas droit de couper une ligne
a =
2
File "<ipython-input-12-b737fa3c9036>", line 1 a = ^ SyntaxError: invalid syntax
a = "toto"
a == 'toto'
True
Il n'y a pas d'équivalent de char
a[1]
'o'
type(a[1])
str
Chaînes sur plusieurs lignes
a = "tot
o"
File "<ipython-input-17-5c6c4e4b596f>", line 1 a = "tot ^ SyntaxError: EOL while scanning string literal
a = """
Mignonne, allons voir si la rose
Qui ce matin avoit desclose
Sa robe de pourpre au Soleil,
"""
a
'\nMignonne, allons voir si la rose\nQui ce matin avoit desclose\nSa robe de pourpre au Soleil,\n'
Instruction print
pour afficher le texte
print a
Mignonne, allons voir si la rose Qui ce matin avoit desclose Sa robe de pourpre au Soleil,
Remplacement de valeurs (à la printf
)
"La reponse est %d" % 42
'La reponse est 42'
"La %s est %d" % ("question", 24)
'La question est 24'
a = 1
a == 1.0
True
Les nombres ont précision arbitraire (pas d'overflow comme en C)
Le L
à la fin indique un nombre long
a = 1000000
a * a * a * a * a * a
1000000000000000000000000000000000000L
Opérateur puissance
a**6
1000000000000000000000000000000000000L
True == (not False)
True
True and False
False
True or False
True
a = ["a", "b", "c"]
a[1]
'b'
len(a)
3
a[2] = "d"
a
['a', 'b', 'd']
a[3]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-34-94e7916e7615> in <module>() ----> 1 a[3] IndexError: list index out of range
a[3] = "e"
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-35-58c7bf901c62> in <module>() ----> 1 a[3] = "e" IndexError: list assignment index out of range
a.append("e")
a
['a', 'b', 'd', 'e']
" ~~=> ".join(a)
'a ~~=> b ~~=> d ~~=> e'
a = { "couleur": "rouge", "forme": "rond"}
a
{'couleur': 'rouge', 'forme': 'rond'}
len(a)
2
a["couleur"]
'rouge'
a["taille"] = "grand"
a
{'couleur': 'rouge', 'forme': 'rond', 'taille': 'grand'}
if 1 + 1 == 2 and 1 - 1 > 0:
a = 10
print "faux"
elif 3 + 4 == 7:
a = 3
print "yes"
else:
a = 4
print "no"
a
yes
3
while
¶i = 0
while i < 10:
print i
i += 1
0 1 2 3 4 5 6 7 8 9
Bloc for
(très différent du C)
a = ["a", "b", "c"]
for x in a:
print x
a b c
fonction range
pour obtenir une liste de nombres
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(10):
print i
0 1 2 3 4 5 6 7 8 9
def ma_fonction(x, y):
c = 2*x
return c + y
ma_fonction(2, 3)
7
Arguments par défaut
def fct(x, y=3, z=10):
return x + y + z
fct(2), fct(2, 4), fct(2, 4, 1), fct(2, z=3)
(15, 16, 7, 8)
import numpy
from pylab import imshow, show
from timeit import default_timer as timer
Et maintenant commence la fête !
%pylab inline
def mandel(x, y, max_iters):
"""
Given the real and imaginary parts of a complex number,
determine if it is a candidate for membership in the Mandelbrot
set given a fixed number of iterations.
"""
c = complex(x, y)
z = 0.0j
for i in range(max_iters):
z = z*z + c
if (z.real*z.real + z.imag*z.imag) >= 4:
return i
return max_iters
def create_fractal(min_x, max_x, min_y, max_y, image, iters):
height = image.shape[0]
width = image.shape[1]
pixel_size_x = (max_x - min_x) / width
pixel_size_y = (max_y - min_y) / height
for x in range(width):
real = min_x + x * pixel_size_x
for y in range(height):
imag = min_y + y * pixel_size_y
color = mandel(real, imag, iters)
image[y, x] = color
image = numpy.zeros((1024, 1536), dtype = numpy.uint8)
start = timer()
create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20)
dt = timer() - start
print "Mandelbrot created in %f s" % dt
imshow(image)
show()
Populating the interactive namespace from numpy and matplotlib Mandelbrot created in 8.127823 s