├── XKCD.png ├── PhD-Comics.png ├── README.md └── introduction.md /XKCD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rougier/Scipy-Bordeaux-2018/HEAD/XKCD.png -------------------------------------------------------------------------------- /PhD-Comics.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rougier/Scipy-Bordeaux-2018/HEAD/PhD-Comics.png -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Scientific Python course 2 | 3 | Lecture notes from the course taught at the [University of Bordeaux] in the 4 | academic year 2018 for PhD students. Each student needs to come with a 5 | notebook computer running either Linux, OSX or Windows. 6 | 7 | ![](XKCD.png) Adapted from https://xkcd.com/353/ 8 | 9 | The scientific Python ecosystem is made of several modules that constitute 10 | together the scientific stack. There are hundreds of [Python scientific 11 | packages] and most of them are built on top of numpy, scipy, matplotib, pandas, 12 | cython and/or sympy. We won't cover everything in this short course, but you 13 | should get enough information to decide if your research can benefit from 14 | Python. And I bet it will likely do. 15 | 16 | This course is based on the following teaching material: 17 | 18 | * [Software Carpentry] ([CC BY 4.0]) 19 | * [Matplotlib tutorial] ([CC BY 4.0]) 20 | * [Scipy Lecture Notes] ([CC BY 4.0]) 21 | * [From Python to Numpy] ([CC BY-NC-SA 4.0]) 22 | 23 | 24 | 25 | ## 1. Beginner course (day 1 & 2) 26 | 27 | ### 1.1 - Introduction (day 1) 28 | 29 | This [gentle introduction to Python](introduction.md) explains how to install 30 | Python and introduces some very simple concepts related to numerical 31 | expressions and other data types. 32 | 33 | **See also**: 34 | 35 | * [The Python Tutorial](https://docs.python.org/3/tutorial/) 36 | 37 | 38 | ### 1.2 - Programming with Python (day 1) 39 | 40 | This [lecture](http://www.scipy-lectures.org/intro/language/python_language.html) 41 | does not attempt to be comprehensive and cover every single feature, or even 42 | every commonly used feature. Instead, it introduces many of Python's most 43 | noteworthy features, and will give you a good idea of the language’s flavor and 44 | style. 45 | 46 | **See also**: 47 | 48 | * [Dive into Python](http://www.diveintopython3.net) 49 | 50 | ### 1.3 - Computation I (day 2) 51 | 52 | The primary goal of this 53 | [lesson](http://www.scipy-lectures.org/intro/numpy/index.html) is to introduce 54 | the numpy (numerical python) module which is de facto the standard module for 55 | numerical computing with Python. It is essential for you to become familiar 56 | with this module since it will be used everywhere in the next lessons. 57 | 58 | **See also**: 59 | 60 | * [Numpy tutorial](https://github.com/rougier/numpy-tutorial) 61 | * [100 Numpy exercises](https://github.com/rougier/numpy-100) 62 | * [Numpy MedKit](http://mentat.za.net/numpy/numpy_advanced_slides/) 63 | 64 | 65 | ### 1.4 - Visualization (day 2) 66 | 67 | This [tutorial](https://github.com/rougier/matplotlib-tutorial) gives an 68 | overview of Matplotlib, the core tool for 2D & 2.5D plotting that produces 69 | publication quality figures as well as interactive environments across 70 | platforms. 71 | 72 | **See also**: 73 | 74 | * [Visualization Crash Course](https://github.com/rougier/ASPP-2017) 75 | * [10 Simple rules for better figures](http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003833) 76 | * [Pyplot tutorial](http://matplotlib.org/users/pyplot_tutorial.html) 77 | 78 | 79 | ---- 80 | 81 | 82 | ## 2. Advanced course (day 3 & 4) 83 | 84 | ### 2.1 - Scientific computation II (day 3) 85 | 86 | This [lesson](http://www.scipy-lectures.org/intro/scipy.html) introduces the 87 | scipy package that contains various toolboxes dedicated to common issues in 88 | scientific computing. Its different submodules correspond to different 89 | applications, such as interpolation, integration, optimization, image 90 | processing, statistics, special functions, etc. 91 | 92 | **See also**: 93 | 94 | * [Scipy Tutorial](http://docs.scipy.org/doc/scipy/reference/tutorial/) 95 | * [Numerical Analysis: Python vs Matlab](http://hyperpolyglot.org/numerical-analysis) 96 | 97 | 98 | ### 2.2 - Version control (day 3) 99 | 100 | This lesson introduces [version control using 101 | git](https://swcarpentry.github.io/git-novice/). Version control is the lab 102 | notebook of the digital world: it's what professionals use to keep track of 103 | what they’ve done and to collaborate with other people. And it isn't just for 104 | software: books, papers, small data sets, and anything that changes over time 105 | or needs to be shared can and should be stored in a version control system. 106 | 107 | **See also**: 108 | 109 | * [Git Book](https://git-scm.com/book/en/v2) 110 | * [Git cheat sheet](https://www.git-tower.com/blog/git-cheat-sheet/) 111 | * [Oh shit, git!](http://ohshitgit.com) 112 | * [Github Education Pack](https://education.github.com/pack) 113 | 114 | ### 2.3 - C/Python integration (day 4) 115 | 116 | This 117 | [chapter](http://www.scipy-lectures.org/advanced/interfacing_with_c/interfacing_with_c.html) 118 | covers the many different routes for making your native code (primarily C/C++) 119 | available from Python, a process commonly referred to wrapping. The goal of 120 | this chapter is to give you a flavour of what technologies exist and what their 121 | respective merits and shortcomings are, so that you can select the appropriate 122 | one for your specific needs. 123 | 124 | 125 | ### 2.4 - Vectorization (day 4) 126 | 127 | [NumPy is all about 128 | vectorization](http://www.labri.fr/perso/nrougier/from-python-to-numpy/). If 129 | you are familiar with Python, this is the main difficulty you'll face because 130 | you'll need to change your way of thinking and your new friends (among others) 131 | are named "vectors", "arrays", "views" or "ufuncs". 132 | 133 | ---- 134 | 135 | 136 | ![](PhD-Comics.png) 137 | 138 | 139 | 140 | [Python]: http://www.python.org 141 | [Numpy]: http://www.numpy.org 142 | [Scipy]: http://www.scipy.org 143 | [Pandas]: http://pandas.pydata.org 144 | [Matplotlib]: http://matplotlib.org 145 | [IPython]: http://ipython.org 146 | [Jupyter]: http://jupyter.org 147 | [Git]: https://git-scm.com 148 | [OpenGL]: https://www.opengl.org 149 | [Glumpy]: https://glumpy.github.io 150 | [Bokeh]: https://bokeh.org 151 | [Cython]: http://cython.org 152 | [Software Carpentry]: http://software-carpentry.org 153 | [Scipy Lecture Notes]: http://www.scipy-lectures.org 154 | [Matplotlib tutorial]: 155 | http://www.labri.fr/perso/nrougier/teaching/matplotlib/matplotlib.html 156 | [From Python to Numpy]: http://www.labri.fr/perso/nrougier/from-python-to-numpy/ 157 | [University of Bordeaux]: http://www.u-bordeaux.com 158 | [Python scientific packages]: (https://pypi.python.org/pypi?:action=browse&c=385) 159 | [CC BY 4.0]: https://creativecommons.org/licenses/by/4.0/ 160 | [CC BY-NC-SA 4.0]: https://creativecommons.org/licenses/by-nc-sa/4.0/ 161 | 162 | -------------------------------------------------------------------------------- /introduction.md: -------------------------------------------------------------------------------- 1 | # A Gentle introduction to Python 2 | **Nicolas P. Rougier** - [Nicolas.Rougier@inria.fr](mailto:Nicolas.Rougier@inria.fr) 3 | Lecture notes from the [EDMI] course taught at the [University of Bordeaux] for the 4 | academic year 2018. 5 | This work is licensed under [Creative Commons Attribution 4.0 International 6 | License](http://creativecommons.org/licenses/by/4.0/). 7 | 8 | 9 | Objectives 10 | ------------------------------------------------------------------------------- 11 | 12 | The primary goal of this lesson is twofold: 13 | 14 | * To ensure you have a clean Python installation 15 | * To discover Python basic syntax through the interpreter 16 | 17 | **Note**: This lesson only covers the very basics of Python. If you're already 18 | familiar with Python, you can probably skip it and target the next 19 | lesson, but who knows, you might discover some tips while reading 20 | this lesson. In any case, make sure to have all necessary packages 21 | installed before the next lesson. 22 | 23 | 24 | 25 | Installation 26 | ------------------------------------------------------------------------------- 27 | 28 | As of today (2018), Python exists mainly in two flavors: Python 2.x and 29 | Python 3.x. On most system, a 2.x version is already installed and for some 30 | systems, the 3.x is also installed. However, because we don't want to mess with 31 | the system installation, we'll install our own private version usign either: 32 | 33 | * Enthought [Canopy] is a comprehensive Python analysis environment that 34 | provides easy installation of the core scientific analytic and scientific 35 | Python packages, creating a robust platform you can explore, develop, and 36 | visualize on. 37 | 38 | * [Anaconda] by Continuum Analytics which is a completely free Python 39 | distribution (including for commercial use and redistribution). It includes 40 | more than 400 of the most popular Python packages for science, math, 41 | engineering, and data analysis. 42 | 43 | For this lesson, we'll go for [Anaconda] that is available for several 44 | architectures: 45 | 46 | * [Anaconda for windows](https://www.continuum.io/downloads#_windows) 47 | * [Anaconda for linux](https://www.continuum.io/downloads#_unix) 48 | * [Anaconda for OSX](https://www.continuum.io/downloads#_macosx) 49 | 50 | The anaconda comes with a lot of nice features but we won't use them (if you're 51 | interested, have a look at their 52 | [starter guide](http://conda.pydata.org/docs/test-drive.html)). Next step is to 53 | test the installation. To do that, you'll need to open a terminal and type: 54 | 55 | ``` bash 56 | $ conda --version 57 | conda 4.4.10 58 | ``` 59 | 60 | If this works, your conda version should be greater than 3.19.1. 61 | We can now try to start the Python interpreter. 62 | 63 | ``` bash 64 | $ python 65 | Python 3.6.4 (default, Jan 6 2018, 11:51:59) 66 | [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin 67 | Type "help", "copyright", "credits" or "license" for more information. 68 | >>> | 69 | ``` 70 | 71 | The anaconda comes also with the [IPython] interpreter which is far more 72 | powerful that the vanilla interpreter. 73 | 74 | 75 | ``` bash 76 | $ ipython 77 | Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) 78 | Type 'copyright', 'credits' or 'license' for more information 79 | IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. 80 | 81 | In [1]: | 82 | ``` 83 | 84 | Now let's check our installation to see if everything is ok. At this point, no 85 | need yet to understand what you're typing but we need to check if some 86 | important packages are present with the proper version. In the following 87 | examples, the `>>>` is the prompt and does not need to be typed. For example, 88 | if you chose the IPython interpetrer, you prompt is more likely something like 89 | `[12]:`. There is also a second prompt (`...`) meaning the previous line is not 90 | ended and needs to be terminated. This is for example the case when you enter an 91 | parantheses unbalanced expression (i.e. number of opening parathenses is greater 92 | than the number of closing parantheses). 93 | 94 | **Checking for numpy** 95 | 96 | ``` python 97 | >>> import numpy 98 | >> print(numpy.__version__) 99 | 1.13.3 100 | >>> numpy.test() # This can last a few seconds 101 | .......................... 102 | ``` 103 | 104 | **Checking for scipy** 105 | 106 | ``` python 107 | >>> import scipy 108 | >>> print(scipy.__version__) 109 | 0.19.1 110 | >>> scipy.test() # This can last a few seconds 111 | ........................... 112 | ``` 113 | 114 | **Checking for matplotlib** 115 | 116 | ``` python 117 | >>> import matplotlib 118 | >>> print(matplotlib.__version__) 119 | 2.1.0 120 | >>> matplotlib.test() # This can last a few minutes 121 | ........................... 122 | ``` 123 | 124 | **Checking for cython** 125 | 126 | ``` python 127 | >>> import cython 128 | >>> print(cython.__version__) 129 | 0.26 130 | ``` 131 | 132 | **Checking for opengl** 133 | 134 | ``` python 135 | >>> import OpenGL 136 | >>> print(OpenGL.__version__) 137 | 3.1.0 138 | ``` 139 | 140 | For each of these packages, the `x.y.z` version should be equal or greater than 141 | the displayed version. If this is not the case, then maybe you conda 142 | installation is not up to date. You can upgrade all packages at once using: 143 | 144 | ``` bash 145 | $ conda update --all 146 | ``` 147 | 148 | If something goes wrong, you'll have to check on the 149 | [Anaconda help page](http://conda.pydata.org/docs/help/help.html). 150 | 151 | 152 | Python is a calculator 153 | ------------------------------------------------------------------------------- 154 | 155 | ### Arithmetic computation 156 | 157 | Now it's time to experience a little bit with Python. Let's start with simple 158 | arithmetic operations because Python can be used as a regular calculator with 159 | standard arithmetic operations (addition, subtraction, multiplication, 160 | division, etc.) 161 | 162 | Addition 163 | ``` python 164 | >>> 2 + 3 165 | 5 166 | ``` 167 | 168 | Subtraction 169 | ``` python 170 | >>> 11 - 3 171 | 8 172 | ``` 173 | 174 | Multiplication 175 | ``` python 176 | >>> 3 * 4 177 | 12 178 | ``` 179 | 180 | Division 181 | ``` python 182 | >>> 11 / 5 183 | 2.2 184 | ``` 185 | 186 | Integer division 187 | ``` python 188 | >>> 11 // 5 189 | 2 190 | ``` 191 | 192 | Modulo operation 193 | ``` python 194 | >>> 11 % 5 195 | 1 196 | ``` 197 | 198 | Power 199 | ``` python 200 | >>> 2**3 201 | 8 202 | ``` 203 | 204 | Note that you cannot have spaces between digits of a number: 205 | 206 | ``` python 207 | >>> 1 0 + 2 208 | File "", line 1 209 | 1 0 + 2 210 | ^ 211 | SyntaxError: invalid syntax 212 | ``` 213 | 214 | In such a case, Python complains about a syntax error and points at the 215 | position of the error in the expression (using the `^` character). Why Python 216 | points at the zero and not the space ? Because you could have written `1 + 2` 217 | and the space would have been legal. The interpreter can only find the error 218 | after it discovers the extra digit and consequently points at it when reporting 219 | the error. 220 | 221 | Of course, you can compose any number of operations in order to compute a more 222 | complex operation: 223 | 224 | ``` python 225 | >>> 11 - (5 * (11//5)) # = 11 % 5 226 | 1 227 | ``` 228 | 229 | 230 | ### Native numeric types 231 | 232 | Python offers natively four main native numeric type, `bool`, `integer`, 233 | `float` and `complex`. But always keep in mind that they are the poor's man 234 | version of their mathematical equivalent (Boolean ($\mathbb{B}$), Integer 235 | ($\mathbb{Z}$), Real ($\mathbb{R}$) and Complex ($\mathbb{C}$)). `ìnteger` have 236 | limited range, `float` and `complex` have limited range and precision. 237 | 238 | In the case of `float` and `complex`, this has very important consequences. 239 | 240 | ``` python 241 | >>> 0.3 == 0.1*3 242 | False 243 | >>> 0.5 == 0.1*5 244 | True 245 | ``` 246 | 247 | The reason is that the decimal number `0.1` cannot be represented exactly is only 248 | approximated[^1]. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display 249 | 250 | ``` python 251 | >>> 0.1 252 | 0.1000000000000000055511151231257827021181583404541015625 253 | ``` 254 | 255 | Not very convenient... Consequently, Python (as many other languages) chose to 256 | display a rounded value instead. If you want to know more, have a look at the 257 | [Floating Point Arithmetic: Issues and Limitations](https://docs.python.org/3/tutorial/floatingpoint.html) 258 | chapter in the official 259 | [Python 3 tutorial](https://docs.python.org/3/tutorial/index.html). An 260 | immediate and practical consequence is that what you see in the console is not 261 | always what you get in memory, even if they're reasonably close. 262 | 263 | [^1]: *What Every Computer Scientist Should Know About Floating-Point Arithmetic* 264 | David Goldberg, Computing Surveys, 1991. 265 | 266 | 267 | For each type, there exist many ways to specify the same number. 268 | 269 | ``` python 270 | >>> True # Boolean 271 | >>> 0b1010 # Integer (base 2: binary) 272 | >>> 0o12 # Integer (base 8: octal) 273 | >>> 10 # Integer (base 10: decimal) 274 | >>> 0x0a # Integer (base 16: hexadecimal) 275 | >>> 10.0 # Float 276 | >>> 1e1 # Float (scientic notation) 277 | >>> float('inf') # Float (infinity +∞) 278 | >>> float('nan') # Float (Not A Number: nan) 279 | >>> 10 + 0j # Complex 280 | ``` 281 | 282 | But you can also force the type of any quantity by casting it. 283 | 284 | ``` python 285 | >>> bool(0) 286 | False 287 | >>> int(0) 288 | 0 289 | >>> float(0) 290 | 0.0 291 | >>> complex(0) 292 | 0j 293 | ``` 294 | 295 | 296 | ### Beyond simple arithmetic 297 | 298 | If you want to use more elaborate functions, you'll need the help of the 299 | [mathematical module](https://docs.python.org/3/library/math.html) for real 300 | numbers and the 301 | [complex mathematical module](https://docs.python.org/3/library/cmath.html) for 302 | complex numbers. 303 | 304 | **Power and logarithmic functions** 305 | 306 | ``` python 307 | >>> from math import * 308 | >>> log(exp(1.234)) 309 | 1.234 310 | ``` 311 | 312 | **Trigonometric functions** 313 | 314 | ``` python 315 | >>> from math import * 316 | >>> asin(sin(1.234)) 317 | 1.234 318 | ``` 319 | 320 | **Hyperbolic functions** 321 | 322 | ``` python 323 | >>> from math import * 324 | >>> asinh(sinh(1.234)) 325 | 1.234 326 | ``` 327 | 328 | **Special functions** 329 | 330 | ``` python 331 | >>> from math import * 332 | >>> gamma(2.0) 333 | 1.0 334 | ``` 335 | 336 | **Constants** 337 | 338 | ``` python 339 | >>> from math import * 340 | >>> pi 341 | 3.141592653589793 342 | >>> e 343 | 2.718281828459045 344 | >>> nan 345 | nan 346 | >>> inf 347 | inf 348 | ``` 349 | 350 | 351 | ### Logical operations 352 | 353 | Logic is an important part of Python because this allows to manipulate and 354 | compare quantities, including numbers, and we'll see later that it works for 355 | all kind of objects. 356 | 357 | ``` python 358 | >>> True and True # Logical and 359 | >>> 42 or 57 # Logical or 360 | >>> 1 == 2-1 # Equality test 361 | >>> 1 != 2 # Inequality test 362 | >>> 1 is 2-1 # Identity test 363 | >>> not 24 # Negation 364 | ``` 365 | 366 | Note that the `is` keyword really means identity, it is not a test for equality. 367 | 368 | ``` python 369 | >>> 1 is 1.0 370 | False 371 | >>> True is 1 372 | False 373 | >>> True and 1 374 | True 375 | ``` 376 | 377 | ### Bitwise operations 378 | 379 | Bitwise operations are logical operations that operate a the bit level. They 380 | might be useful in some situations but we won't use them in this course. 381 | 382 | ``` python 383 | >>> 1 | 2 # bitwise or 384 | >>> 1 & 2 # bitwise and 385 | >>> 1 ^ 2 # bitwise xor 386 | >>> 8 << 2 # bitwise left shift 387 | >>> 8 >> 2 # bitwise right shift 388 | >>> ~8 # bitwise negation 389 | ``` 390 | 391 | 392 | 393 | 394 | Python is much more 395 | ------------------------------------------------------------------------------- 396 | 397 | Beside being a convenient calculator, Python is also (and mostly) a powerful 398 | programming language with an elegant and intuitive syntax. Furthermore, you 399 | have to knwo that Python is an interpreted langage, meaning each time you enter 400 | a set of instructions, they need to be intepreted by the Python interpreter. This 401 | can make Python quite slow in some situation but we'll later how to overcome most 402 | of Python slowness. 403 | 404 | ### Variables 405 | 406 | Until now, we have been playing in the console, throwing some expressions in 407 | the interpreted and checked the result. Problem is that those expression cannot 408 | be re-used. It's thus time to save us some trouble and assign those expressions 409 | to variables. This can be done quite naturally. 410 | 411 | ``` python 412 | >>> width = 1 413 | >>> height = 2 414 | ``` 415 | 416 | What is really cool though is that you can assign several variables at once: 417 | 418 | ``` python 419 | >>> width, height = 2,1 420 | >>> width 421 | 1 422 | >>> height 423 | 2 424 | ``` 425 | 426 | However, you cannot refer a new variable on the same line 427 | 428 | ``` python 429 | >>> width, height = 2, 2*width 430 | Traceback (most recent call last): 431 | File "", line 1, in 432 | NameError: name 'width' is not defined 433 | ``` 434 | 435 | In this case, you have to split the expression in two distinct lines. 436 | 437 | ``` python 438 | >>> width = 2 439 | >>> height = 2*width 440 | ``` 441 | 442 | Variables can be manipulated just as any expression but they need to have been 443 | defined previously. 444 | 445 | ``` python 446 | >>> a = 2*b 447 | Traceback (most recent call last): 448 | File "", line 1, in 449 | NameError: name 'b' is not defined 450 | ``` 451 | 452 | In interactive mode, that is, the console mode we've been using from the start, 453 | there is a special variable whose name is '_' and that contains the last 454 | **printed** expression. 455 | 456 | ``` python 457 | >>> very_long_name = 10 458 | >>> very_long_name 459 | 10 460 | >>> b = 2 + _ # here, _ = very_long_name 461 | >>> b 462 | 12 463 | ``` 464 | 465 | Don't assign explicitely a value to the `_` variable or you'll kill the magic, 466 | and you don't want to do that, do you ? 467 | 468 | 469 | 470 | ### Containers 471 | 472 | Beside the numeric types, Python also offers native container type (also known 473 | as collections), one is dedicated to the storing of ordered sequence of 474 | characters (i.e. strings) while some others allows to store just anything and 475 | offers different properties. In a nutshell: 476 | 477 | ``` python 478 | >>> "1,2,3,4" # String (ordered, character only, immutable, indexable) 479 | >>> (1,2,3,4) # Tuple (ordered, immutable, indexable) 480 | >>> [1,2,3,4] # List (ordered, mutable, indexable) 481 | >>> {1,2,3,4} # Set (unordered, mutable, unique elements) 482 | >>> {1:2,3:4} # Dictionnary (unordered, mutable, hashable) 483 | ``` 484 | 485 | **Strings** 486 | 487 | Strings are expressed by enclosing a text using pairs of " or \' 488 | characters. Depending on the character you chose, you can use the other inside 489 | the string. 490 | 491 | ``` python 492 | >>> "Hello 'world!'" 493 | "Hello 'world!'" 494 | >>> 'Hello "world"!' 495 | 'Hello "world!"' 496 | >>> "" # empty string 497 | '' 498 | ``` 499 | 500 | Note that you can split a string using spaces and Python will concatenate all 501 | the pieces together. 502 | 503 | ``` python 504 | >>> "Hello" " " "world!" 505 | 'Hello world!' 506 | ``` 507 | 508 | 509 | But you can also explicitely concatenate the different pieces together. 510 | 511 | ``` python 512 | >>> "Hello" + " " + "world!" 513 | 'Hello world!' 514 | ``` 515 | 516 | For multiline strings, you need to triple the enclosing quotes or to use parentheses. 517 | 518 | ``` python 519 | >>> """Hello 520 | ... world!""" 521 | 'Hello\nworld!' 522 | 523 | >>> '''Hello 524 | ... world!''' 525 | 'Hello\nworld!' 526 | 527 | >>>("Hello" 528 | ... " world!") 529 | 'Hello world!' 530 | ``` 531 | 532 | In the output above, you can seen the "\n" character has been added, it 533 | expresses the newline character. There are several backslashed characters: 534 | 535 | Escape Sequence | Meaning 536 | ----------------|--------------------------- 537 | \\\\ | Backslash (\) 538 | \\\' | Single quote (') 539 | \\\" | Double quote (") 540 | \a | ASCII Bell (BEL) 541 | \b | ASCII Backspace (BS) 542 | \n | ASCII Linefeed (LF) 543 | \r | ASCII Carriage Return (CR) 544 | \t | ASCII Horizontal Tab (TAB) 545 | \v | ASCII Vertical Tab (TAB) 546 | 547 | This means the '\n' will be interpreted as a new line character, but what if we 548 | want to really have '\n' in our string as in 'C:\\some\\name'? Either we 549 | "escape" all the backslash or we prefix the string with `r` meaning special 550 | characters won't be interpeted. 551 | 552 | ``` python 553 | >>> print('C:\some\name') 554 | 'C:\some 555 | ame' 556 | >>> print('C:\\some\\name') 557 | C:\some\name 558 | >>> print(r'C:\some\name') 559 | C:\some\name 560 | ``` 561 | 562 | Strings in Python 3 are encoded using UTF-8 ([Unicode]), meaning you can encode 563 | pretty much any glyphs fom any languages (and emojis as well). 564 | 565 | ``` python 566 | >>> "ℕ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ" 567 | 'ℕ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ' 568 | ``` 569 | 570 | **Tuples** 571 | 572 | Tuples are immutable containers, meaning they cannot be changed after they've 573 | been created. They allow to store pretty much anything, including other tuples. 574 | To create a tuple, you simply write a comma-separated list of values, 575 | optionally enclosed by parentheses. 576 | 577 | ``` python 578 | >>> 1,2,3 579 | (1, 2, 3) 580 | >>> 1, "2", (1,2) 581 | (1, '2', (1, 2)) 582 | >>> () # empty tuple 583 | () 584 | ``` 585 | 586 | **Lists** 587 | 588 | Lists are mutable containers quite similar to tuple, but they can be modified 589 | after creation. They also allow to store pretty much anything. To create a 590 | list, you need to write a comma-separated list of values enclosed by square 591 | brackets. 592 | 593 | ``` python 594 | >>> [1,2,3] 595 | [1, 2, 3] 596 | 597 | >>> [1, "2", (1,2)] 598 | [1, '2', (1, 2)] 599 | 600 | >>> [] # empty list 601 | [] 602 | ``` 603 | 604 | **Sets** 605 | 606 | Sets are mutable containers (they can be modified) and contains only unique 607 | elements, i.e. they prevent to have duplicated elements. 608 | 609 | ``` python 610 | >>> {1, 2, 2} 611 | {1, 2} 612 | 613 | >>> {1, 2, "2"} 614 | {1, 2, '2'} 615 | ``` 616 | 617 | **Dictionnary** 618 | 619 | Dictionnary can be considered as a kind of associative memory where items are 620 | indexed by a key (instead of integer). The type of the key can be pretty much 621 | anything. 622 | 623 | ``` python 624 | >>> { "item 1" : 1, "item 2" : 2} 625 | {'item 2': 2, 'item 1': 1} 626 | >>> { 1 : 2, 3 : 4} 627 | {1: 2, 3: 4} 628 | ``` 629 | 630 | 631 | ### Indexing and slicing 632 | 633 | Individual items of a list, tuple and strings can be accessed invidually using 634 | their position as index. Note that first element has index 0 635 | 636 | ``` python 637 | >>> d = [1,2,3,4,5] 638 | >>> d[0] 639 | 1 640 | ``` 641 | 642 | This also work using negative indices, meaning the position has to be taken 643 | from the end. Note that last element has index -1. 644 | 645 | ``` python 646 | >>> s = "Hello world!" 647 | >>> s[-1] 648 | '!' 649 | ``` 650 | 651 | Furthermore, we can also access a **range** of items using the slice notation 652 | `start:end`. Note that both start and end are optional. 653 | 654 | ``` python 655 | >>> d = [1,2,3,4,5] 656 | >>> d[1:3] 657 | [2, 3] 658 | ``` 659 | 660 | If start is missing, Python will implicitly replace it by the start of the 661 | list. If end is missing, Python will implicitly replace it by the end of the 662 | list. 663 | 664 | 665 | ``` python 666 | >>> d = [1,2,3,4,5] 667 | 668 | >>> d[1:] 669 | [2, 3, 4, 5] 670 | 671 | >>> d[:2] 672 | [1, 2] 673 | 674 | >>> d[:] 675 | [1, 2, 3, 4, 5] 676 | ``` 677 | 678 | We can further refine our slice by giving the step to between elements. The new 679 | syntax is thus `start:end:step`. 680 | 681 | ``` python 682 | >>> d = [1,2,3,4,5,6] 683 | >>> d[0:5:2] 684 | [1, 3, 5] 685 | 686 | # Can be abbreviated into 687 | >>> d[::2] # 688 | [1, 3, 5] 689 | ``` 690 | 691 | What if we use a negative step? We get the reversed sequence. 692 | 693 | ``` python 694 | >>> d = [1,2,3,4,5,6] 695 | >>> d[::-1] 696 | [6, 5, 4, 3, 2, 1] 697 | ``` 698 | 699 | Because strings are indexable, indexing and slicing work just the same. 700 | 701 | 702 | ``` python 703 | >>> s = "Hello world!" 704 | >>> s[6:-1] 705 | " world" 706 | >>> s[6:] 707 | " world!" 708 | ``` 709 | 710 | 711 | ### Adding and removing 712 | 713 | Adding an element to a mutable container can be done in two distinct 714 | ways. Either by creating a new container that is the container plus the new 715 | item, or by inserting the new item into the container, hence modyfying it. 716 | 717 | ``` python 718 | >>> l1 = [1, 2, 3] 719 | >>> l2 = l1 + [4] 720 | >>> l2 721 | [1, 2, 3, 4] 722 | >>> l1.append(4) 723 | >>> l1 724 | [1, 2, 3, 4] 725 | ``` 726 | 727 | For removing items, we need to use the **del** keyword and give indices where 728 | to delete items. 729 | 730 | ``` python 731 | >>> l1 = [1, 2, 3, 4, 5, 6] 732 | >>> del l1[0 ] 733 | >>> l1 734 | [2, 3, 4, 5, 6] 735 | ``` 736 | 737 | But we can also delete a range of indices at once. 738 | 739 | ``` python 740 | >>> l1 = [1, 2, 3, 4, 5, 6] 741 | >>> del l1[::2] 742 | >>> l1 743 | [2,4,6] 744 | ``` 745 | 746 | 747 | 748 | Running scripts 749 | ------------------------------------------------------------------------------- 750 | 751 | Until now, we have been mostly typing some Python expressions directly into 752 | the interpreter, meaning we had to type and retype the same expression again 753 | and again. To save us some time, it's time to put all these commands into a 754 | file that will be ran by the Python interpreter. First, chose a text editor you 755 | might like and fill it with some python commands. 756 | 757 | ``` python 758 | print("Hello world!") 759 | ``` 760 | 761 | Then save it with the name `script.py`. The `.py` is the regular file extension 762 | used for Python programs. You are free to use any exension you like, but using 763 | `.py` is a damn good idea since the operating system can make the connection 764 | with Python based on this extension. 765 | 766 | To run this script, we have two options. First, we can start it using the 767 | regular python interpreter. 768 | 769 | ``` bash 770 | $ python script.py 771 | Hello world! 772 | $ 773 | ``` 774 | 775 | If you run the above command, Python will terminate as soon as your program 776 | has ended. If you want to stay within the Python interpreter, you'll have to use 777 | the `-i` switch (interactive mode) that tells Python to not exit once the program 778 | has finished. 779 | 780 | ``` bash 781 | $ python script.py 782 | Hello world! 783 | >>> 784 | ``` 785 | 786 | Another option is to use [IPython] that allows to run a script from the within 787 | the interpreter. 788 | 789 | ``` python 790 | [1]: %run script.py 791 | Hello world! 792 | [2]: 793 | ``` 794 | 795 | ### Indentation 796 | 797 | Something you will discover soon enough (or maybe you've already discovered it) 798 | is that Python is rather nitpicking about indentation. 799 | 800 | ``` python 801 | >>> a = 1 802 | >>> a = 1 803 | File "", line 1 804 | a = 1 805 | ^ 806 | IndentationError: unexpected indent 807 | ``` 808 | 809 | The reason is that indentation has a semantic meaning but we'll see that later. 810 | 811 | 812 | 813 | The Jupyter notebook 814 | ------------------------------------------------------------------------------- 815 | 816 | The [Jupyter] notebook is a web application that allows you to create and share 817 | documents that contain live code, equations, visualizations and explanatory 818 | text. Uses include (but not limited to): 819 | 820 | * data cleaning and transformation 821 | * numerical simulation 822 | * statistical modeling 823 | * machine learning 824 | 825 | The Jupyter notebook is not restricted to python and support for over 40 826 | programming languages, including those popular in Data Science such as Python, 827 | R, Julia and Scala. 828 | 829 | You can try it [online](https://try.jupyter.org) but you can also start a new 830 | one locally: 831 | 832 | ```shell 833 | $ jupyter notebook 834 | ``` 835 | 836 | This should open a new tab in your browser (or open a new browser if it was 837 | closed) showing your available notebooks. There should be none, so you can 838 | create a new one and start typing python code. 839 | 840 | We won't explore all that you can do with notebook during this course but you can 841 | have a look at the [nbviewer](http://nbviewer.jupyter.org) to see what can be 842 | done with them. 843 | 844 | 845 | 846 | Exercises 847 | ------------------------------------------------------------------------------- 848 | 849 | We'll stop here with this very short introduction to Python. It's now time to 850 | move on to programming with python. So now, shutdown your computer, grab a pen 851 | a sheet of paper and try to answer these exercices without typing them in a 852 | Python interpreter. Once you've answered every questiosn, you can chek them. 853 | 854 | ###Find the type of the following expressions 855 | 856 | ``` python 857 | .0 858 | ``` 859 | 860 | ``` python 861 | -1 862 | ``` 863 | 864 | ``` python 865 | 1, 866 | ``` 867 | 868 | ``` python 869 | '4.0 + 5.0' 870 | ``` 871 | 872 | ``` python 873 | 1e2 874 | ``` 875 | 876 | ``` python 877 | 1j 878 | ``` 879 | 880 | ``` python 881 | [{()}] 882 | ``` 883 | 884 | ``` python 885 | float('nan') 886 | ``` 887 | 888 | 889 | ### Are these legal python expressions? 890 | 891 | ```python 892 | 1 + 1 == 2 893 | ``` 894 | 895 | ```python 896 | 1 = 2 897 | ``` 898 | 899 | ``` python 900 | (1,)[0] 901 | ``` 902 | 903 | ``` python 904 | 1 + 1i 905 | ``` 906 | 907 | ``` python 908 | 1 <- 2 909 | ``` 910 | 911 | ``` python 912 | 0.+.0 913 | ``` 914 | 915 | ``` python 916 | 3***3 917 | ``` 918 | 919 | ``` python 920 | 3 <<2>> 3 921 | ``` 922 | 923 | ``` python 924 | [({})] 925 | ``` 926 | 927 | 928 | ### Find the result of the following expressions 929 | 930 | ``` python 931 | 1.+1, 932 | ``` 933 | 934 | ``` python 935 | 1,+1. 936 | ``` 937 | 938 | ``` python 939 | (1,)*3 940 | ``` 941 | 942 | ``` python 943 | 1e1000 - 1e1000 944 | ``` 945 | 946 | ``` python 947 | 'abc'*3 948 | ``` 949 | 950 | ``` python 951 | 3 or 10 952 | ``` 953 | 954 | ``` python 955 | 3 <2> 3 956 | ``` 957 | 958 | ### How to... 959 | 960 | * Build the empty set? 961 | * Get the list of unique letters composing "abracadabra" 962 | * Build a tuple of two empty lists 963 | * Generate a list of all even numbers between 20 and 40 (included) 964 | * Check if a word is a palindrom? 965 | * Transform the string "1.2" into a float? 966 | * Count the number of unique elements in a list? 967 | * Find the maximum representable integer ? 968 | * Print the string `"Isn't, he said"` (including quotes)? 969 | * Swap the content of two variables? 970 | 971 | 972 | 973 | Resources 974 | ------------------------------------------------------------------------------- 975 | 976 | Here are a set of resources for those who want to go further in their knowledge 977 | of Python. 978 | 979 | * [**The (official) Python tutorial**](https://docs.python.org/3/tutorial/index.html) 980 | does not attempt to be comprehensive and cover every single feature, or even 981 | every commonly used feature. Instead, it introduces many of Python's most 982 | noteworthy features, and will give you a good idea of the language's flavor 983 | and style. 984 | 985 | * [**Dive into python**](http://www.diveintopython3.net) is a teach-by-example 986 | guide to the paradigms of programming in Python and modern software 987 | development techniques. It assumes some preexisting knowledge of programming, 988 | although not necessarily in Python. 989 | 990 | * [**Programming with Python**](https://github.com/vsego/python-lecture-notes) are 991 | the lecture notes from the course taught at the University of Manchester in 992 | the academic year 2014/15. The aim of the course is to lay a strong 993 | foundation for your future programming requirements, be they in Python or 994 | some other language or a similar tool. 995 | 996 | * [**Scipy Lecture Notes**](http://www.scipy-lectures.org) are a set of tutorials 997 | on the scientific Python ecosystem: a quick introduction to central tools and 998 | techniques. The different chapters each correspond to a 1 to 2 hours course 999 | with increasing level of expertise, from beginner to expert. 1000 | 1001 | 1002 | 1003 | [Anaconda]: https://www.continuum.io/downloads/ 1004 | [Canopy]: https://enthought.com/products/canopy/ 1005 | [Python]: http://www.python.org 1006 | [Numpy]: http://www.numpy.org 1007 | [Scipy]: http://www.scipy.org 1008 | [Pandas]: http://pandas.pydata.org 1009 | [Matplotlib]: http://matplotlib.org 1010 | [IPython]: http://ipython.org 1011 | [Jupyter]: http://jupyter.org 1012 | [Git]: https://git-scm.com 1013 | [OpenGL]: https://www.opengl.org 1014 | [Glumpy]: https://glumpy.github.io 1015 | [Bokeh]: https://bokeh.org 1016 | [Cython]: http://cython.org 1017 | [EDMI]: http://www.math.u-bordeaux1.fr/ED/ecole_doctorale/ 1018 | [University of Bordeaux]: http://www.u-bordeaux.com 1019 | [Unicode]: https://en.wikipedia.org/wiki/Unicode 1020 | 1021 | --------------------------------------------------------------------------------