1-PythonIntro.ipynb 96.3 KB
Newer Older
Massih-Reza Amini's avatar
toto  
Massih-Reza Amini committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction to Python programming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Le notebook suivant sert à introduire le langage Python."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pseudocode"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Le Pseudocode vu en cours est une description de haut niveau des principales instructions utilisées dans un programme. Il est souvent comme un outil permettant aux programmeurs de mieux comprendre un problème sans rentrer dans les détails de prgorammation d'un langage particulier. Voici un exmple de pseudocode pour sommer les éléments d'une liste:\n",
    "\n",
    "`cnt <- 0\n",
    "for element in list:\n",
    "    cnt <- cnt + element`\n",
    "\n",
    "L'écritre d'un pseudocode pour des programmes complexes avant la phase de programmation permet en général d'éviter des erreurs de sense et de logique."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python est un langage interprété"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cela vaut dire que les instructions sont d'abord lues avant d'être executées une à une. Ainsi, il n'est pas ainsi de passer par une phase de compilation. Les langages interprétés sont plus adaptés à des langages dynamiques."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Python program files"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* Les programmes Python ont l'extension \"`.py`\":\n",
    "\n",
    "        myprogram.py\n",
    "\n",
    "* Les commentaires sont précédés du caractère `#` \n",
    "\n",
    "* Pour executer un programme python:\n",
    "\n",
    "        $ python myprogram.py\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "run_hello_world.py\r\n"
     ]
    }
   ],
   "source": [
    "ls scripts/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "print(\"Hello World. \\n Welcome to Python!\")\r\n"
     ]
    }
   ],
   "source": [
    "cat scripts/run_hello_world.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello World. \r\n",
      " Welcome to Python!\r\n"
     ]
    }
   ],
   "source": [
    "!python scripts/run_hello_world.py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "L'execution du programme précédent s'est fait via le notebook Ipython notebook (ou le notebook Jupyter executant le noyau python) comme un terminal dans ce cas il est nécessaire de précéder la ligne d'éxecution du caractère '!'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## IPython notebooks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Un notebook IPython est stocké en format [JSON](http://en.wikipedia.org/wiki/JSON). L'avantage est qu'on peut mélanger du texte (enrichi) avec du code Python. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Modules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "La plupart des fonctionnalité de Python est faite avec des *modules*. La librairie standard Python est une large collection de modules qui met à disposition des implémentations pour la lecture et l'écriture, des calculs standards, etc."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Références"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    " * Référence du langage Python : http://docs.python.org/2/reference/index.html\n",
    " * Librairie standard de Python: http://docs.python.org/2/library/\n",
    "\n",
    "Pour utiliser un  module en Python il doit d'abord être importé en l'invoquant avec l'argument `import`. Par exemple pour importer le module `math`, qui contient les fonctions standard en mathématiques on écrit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ceci contient tout le module et on peut l'invoquer en spécifiant les fonctions utilisées:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-1.0\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "x = math.cos(math.pi)\n",
    "\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Une autre façon est d'importer tous les symboles (fonctions et variables) dans un module sans être obligé d'uliliser le prefixe \"`math.`\" à chaque fois où une fonctions est invoquée:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0\n"
     ]
    }
   ],
   "source": [
    "from math import * #This is a bad practise \n",
    "\n",
    "x = cos(2 * pi)\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cependant dans le cas où plusieurs modules sont importés il est vivement conseillé de ne pas utiliser cette dernière afin d'éviter toute collision et confusion entre les fonctions invoquées.\n",
    "\n",
    "Une troisième alternative est de n'importer que quelques symboles bien sélectionnés d'un module en listant explicitement ceux qu'on souhaite invoquer :"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-0.4999999999999998\n"
     ]
    }
   ],
   "source": [
    "from math import cos, pi # Importing only the functions you need from a particular package is a much better practise. \n",
    "\n",
    "x = cos(2 * pi/3)\n",
    "\n",
    "print(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Le contenu d'un module et la documentation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Une fois un module importé; on peut utiliser la fonction `dir` pour connaître son contenu:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "print(dir(math))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Avec la fonction `help` on peut avoir la description de chacune des fonctions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on float object:\n",
      "\n",
      "class float(object)\n",
      " |  float(x) -> floating point number\n",
      " |  \n",
      " |  Convert a string or number to a floating point number, if possible.\n",
      " |  \n",
      " |  Methods defined here:\n",
      " |  \n",
      " |  __abs__(self, /)\n",
      " |      abs(self)\n",
      " |  \n",
      " |  __add__(self, value, /)\n",
      " |      Return self+value.\n",
      " |  \n",
      " |  __bool__(self, /)\n",
      " |      self != 0\n",
      " |  \n",
      " |  __divmod__(self, value, /)\n",
      " |      Return divmod(self, value).\n",
      " |  \n",
      " |  __eq__(self, value, /)\n",
      " |      Return self==value.\n",
      " |  \n",
      " |  __float__(self, /)\n",
      " |      float(self)\n",
      " |  \n",
      " |  __floordiv__(self, value, /)\n",
      " |      Return self//value.\n",
      " |  \n",
      " |  __format__(...)\n",
      " |      float.__format__(format_spec) -> string\n",
      " |      \n",
      " |      Formats the float according to format_spec.\n",
      " |  \n",
      " |  __ge__(self, value, /)\n",
      " |      Return self>=value.\n",
      " |  \n",
      " |  __getattribute__(self, name, /)\n",
      " |      Return getattr(self, name).\n",
      " |  \n",
      " |  __getformat__(...) from builtins.type\n",
      " |      float.__getformat__(typestr) -> string\n",
      " |      \n",
      " |      You probably don't want to use this function.  It exists mainly to be\n",
      " |      used in Python's test suite.\n",
      " |      \n",
      " |      typestr must be 'double' or 'float'.  This function returns whichever of\n",
      " |      'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the\n",
      " |      format of floating point numbers used by the C type named by typestr.\n",
      " |  \n",
      " |  __getnewargs__(...)\n",
      " |  \n",
      " |  __gt__(self, value, /)\n",
      " |      Return self>value.\n",
      " |  \n",
      " |  __hash__(self, /)\n",
      " |      Return hash(self).\n",
      " |  \n",
      " |  __int__(self, /)\n",
      " |      int(self)\n",
      " |  \n",
      " |  __le__(self, value, /)\n",
      " |      Return self<=value.\n",
      " |  \n",
      " |  __lt__(self, value, /)\n",
      " |      Return self<value.\n",
      " |  \n",
      " |  __mod__(self, value, /)\n",
      " |      Return self%value.\n",
      " |  \n",
      " |  __mul__(self, value, /)\n",
      " |      Return self*value.\n",
      " |  \n",
      " |  __ne__(self, value, /)\n",
      " |      Return self!=value.\n",
      " |  \n",
      " |  __neg__(self, /)\n",
      " |      -self\n",
      " |  \n",
      " |  __new__(*args, **kwargs) from builtins.type\n",
      " |      Create and return a new object.  See help(type) for accurate signature.\n",
      " |  \n",
      " |  __pos__(self, /)\n",
      " |      +self\n",
      " |  \n",
      " |  __pow__(self, value, mod=None, /)\n",
      " |      Return pow(self, value, mod).\n",
      " |  \n",
      " |  __radd__(self, value, /)\n",
      " |      Return value+self.\n",
      " |  \n",
      " |  __rdivmod__(self, value, /)\n",
      " |      Return divmod(value, self).\n",
      " |  \n",
      " |  __repr__(self, /)\n",
      " |      Return repr(self).\n",
      " |  \n",
      " |  __rfloordiv__(self, value, /)\n",
      " |      Return value//self.\n",
      " |  \n",
      " |  __rmod__(self, value, /)\n",
      " |      Return value%self.\n",
      " |  \n",
      " |  __rmul__(self, value, /)\n",
      " |      Return value*self.\n",
      " |  \n",
      " |  __round__(...)\n",
      " |      Return the Integral closest to x, rounding half toward even.\n",
      " |      When an argument is passed, work like built-in round(x, ndigits).\n",
      " |  \n",
      " |  __rpow__(self, value, mod=None, /)\n",
      " |      Return pow(value, self, mod).\n",
      " |  \n",
      " |  __rsub__(self, value, /)\n",
      " |      Return value-self.\n",
      " |  \n",
      " |  __rtruediv__(self, value, /)\n",
      " |      Return value/self.\n",
      " |  \n",
      " |  __setformat__(...) from builtins.type\n",
      " |      float.__setformat__(typestr, fmt) -> None\n",
      " |      \n",
      " |      You probably don't want to use this function.  It exists mainly to be\n",
      " |      used in Python's test suite.\n",
      " |      \n",
      " |      typestr must be 'double' or 'float'.  fmt must be one of 'unknown',\n",
      " |      'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be\n",
      " |      one of the latter two if it appears to match the underlying C reality.\n",
      " |      \n",
      " |      Override the automatic determination of C-level floating point type.\n",
      " |      This affects how floats are converted to and from binary strings.\n",
      " |  \n",
      " |  __str__(self, /)\n",
      " |      Return str(self).\n",
      " |  \n",
      " |  __sub__(self, value, /)\n",
      " |      Return self-value.\n",
      " |  \n",
      " |  __truediv__(self, value, /)\n",
      " |      Return self/value.\n",
      " |  \n",
      " |  __trunc__(...)\n",
      " |      Return the Integral closest to x between 0 and x.\n",
      " |  \n",
      " |  as_integer_ratio(...)\n",
      " |      float.as_integer_ratio() -> (int, int)\n",
      " |      \n",
      " |      Return a pair of integers, whose ratio is exactly equal to the original\n",
      " |      float and with a positive denominator.\n",
      " |      Raise OverflowError on infinities and a ValueError on NaNs.\n",
      " |      \n",
      " |      >>> (10.0).as_integer_ratio()\n",
      " |      (10, 1)\n",
      " |      >>> (0.0).as_integer_ratio()\n",
      " |      (0, 1)\n",
      " |      >>> (-.25).as_integer_ratio()\n",
      " |      (-1, 4)\n",
      " |  \n",
      " |  conjugate(...)\n",
      " |      Return self, the complex conjugate of any float.\n",
      " |  \n",
      " |  fromhex(...) from builtins.type\n",
      " |      float.fromhex(string) -> float\n",
      " |      \n",
      " |      Create a floating-point number from a hexadecimal string.\n",
      " |      >>> float.fromhex('0x1.ffffp10')\n",
      " |      2047.984375\n",
      " |      >>> float.fromhex('-0x1p-1074')\n",
      " |      -5e-324\n",
      " |  \n",
      " |  hex(...)\n",
      " |      float.hex() -> string\n",
      " |      \n",
      " |      Return a hexadecimal representation of a floating-point number.\n",
      " |      >>> (-0.1).hex()\n",
      " |      '-0x1.999999999999ap-4'\n",
      " |      >>> 3.14159.hex()\n",
      " |      '0x1.921f9f01b866ep+1'\n",
      " |  \n",
      " |  is_integer(...)\n",
      " |      Return True if the float is an integer.\n",
      " |  \n",
      " |  ----------------------------------------------------------------------\n",
      " |  Data descriptors defined here:\n",
      " |  \n",
      " |  imag\n",
      " |      the imaginary part of a complex number\n",
      " |  \n",
      " |  real\n",
      " |      the real part of a complex number\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(math.pi)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Une uatre façon est d'utiliser le symbole \"?\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "?math.log"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.718281828459045"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import exp, log\n",
    "exp(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.3219280948873626"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import log\n",
    "log(10, 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "return arrays must be of ArrayType",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-13-f03f32b5ac16>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mlog\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mlog\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m10\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# This will create an error. This is why importing function from several packages is not a good practise.\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m: return arrays must be of ArrayType"
     ]
    }
   ],
   "source": [
    "from numpy import log\n",
    "log(10, 2) # This will create an error. This is why importing function from several packages is not a good practise.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "?log"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "Les modules généraux les plus utilisés en Python sont `os`, `sys`, `math`, `shutil`, `re`, `subprocess`, `multiprocessing`, `threading`. \n",
    "\n",
    "Pour la science des données ces modules sont les plus populaires: `numpy`, `scipy`, `scikit-learn` et `pandas`.\n",
    "\n",
    "Une liste complète des modules de  Python 2  Python 3 est disponbile à http://docs.python.org/2/library/ and http://docs.python.org/3/library/."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Variables et types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Symbol names "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Les noms des variable en Python contiennent des caractères alphanumériques `a-z`, `A-Z`, `0-9` et quelques caractères spéciaux comme `_`. Les noms des variables normaux doivent commencer avec une lettre. \n",
    "\n",
    "Par convention, les noms des variables commencent avec une lettre en minuscule, et les noms des classes en majuscules. \n",
    "\n",
    "Les nomes ne peuvent pas être un des mots clés utilisés en Python:\n",
    "\n",
    "    and, as, assert, break, class, continue, def, del, elif, else, except, \n",
    "    exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n",
    "    pass, print, raise, return, try, while, with, yield\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Affectation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Le signe de l'affectation en Python est `=`. Python est un langage de typage dynamique; où il n'est pas nécessaire de spécifier les types des variables au début des programmes.\n",
    "\n",
    "La création d'une variable se fait via son affectation. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "# variable assignments\n",
    "x = 1.0\n",
    "my_variable = 12.2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ainsi le type d'une variable est déduit de sa valeur"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "float"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Si une nouvelle valeur est affectée à une variable, son type change."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Si on essaie d'utiliser une variable qui n'est pas créée, l'erreur `NameError` est émise"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'y' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-30-d9183e048de3>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'y' is not defined"
     ]
    }
   ],
   "source": [
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Types fondamentax"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "int"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# integers\n",
    "x = 1\n",
    "type(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "float"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# float\n",
    "x = 1.0\n",
    "type(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "bool"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# boolean\n",
    "b1 = True\n",
    "b2 = False\n",
    "\n",
    "type(b1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "complex"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# complex numbers: note the use of `j` to specify the imaginary part\n",
    "x = 1.0 - 1.0j\n",
    "type(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1-1j)\n"
     ]
    }
   ],
   "source": [
    "print(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.0 -1.0\n"
     ]
    }
   ],
   "source": [
    "print(x.real, x.imag)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Module types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Ce module contient le nom et les définitions qui peuvent être utilisées pour connaître si les variables sont d'un certain type."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['AsyncGeneratorType', 'BuiltinFunctionType', 'BuiltinMethodType', 'CodeType', 'CoroutineType', 'DynamicClassAttribute', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'LambdaType', 'MappingProxyType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'SimpleNamespace', 'TracebackType', '_GeneratorWrapper', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_ag', '_calculate_meta', '_collections_abc', '_functools', 'coroutine', 'new_class', 'prepare_class']\n"
     ]
    }
   ],
   "source": [
    "import types\n",
    "\n",
    "# print all types defined in the `types` module\n",
    "print(dir(types))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = 1.0\n",
    "\n",
    "# check if the variable x is a float\n",
    "type(x) is float"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# check if the variable x is an int\n",
    "type(x) is int"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On peut aussi utiliser la méthode `isinstance` pour tester les types des variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
For faster browsing, not all history is shown. View entire blame