├── LICENSE.txt ├── README.md ├── data ├── XKCD.png ├── indent.png └── notebook.png └── lessons ├── 01-installation.md ├── 02-introduction.md └── introduction.md /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Attribution 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution 4.0 International Public License 58 | 59 | By exercising the Licensed Rights (defined below), You accept and agree 60 | to be bound by the terms and conditions of this Creative Commons 61 | Attribution 4.0 International Public License ("Public License"). To the 62 | extent this Public License may be interpreted as a contract, You are 63 | granted the Licensed Rights in consideration of Your acceptance of 64 | these terms and conditions, and the Licensor grants You such rights in 65 | consideration of benefits the Licensor receives from making the 66 | Licensed Material available under these terms and conditions. 67 | 68 | 69 | Section 1 -- Definitions. 70 | 71 | a. Adapted Material means material subject to Copyright and Similar 72 | Rights that is derived from or based upon the Licensed Material 73 | and in which the Licensed Material is translated, altered, 74 | arranged, transformed, or otherwise modified in a manner requiring 75 | permission under the Copyright and Similar Rights held by the 76 | Licensor. For purposes of this Public License, where the Licensed 77 | Material is a musical work, performance, or sound recording, 78 | Adapted Material is always produced where the Licensed Material is 79 | synched in timed relation with a moving image. 80 | 81 | b. Adapter's License means the license You apply to Your Copyright 82 | and Similar Rights in Your contributions to Adapted Material in 83 | accordance with the terms and conditions of this Public License. 84 | 85 | c. Copyright and Similar Rights means copyright and/or similar rights 86 | closely related to copyright including, without limitation, 87 | performance, broadcast, sound recording, and Sui Generis Database 88 | Rights, without regard to how the rights are labeled or 89 | categorized. For purposes of this Public License, the rights 90 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 91 | Rights. 92 | 93 | d. Effective Technological Measures means those measures that, in the 94 | absence of proper authority, may not be circumvented under laws 95 | fulfilling obligations under Article 11 of the WIPO Copyright 96 | Treaty adopted on December 20, 1996, and/or similar international 97 | agreements. 98 | 99 | e. Exceptions and Limitations means fair use, fair dealing, and/or 100 | any other exception or limitation to Copyright and Similar Rights 101 | that applies to Your use of the Licensed Material. 102 | 103 | f. Licensed Material means the artistic or literary work, database, 104 | or other material to which the Licensor applied this Public 105 | License. 106 | 107 | g. Licensed Rights means the rights granted to You subject to the 108 | terms and conditions of this Public License, which are limited to 109 | all Copyright and Similar Rights that apply to Your use of the 110 | Licensed Material and that the Licensor has authority to license. 111 | 112 | h. Licensor means the individual(s) or entity(ies) granting rights 113 | under this Public License. 114 | 115 | i. Share means to provide material to the public by any means or 116 | process that requires permission under the Licensed Rights, such 117 | as reproduction, public display, public performance, distribution, 118 | dissemination, communication, or importation, and to make material 119 | available to the public including in ways that members of the 120 | public may access the material from a place and at a time 121 | individually chosen by them. 122 | 123 | j. Sui Generis Database Rights means rights other than copyright 124 | resulting from Directive 96/9/EC of the European Parliament and of 125 | the Council of 11 March 1996 on the legal protection of databases, 126 | as amended and/or succeeded, as well as other essentially 127 | equivalent rights anywhere in the world. 128 | 129 | k. You means the individual or entity exercising the Licensed Rights 130 | under this Public License. Your has a corresponding meaning. 131 | 132 | 133 | Section 2 -- Scope. 134 | 135 | a. License grant. 136 | 137 | 1. Subject to the terms and conditions of this Public License, 138 | the Licensor hereby grants You a worldwide, royalty-free, 139 | non-sublicensable, non-exclusive, irrevocable license to 140 | exercise the Licensed Rights in the Licensed Material to: 141 | 142 | a. reproduce and Share the Licensed Material, in whole or 143 | in part; and 144 | 145 | b. produce, reproduce, and Share Adapted Material. 146 | 147 | 2. Exceptions and Limitations. For the avoidance of doubt, where 148 | Exceptions and Limitations apply to Your use, this Public 149 | License does not apply, and You do not need to comply with 150 | its terms and conditions. 151 | 152 | 3. Term. The term of this Public License is specified in Section 153 | 6(a). 154 | 155 | 4. Media and formats; technical modifications allowed. The 156 | Licensor authorizes You to exercise the Licensed Rights in 157 | all media and formats whether now known or hereafter created, 158 | and to make technical modifications necessary to do so. The 159 | Licensor waives and/or agrees not to assert any right or 160 | authority to forbid You from making technical modifications 161 | necessary to exercise the Licensed Rights, including 162 | technical modifications necessary to circumvent Effective 163 | Technological Measures. For purposes of this Public License, 164 | simply making modifications authorized by this Section 2(a) 165 | (4) never produces Adapted Material. 166 | 167 | 5. Downstream recipients. 168 | 169 | a. Offer from the Licensor -- Licensed Material. Every 170 | recipient of the Licensed Material automatically 171 | receives an offer from the Licensor to exercise the 172 | Licensed Rights under the terms and conditions of this 173 | Public License. 174 | 175 | b. No downstream restrictions. You may not offer or impose 176 | any additional or different terms or conditions on, or 177 | apply any Effective Technological Measures to, the 178 | Licensed Material if doing so restricts exercise of the 179 | Licensed Rights by any recipient of the Licensed 180 | Material. 181 | 182 | 6. No endorsement. Nothing in this Public License constitutes or 183 | may be construed as permission to assert or imply that You 184 | are, or that Your use of the Licensed Material is, connected 185 | with, or sponsored, endorsed, or granted official status by, 186 | the Licensor or others designated to receive attribution as 187 | provided in Section 3(a)(1)(A)(i). 188 | 189 | b. Other rights. 190 | 191 | 1. Moral rights, such as the right of integrity, are not 192 | licensed under this Public License, nor are publicity, 193 | privacy, and/or other similar personality rights; however, to 194 | the extent possible, the Licensor waives and/or agrees not to 195 | assert any such rights held by the Licensor to the limited 196 | extent necessary to allow You to exercise the Licensed 197 | Rights, but not otherwise. 198 | 199 | 2. Patent and trademark rights are not licensed under this 200 | Public License. 201 | 202 | 3. To the extent possible, the Licensor waives any right to 203 | collect royalties from You for the exercise of the Licensed 204 | Rights, whether directly or through a collecting society 205 | under any voluntary or waivable statutory or compulsory 206 | licensing scheme. In all other cases the Licensor expressly 207 | reserves any right to collect such royalties. 208 | 209 | 210 | Section 3 -- License Conditions. 211 | 212 | Your exercise of the Licensed Rights is expressly made subject to the 213 | following conditions. 214 | 215 | a. Attribution. 216 | 217 | 1. If You Share the Licensed Material (including in modified 218 | form), You must: 219 | 220 | a. retain the following if it is supplied by the Licensor 221 | with the Licensed Material: 222 | 223 | i. identification of the creator(s) of the Licensed 224 | Material and any others designated to receive 225 | attribution, in any reasonable manner requested by 226 | the Licensor (including by pseudonym if 227 | designated); 228 | 229 | ii. a copyright notice; 230 | 231 | iii. a notice that refers to this Public License; 232 | 233 | iv. a notice that refers to the disclaimer of 234 | warranties; 235 | 236 | v. a URI or hyperlink to the Licensed Material to the 237 | extent reasonably practicable; 238 | 239 | b. indicate if You modified the Licensed Material and 240 | retain an indication of any previous modifications; and 241 | 242 | c. indicate the Licensed Material is licensed under this 243 | Public License, and include the text of, or the URI or 244 | hyperlink to, this Public License. 245 | 246 | 2. You may satisfy the conditions in Section 3(a)(1) in any 247 | reasonable manner based on the medium, means, and context in 248 | which You Share the Licensed Material. For example, it may be 249 | reasonable to satisfy the conditions by providing a URI or 250 | hyperlink to a resource that includes the required 251 | information. 252 | 253 | 3. If requested by the Licensor, You must remove any of the 254 | information required by Section 3(a)(1)(A) to the extent 255 | reasonably practicable. 256 | 257 | 4. If You Share Adapted Material You produce, the Adapter's 258 | License You apply must not prevent recipients of the Adapted 259 | Material from complying with this Public License. 260 | 261 | 262 | Section 4 -- Sui Generis Database Rights. 263 | 264 | Where the Licensed Rights include Sui Generis Database Rights that 265 | apply to Your use of the Licensed Material: 266 | 267 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 268 | to extract, reuse, reproduce, and Share all or a substantial 269 | portion of the contents of the database; 270 | 271 | b. if You include all or a substantial portion of the database 272 | contents in a database in which You have Sui Generis Database 273 | Rights, then the database in which You have Sui Generis Database 274 | Rights (but not its individual contents) is Adapted Material; and 275 | 276 | c. You must comply with the conditions in Section 3(a) if You Share 277 | all or a substantial portion of the contents of the database. 278 | 279 | For the avoidance of doubt, this Section 4 supplements and does not 280 | replace Your obligations under this Public License where the Licensed 281 | Rights include other Copyright and Similar Rights. 282 | 283 | 284 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 285 | 286 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 287 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 288 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 289 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 290 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 291 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 292 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 293 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 294 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 295 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 296 | 297 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 298 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 299 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 300 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 301 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 302 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 303 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 304 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 305 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 306 | 307 | c. The disclaimer of warranties and limitation of liability provided 308 | above shall be interpreted in a manner that, to the extent 309 | possible, most closely approximates an absolute disclaimer and 310 | waiver of all liability. 311 | 312 | 313 | Section 6 -- Term and Termination. 314 | 315 | a. This Public License applies for the term of the Copyright and 316 | Similar Rights licensed here. However, if You fail to comply with 317 | this Public License, then Your rights under this Public License 318 | terminate automatically. 319 | 320 | b. Where Your right to use the Licensed Material has terminated under 321 | Section 6(a), it reinstates: 322 | 323 | 1. automatically as of the date the violation is cured, provided 324 | it is cured within 30 days of Your discovery of the 325 | violation; or 326 | 327 | 2. upon express reinstatement by the Licensor. 328 | 329 | For the avoidance of doubt, this Section 6(b) does not affect any 330 | right the Licensor may have to seek remedies for Your violations 331 | of this Public License. 332 | 333 | c. For the avoidance of doubt, the Licensor may also offer the 334 | Licensed Material under separate terms or conditions or stop 335 | distributing the Licensed Material at any time; however, doing so 336 | will not terminate this Public License. 337 | 338 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 339 | License. 340 | 341 | 342 | Section 7 -- Other Terms and Conditions. 343 | 344 | a. The Licensor shall not be bound by any additional or different 345 | terms or conditions communicated by You unless expressly agreed. 346 | 347 | b. Any arrangements, understandings, or agreements regarding the 348 | Licensed Material not stated herein are separate from and 349 | independent of the terms and conditions of this Public License. 350 | 351 | 352 | Section 8 -- Interpretation. 353 | 354 | a. For the avoidance of doubt, this Public License does not, and 355 | shall not be interpreted to, reduce, limit, restrict, or impose 356 | conditions on any use of the Licensed Material that could lawfully 357 | be made without permission under this Public License. 358 | 359 | b. To the extent possible, if any provision of this Public License is 360 | deemed unenforceable, it shall be automatically reformed to the 361 | minimum extent necessary to make it enforceable. If the provision 362 | cannot be reformed, it shall be severed from this Public License 363 | without affecting the enforceability of the remaining terms and 364 | conditions. 365 | 366 | c. No term or condition of this Public License will be waived and no 367 | failure to comply consented to unless expressly agreed to by the 368 | Licensor. 369 | 370 | d. Nothing in this Public License constitutes or may be interpreted 371 | as a limitation upon, or waiver of, any privileges and immunities 372 | that apply to the Licensor or You, including from the legal 373 | processes of any jurisdiction or authority. 374 | 375 | 376 | ======================================================================= 377 | 378 | Creative Commons is not a party to its public 379 | licenses. Notwithstanding, Creative Commons may elect to apply one of 380 | its public licenses to material it publishes and in those instances 381 | will be considered the “Licensor.” The text of the Creative Commons 382 | public licenses is dedicated to the public domain under the CC0 Public 383 | Domain Dedication. Except for the limited purpose of indicating that 384 | material is shared under a Creative Commons public license or as 385 | otherwise permitted by the Creative Commons policies published at 386 | creativecommons.org/policies, Creative Commons does not authorize the 387 | use of the trademark "Creative Commons" or any other trademark or logo 388 | of Creative Commons without its prior written consent including, 389 | without limitation, in connection with any unauthorized modifications 390 | to any of its public licenses or any other arrangements, 391 | understandings, or agreements concerning use of licensed material. For 392 | the avoidance of doubt, this paragraph does not form part of the 393 | public licenses. 394 | 395 | Creative Commons may be contacted at creativecommons.org. 396 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Scientific Python Crash Course 3 | 4 | ![](data/XKCD.png) 5 | 6 | This is the material for a 20 hours crash course on Scientific Python 7 | that has been split in 5 beginner and 3 advanced 8 | modules. Contributions and feedbacks are welcome. Released under a 9 | [CC-BY 4.0 10 | International](https://creativecommons.org/licenses/by/4.0/legalcode) license. 11 | 12 | Nicolas P. Rougier


13 | 14 | 15 | ## Material 16 | 17 | ### [1. Installation](lessons/01-installation.md) 18 | 19 | 20 | 21 | This lesson aims at providing the student with a clean development environment, 22 | including Python installation and essential packages (using the [Anaconda] 23 | installer), a decent text editor (e.g. [emacs], [vim], [atom], [notepad++]), a 24 | git command line and a shell. We'll also introduce the Python & [IPython] 25 | shells, the [Jupyter] notebook and explains how to run a python 26 | script from the command line or from inside the [IPython] shell. 27 | 28 | **Keywords**: `anaconda`, `shell`, `notebook`, `script`, `git`, `editor` 29 | **Prerequisites**: None 30 | **Resources**: None 31 | 32 |
33 | 34 | 35 | ### [2. Introduction](lessons/introduction.md) 36 | 37 | 38 | 39 | We introduce here the Python language. Only the bare minimum necessary for 40 | getting started with Numpy and Scipy is addressed here. To learn more about 41 | the language, consider going through the excellent tutorial 42 | https://docs.python.org/tutorial. Dedicated books are also available, such as 43 | http://www.diveintopython.net/. 44 | 45 | **Keywords**: `python`, `types`, `control flow`, `function`, `package` 46 | **Prerequisites**: Installation 47 | **Resources**: [The Python tutorial](https://docs.python.org/3/tutorial/) 48 | 49 |
50 | 51 | 52 | ### [3. Numerical computing (numpy)](https://scipy-lectures.org/intro/numpy/index.html) 53 | 54 | 55 | 56 | This lesson gives an overview of [NumPy], the core library for performant 57 | numerical computing, with support for large, multi-dimensional 58 | arrays and matrices, along with a large collection of high-level mathematical 59 | functions to operate on these arrays. 60 | 61 | **Keywords**: `numpy`, `array`, `dtype`, `shape`, `broadcast` 62 | **Prerequisites**: Introduction 63 | **Resources**: [SciPy Lecture Notes](https://scipy-lectures.org/) 64 | 65 |
66 | 67 | 68 | ### [4. Data visualization (matplotlib)](https://github.com/rougier/matplotlib-tutorial) 69 | 70 | 71 | 72 | In this lesson, we are going to explore [Matplotlib] that is the single most 73 | used Python package for 2D-graphics. It provides both a very quick way to 74 | visualize data from Python and to produce publication-quality figures in many 75 | different formats. We'll cover only most common use cases. 76 | 77 | **Keywords**: `matplotlib`, `figure`, `plot`, `data` 78 | **Prerequisites**: Introduction, Numerical computing 79 | **Resources**: [Scientific Visulization: Python + Matplotlib](https://www.labri.fr/perso/nrougier/scientific-visualization.html) 80 | 81 |
82 | 83 | 84 | ### [5. Scientific computing (scipy)]() 85 | 86 | 87 | 88 | We'll explore the [SciPy] library that contains a large number of independent 89 | modules for optimization, linear algebra, integration, interpolation, special 90 | functions, FFT, signal and image processing, ODE solvers and other tasks common 91 | in science and engineering. 92 | 93 | **Keywords**: `linear algebra`, `signal processing`, `analysis`, `integration`, `solvers` 94 | **Prerequisites**: Numerical Computing 95 | **Resources**: [SciPy Lecture Notes](https://scipy-lectures.org/) 96 | 97 |
98 | 99 | 100 | ### [6. Version Control (git)](https://swcarpentry.github.io/git-novice/) 101 | 102 | 103 | 104 | Version control is the lab notebook of the digital world: it’s what 105 | professionals use to keep track of what they’ve done and to collaborate with 106 | other people. Every large software development project relies on it, and most 107 | programmers use it for their small jobs as well. And it isn’t just for 108 | software: books, papers, small data sets, and anything that changes over time 109 | or needs to be shared can and should be stored in a version control system. 110 | 111 | **Keywords**: `git`, `github`, `clone`, `commit`, `push`, `fork` 112 | **Prerequisites**: Installation 113 | **Resources**: [Software Carpentry](https://software-carpentry.org/) 114 | 115 |
116 | 117 | 118 | 119 | ### [7. Vectorization techniques (numpy)](https://www.labri.fr/perso/nrougier/from-python-to-numpy) 120 | 121 | 122 | 123 | The goal of this lesson is to explain some vectorization techniques that 124 | can drastically improve computation, with several orders of magnitude in 125 | some cases. 126 | 127 | **Keywords**: `Code`, `Problem`, `Spatial`, `Temporal` 128 | **Prerequisites**: Numerical Computing 129 | **Resources**: [From Python to Numpy](https://www.labri.fr/perso/nrougier/from-python-to-numpy) 130 | 131 |
132 | 133 | 134 | ### [8. Interface with C (cython and ctypes)](https://scipy-lectures.org/advanced/interfacing_with_c/interfacing_with_c.html) 135 | 136 | 137 | 138 | [Cython] is a static compiler for both the Python programming language and the 139 | extended Cython programming language that eases the writing of C extensions. 140 | [Numba] translates Python functions to optimized machine code at runtime (just in 141 | time) using the industry-standard LLVM compiler library. 142 | 143 | **Keywords**: `Optimization`, `Cython`, `Numba`, `Compiler`, `JIT` 144 | **Prerequisites**: Numerical Computing , Vectorization techniques 145 | **Resources**: [SciPy Lecture Notes](https://scipy-lectures.org/) 146 | 147 |
148 | 149 | 150 | ### Bibliography 151 | * [SciPy 1.0: fundamental algorithms for scientific computing in Python](https://www.nature.com/articles/s41592-019-0686-2), 152 | P.Virtanen, R.Gommers & al., Nature Methods, 2020. 153 | * [Array programming with NumPy](https://www.nature.com/articles/s41586-020-2649-2), 154 | C.R. Harris, K.J. Millman & al., Nature, 2020. 155 | * [How to transform code into scientific contribution](https://www.frontiersin.org/articles/10.3389/fninf.2017.00069/full), 156 | N.P. Rougier & F.Benureau, Frontiers in Neuroinformatics, 2018. 157 | * [Ten simple rules for better figures](https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003833), 158 | N.P. Rougier, M. Droettboom & P. E. Bourne, Plos Computational Biology, 2014. 159 | 160 | ### Copyright notice 161 | 162 | Copyright © 2021 [Nicolas P. Rougier](http://www.labri.fr/perso/nrougier) — 163 | Released under a [CC-BY 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) license. 164 | Banner image copyright © Randall Monroe ([XKCD #353](https://xkcd.com/353/)) — 165 | This course has been written in November 2021 using: 166 | 167 | 168 | 169 | 170 | 171 | [Anaconda]: https://www.anaconda.com/ 172 | [Emacs]: http://www.emacs.org/ 173 | [vim]: https://www.vim.org/ 174 | [Atom]: https://atom.io/ 175 | [Notepad++]: https://notepad-plus-plus.org/ 176 | [IPython]: http://www.ipython.org/ 177 | [Jupyter]: http://www.jupyter.org/ 178 | [NumPy]: http://www.numpy.org/ 179 | [Scipy]: http://www.scipy.org/ 180 | [Matplotlib]: http://www.matplotlib.org/ 181 | [Cython]: https://cython.org/ 182 | [Numba]: https://numba.pydata.org/ 183 | -------------------------------------------------------------------------------- /data/XKCD.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rougier/scipy-crash-course/0e62b6a7ce42c934ce415f784500a59d8cc6534e/data/XKCD.png -------------------------------------------------------------------------------- /data/indent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rougier/scipy-crash-course/0e62b6a7ce42c934ce415f784500a59d8cc6534e/data/indent.png -------------------------------------------------------------------------------- /data/notebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rougier/scipy-crash-course/0e62b6a7ce42c934ce415f784500a59d8cc6534e/data/notebook.png -------------------------------------------------------------------------------- /lessons/01-installation.md: -------------------------------------------------------------------------------- 1 | 2 | ## Installation 3 | 4 | 5 | This lesson aims at providing the student with a clean development environment, 6 | including Python installation and essential packages (using the [Anaconda] 7 | installer), a decent text editor (e.g. [emacs], [vim], [atom], [notepad++]), a 8 | git command line and a shell. We'll also introduce the Python & [IPython] 9 | shells, the [Jupyter] notebook and explains how to run a python 10 | script from the command line or from inside the [IPython] shell. 11 | 12 |
13 | 14 | **Contents** 15 | * [Objectives](#objectives) 16 | * [Installation](#installation) .............................................................................................................................................. 17 | 18 | * [Python, IPython & Jupyter](#python-ipython--jupyter-) .................................................................................................................... 19 | 20 | * [Testing your installation](#testing-your-installation-) ......................................................................................................................... 21 | 22 | 23 | 24 |



25 | 26 | ## Objectives 27 | 28 | The primary goals of this lesson are: 29 | 30 | * To ensure you have a clean Python installation (including [Jupyter]) 31 | * To install a decent text editor on your system 32 | * To type a few Python lines and to run a python script 33 | 34 | ### Convention 35 | 36 | During this introduction, we'll use three different kind of console, namely 37 | `shell` (or powershell), `Python` and `IPython`. To help you distinguish them, 38 | there will be a small colored icon in front of them: 39 | 40 | 41 | 42 | ``` bash 43 | GNU bash, version 3.2.57(1)-release-(x86_64-apple-darwin18) 44 | $ _ 45 | ``` 46 | 47 | 48 | 49 | ``` Pycon 50 | Python 3.7.2 (default, Feb 12 2019, 08:15:36) 51 | [Clang 10.0.0 (clang-1000.11.45.5)] on darwin 52 | Type "help", "copyright", "credits" or "license" for more information. 53 | >>> _ 54 | ``` 55 | 56 | 57 | 58 | ``` IPython 59 | Python 3.7.2 (default, Feb 12 2019, 08:15:36) 60 | Type 'copyright', 'credits' or 'license' for more information 61 | IPython 7.0.1 -- An enhanced Interactive Python. Type '?' for help. 62 | 63 | In [1]: _ 64 | ``` 65 | 66 | In the examples above, `>>>` is the Python prompt and does not need to be 67 | typed. For IPython, the prompt is more likely to be something like 68 | `[12]:`. There is also a second prompt (`...`) meaning the previous line is not 69 | ended and needs to be terminated. This is for example the case when you enter a 70 | parenthese or an unbalanced expression (e.g. number of opening parenthesis is 71 | greater than the number of closing parenthesis). 72 | 73 | If you type a bash command in a Python shell or a Python command in a Bash 74 | shell, the console will report an error. 75 | 76 | > **Note**: to exit a Python shell or a regular shell, you can type `exit()` or 77 | type `Control-D`. 78 | 79 | 80 |

81 | ## Installation 82 | 83 | As of today (2019), Python exists mainly in two flavors: Python 2.x 84 | (deprecated) and Python 3.x. On some systems, the 2.x version is already 85 | installed and for some systems, the 3.x version might be installed as well (or 86 | instead). However, we cannot use any of them because we'll need to install 87 | several packages that might interfere with the system packages. We'll thus have 88 | to install our own version using [Anaconda] by Continuum Analytics which is a 89 | free Python distribution (including for commercial use and redistribution) and 90 | includes more than 400 of the most popular Python packages for science, math, 91 | engineering, and data analysis. 92 | 93 | [Anaconda] is available for several architectures: 94 | 95 | * [Anaconda for windows](https://www.anaconda.com/distribution/#windows) 96 | (Python 3.7 version and the 64-Bit Graphical Installer (614.3 MB)) 97 | * [Anaconda for linux](https://www.anaconda.com/distribution/#linux) 98 | (Python 3.7 version and the 64-Bit (x86) Installer (652.5 MB) 99 | * [Anaconda for OSX](https://www.anaconda.com/distribution/#macos) 100 | (Python 3.7 version and the 64-Bit Graphical Installer (652.7 MB)) 101 | 102 | When asked whether to install Visual Studio, choose yes if you're on Windows. 103 | 104 | Once installation has finished, we'll need to test it. 105 | 106 | > **Note** that If you're using a Windows machine, you'll need to install 107 | > [powershell](https://docs.microsoft.com/en-us/powershell/) that let you 108 | > manage your computer from the command line. 109 | 110 | 111 | You can now open a terminal (or powershell on Windows) and test if you've 112 | access to the `conda` command: 113 | 114 | 115 | 116 | ``` bash 117 | $ conda --version 118 | conda 4.5.12 119 | ``` 120 | 121 | Since the installer might not be up to date (depending on when it was build), 122 | you may need to update your anaconda installation: 123 | 124 | 125 | 126 | ``` bash 127 | $ conda update --all 128 | Collecting package metadata: done 129 | Solving environment: done 130 | 131 | ## Package Plan ## 132 | 133 | ... 134 | 135 | Proceed ([y]/n)? 136 | 137 | ... 138 | 139 | Preparing transaction: done 140 | Verifying transaction: done 141 | Executing transaction: done 142 | 143 | $ conda --version 144 | conda 4.6.4 145 | ``` 146 | 147 | > **Note**: If the `conda` does not work, you'll need to open the Anaconda 148 | > navigator and to update the packages through the interface. The reason why 149 | > the `conda` does not work might be linked to a `PATH` problem. In such case, 150 | > it might be worth to reboot your machine to see if this solves the problem. 151 | 152 | 153 | ### Git, a distributed version control system 154 | 155 | We now need to install Git which is not related to Python and has not been 156 | installed during the previous step. Depending on your system, it might be 157 | already installed but most probably it is not up to date and this is the reason 158 | why we'll install our own version. Download the version for your system and 159 | proceed with installation: 160 | 161 | * [Windows](https://git-scm.com/downloads/win) 162 | * [Linux](https://git-scm.com/download/linux) 163 | * [Mac](https://git-scm.com/download/mac) 164 | 165 | Once installation has finished, you can type: 166 | 167 | 168 | 169 | ``` bash 170 | $ git --version 171 | 2.20.1 172 | ``` 173 | 174 | > **Note**: As for `conda`, this command may not work if your `PATH` has not 175 | > been updated properly. You can try starting a new terminal and/or reboot 176 | > your machine to see if this solves the problem. 177 | 178 | 179 | 180 | ### Code editor 181 | 182 | The last thing we need to install is a decent code editor. You might have one 183 | already installed on your system and if you're faimilar with it, no need to 184 | install another one. Still, you'll need to configure it properly. If you have 185 | no code editor (or if you're not sure you have one), you need to install 186 | one. There is actually a large choice but I will only list here the most 187 | relevant ones: 188 | 189 | * [Atom] 190 | * [Notepad++] 191 | * [Sublime Text] 192 | * [Emacs] (powerful but difficult for a beginner) 193 | * [vim] (powerful but difficult for a beginner) 194 | 195 | Whatever the editor you chose, you will need to configure it to **not** use 196 | tabulations but to insert spaces (e.g. 4) when you press the `tab` key. This is 197 | important because if you don't do it and mix spaces and tabulations, Python 198 | will complain (it is not allowed) and using only tabs is generally a bad 199 | idea. The way to configure this is editor dependent so I'll let you search how 200 | to do it in your preferred editor. 201 | 202 | 203 | 204 |

205 | ## Python, IPython & Jupyter 206 | 207 | You are now ready to start using Python and there are several ways to do that: 208 | 209 | 1. You can start a Python or IPython shell and type some Python commands 210 | 2. You can write a Python script and execute it 211 | 3. You can start the Jupyter notebook and type some Python code in the browser 212 | (and save your code and results in various formats such as PDF or HTML) 213 | 214 | The Python shell can be started using the command `python` or `python3`: 215 | 216 | 217 | 218 | ``` Pycon 219 | $ Python 220 | Python 3.7.2 (default, Feb 12 2019, 08:15:36) 221 | [Clang 10.0.0 (clang-1000.11.45.5)] on darwin 222 | Type "help", "copyright", "credits" or "license" for more information. 223 | >>> _ 224 | ``` 225 | 226 | Once inside the sell, you can start typing command: 227 | 228 | 229 | 230 | ``` Pycon 231 | >>> print("Hello world!") 232 | Hello world! 233 | ``` 234 | 235 | 236 | The IPython shell can be started using the command `ipython` or `ipython3`: 237 | 238 | 239 | 240 | ``` Pycon 241 | $ IPython 242 | Python 3.7.2 (default, Dec 29 2018, 00:00:04) 243 | Type 'copyright', 'credits' or 'license' for more information 244 | IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help. 245 | 246 | In [1]: _ 247 | ``` 248 | 249 | It works pretty much like the default Python shell and you can type commands: 250 | 251 | 252 | 253 | ``` Pycon 254 | In [1]: print("Hello world!") 255 | Hello world! 256 | ``` 257 | 258 | Both shells allow to enter Python commands, but IPython offers a set of 259 | supplementary commands as well as some goodies such as code completion and 260 | interactive figures. If you don't which one to use, choose IPython (you'll 261 | thank me later). 262 | 263 | 264 | Using the shell is fine for short code snippets, but as soon as you will want 265 | to write longer program, you'll need first to write your code in a text editor 266 | and then you will execute your code. Let me show you with a very simple script. 267 | 268 | Open your text editor and write: 269 | 270 | ``` 271 | print("Hello world!") 272 | ``` 273 | 274 | and save the file as `hello.py`. The `.py` is the regular file extension used 275 | for Python programs. You are free to use any exension you like, but using `.py` 276 | is a good idea since the operating system can identify the file as being a 277 | Python script. 278 | 279 | Take note on where you saved your file because you'll need to go to this place 280 | in the shell in order to be able to run it (you can also use the absolute path 281 | to execute it but it is less convenient. 282 | 283 | 284 | 285 | ``` Bash 286 | # Replace the path with the path where you saved your script 287 | $ cd ~/GitHub/scipy-crash-course/examples 288 | $ python hello.py 289 | Hello world! 290 | ``` 291 | 292 | If you run the above command, Python will terminate as soon as your program 293 | has ended. If you want to stay within the Python interpreter, you'll have to use 294 | the `-i` switch (interactive mode) that tells Python to not exit once the program 295 | has finished. 296 | 297 | The IPython shell allows you to run a script through the magic 298 | command `%run` (there are many [other magic commands](https://ipython.org/ipython-doc/3/interactive/magics.html)). 299 | 300 | 301 | 302 | ```IPython 303 | In [1]: %run hello.py 304 | Hello world! 305 | ``` 306 | 307 | Last, but not least, you can use the [Jupyter] notebook that is an open-source 308 | web application that allows you to create and share documents that contain live 309 | code, equations, visualizations and narrative text. It's a very powerful tool 310 | and is used by an increasing number of researcher. 311 | 312 | ![https://blog.jupyter.org/we-analyzed-1-million-jupyter-notebooks-now-you-can-too-guest-post-8116a964b536](data/notebook.png) 313 | 314 | If you want to get started with Jupyter notebook, you better read the 315 | [tutorial](https://jupyter.readthedocs.io/en/latest/running.html) at 316 | jupiter.org or this nice 317 | [tutorial](https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook) 318 | at datacamp. 319 | 320 | 321 | 322 |

323 | ## Testing your installation 324 | 325 | 326 | It's now time to check our installation to see if everything is ok. At this 327 | point, no need yet to understand what you're typing but we need to check if 328 | some important packages are present with the proper version. 329 | 330 | 331 | **Checking for numpy** 332 | 333 | 334 | 335 | ``` pycon 336 | >>> import numpy 337 | >>> print(numpy.__version__) 338 | 1.15.2 339 | >>> numpy.test() # This can last a few seconds 340 | .......................... 341 | ``` 342 | 343 | **Checking for scipy** 344 | 345 | 346 | 347 | ``` pycon 348 | >>> import scipy 349 | >>> print(scipy.__version__) 350 | 1.1.0 351 | >>> scipy.test() # This can last several minutes 352 | ........................... 353 | ``` 354 | 355 | **Checking for matplotlib** 356 | 357 | 358 | 359 | ``` pycon 360 | >>> import matplotlib 361 | >>> print(matplotlib.__version__) 362 | 3.0.0 363 | ``` 364 | 365 | **Checking for cython** 366 | 367 | 368 | 369 | ``` pycon 370 | >>> import cython 371 | >>> print(cython.__version__) 372 | 0.28.2 373 | ``` 374 | 375 | **Checking for numba** 376 | 377 | 378 | 379 | ``` pycon 380 | >>> import numba 381 | >>> print(numba.__version__) 382 | 0.40.0 383 | >>> numba.test() # This can last several minutes 384 | ........................... 385 | ``` 386 | 387 | 388 | For each of these packages, the `x.y.z` version should be equal or greater than 389 | the displayed version. If this is not the case, then maybe you conda 390 | installation is not up to date and needs to be upgraded (go back the 391 | [Installation](#installation) section to see how this can be done. 392 | 393 | 394 |

395 | 396 | ## 397 | 398 | Copyright © 2019 [Nicolas P. Rougier](http://www.labri.fr/perso/nrougier) • 399 | Released under a [CC-BY 4.0 International](https://creativecommons.org/licenses/by/4.0/legalcode) license. 400 | 401 | 402 | 403 | [Anaconda]: https://www.anaconda.com 404 | [Python]: http://www.python.org 405 | [Numpy]: http://www.numpy.org 406 | [Scipy]: http://www.scipy.org 407 | [Matplotlib]: http://matplotlib.org 408 | [IPython]: http://ipython.org 409 | [Jupyter]: http://jupyter.org 410 | [Git]: https://git-scm.com 411 | [Cython]: http://cython.org 412 | [Unicode]: https://en.wikipedia.org/wiki/Unicode 413 | [Emacs]: http://www.emacs.org/ 414 | [vim]: https://www.vim.org/ 415 | [Atom]: https://atom.io/ 416 | [Notepad++]: https://notepad-plus-plus.org/ 417 | [Sublime Text]: https://www.sublimetext.com/ 418 | 419 | -------------------------------------------------------------------------------- /lessons/02-introduction.md: -------------------------------------------------------------------------------- 1 | 2 | ## Introduction 3 | 4 | We introduce here the Python language. Only the bare minimum necessary for 5 | getting started with Numpy and Scipy is addressed here. To learn more about 6 | the language, consider going through the excellent tutorial 7 | https://docs.python.org/tutorial. Dedicated books are also available, such as 8 | http://www.diveintopython.net/. 9 | 10 |
11 | 12 | **Contents** 13 | * [Objectives](#objectives) 14 | * [First steps ](#first-steps-) .............................................................................................................................................. 15 | * [Types & variables]() .................................................................................................................................. 16 | * [Control flow]() ........................................................................................................................................... 17 | * [Functions]() ............................................................................................................................................... 18 | * [Modules]() ................................................................................................................................................. 19 | * [Input / Output]() ........................................................................................................................................ 20 | * [Exceptions]() ............................................................................................................................................. 21 | 22 | 23 |



24 | 25 | ## Objectives 26 | 27 | The primary goals of this lesson are: 28 | 29 | * To introduce Python types & manipulations 30 | * To start programming moderately complex scripts 31 | * To be able to read and write files 32 | 33 | 34 | 35 |

36 | ## First steps 37 | 38 | Now it's time to experience a little bit with Python. Let's start with simple 39 | arithmetic operations because Python can be used as a regular calculator with 40 | standard arithmetic operations (addition, subtraction, multiplication, 41 | division, etc.) 42 | 43 | #### Addition 44 | 45 | ```pycon 46 | >>> 2 + 3 47 | 5 48 | ``` 49 | 50 | #### Subtraction 51 | 52 | ```pycon 53 | >>> 11 - 3 54 | 8 55 | ``` 56 | 57 | #### Multiplication 58 | 59 | ```pycon 60 | >>> 3 * 4 61 | 12 62 | ``` 63 | 64 | #### Division 65 | 66 | ```pycon 67 | >>> 11 / 5 68 | 2.2 69 | ``` 70 | 71 | #### Integer division 72 | 73 | ```pycon 74 | >>> 11 // 5 75 | 2 76 | ``` 77 | 78 | #### Modulo operation 79 | 80 | ```pycon 81 | >>> 11 % 5 82 | 1 83 | ``` 84 | 85 | #### Power 86 | 87 | ```pycon 88 | >>> 2**3 89 | 8 90 | ``` 91 | 92 | Note that you cannot have spaces between digits of a number: 93 | 94 | ```pycon 95 | >>> 1 0 + 2 96 | File "", line 1 97 | 1 0 + 2 98 | ^ 99 | SyntaxError: invalid syntax 100 | ``` 101 | 102 | In such a case, Python complains about a syntax error and points at the 103 | position of the error in the expression (using the `^` character). Why Python 104 | points at the zero and not the space ? Because you could have written `1 + 2` 105 | and the space would have been legal. The interpreter can only find the error 106 | after it discovers the extra digit and consequently points at it when reporting 107 | the error. 108 | 109 | Of course, you can compose any number of operations in order to compute a more 110 | complex operation: 111 | 112 | ```pycon 113 | >>> 11 - (5 * (11//5)) # = 11 % 5 114 | 1 115 | ``` 116 | 117 | 118 | ### Native numeric types 119 | 120 | Python offers natively four main native numeric type, `bool`, `integer`, 121 | `float` and `complex`. But always keep in mind that they are the poor's man 122 | version of their mathematical equivalent (Boolean (𝔹), Integer (ℤ), Real (ℝ) 123 | and Complex (ℂ)): `ìnteger` have limited range, `float` and `complex` have 124 | limited range and precision. 125 | 126 | In the case of `float` and `complex`, this has very important consequences. 127 | 128 | ``` pycon 129 | >>> 0.1 + 0.1 + 0.1 == 0.3 130 | False 131 | ``` 132 | 133 | The reason is that decimal numbers `0.1` and `0.3` cannot be represented 134 | exactly and are only approximated. On most machines, if Python were to print 135 | the actual value of the approximation, it would have to display: 136 | 137 | ```pycon 138 | >>> print("{0:.64f}".format(0.1)) 139 | 0.1000000000000000055511151231257827021181583404541015625000000000 140 | >>> print("{0:.64f}".format(0.3)) 141 | 0.2999999999999999888977697537484345957636833190917968750000000000 142 | ``` 143 | 144 | Consequently, Python (as many other languages) chose to display a rounded value 145 | instead. If you want to know more, have a look at the [Floating Point 146 | Arithmetic: Issues and 147 | Limitations](https://docs.python.org/3/tutorial/floatingpoint.html) chapter in 148 | the official [Python 3 149 | tutorial](https://docs.python.org/3/tutorial/index.html). An immediate and 150 | practical consequence is that what you see in the console is not always what 151 | you get in memory, even if they're reasonably close. If you want to know more 152 | about that, make sur to read [What Every Computer Scientist Should Know About 153 | Floating-Point 154 | Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html), 155 | David Goldberg, Computing Surveys, 1991. 156 | 157 | 158 | The right way to compare float numbers is thus to check if the difference is 159 | below a given threshold: 160 | 161 | ``` pycon 162 | >>> (0.1 + 0.1 + 0.1) - 0.3 < 1e-15 163 | True 164 | ``` 165 | 166 | 167 | For each type, there exist many ways to specify the same number. 168 | 169 | ``` pycon 170 | >>> True # Boolean 171 | >>> 0b1010 # Integer (base 2: binary) 172 | >>> 0o12 # Integer (base 8: octal) 173 | >>> 10 # Integer (base 10: decimal) 174 | >>> 0x0a # Integer (base 16: hexadecimal) 175 | >>> 10.0 # Float 176 | >>> 1e1 # Float (scientic notation) 177 | >>> float('inf') # Float (infinity +∞) 178 | >>> float('nan') # Float (Not A Number: nan) 179 | >>> 10 + 0j # Complex 180 | ``` 181 | 182 | You can also force the type of a quantity by casting it into a different type: 183 | 184 | ```pycon 185 | >>> bool(0) 186 | False 187 | >>> int(0) 188 | 0 189 | >>> float(0) 190 | 0.0 191 | >>> complex(0) 192 | 0j 193 | ``` 194 | 195 | 196 | ### Beyond simple arithmetic 197 | 198 | If you want to use more elaborate functions, you'll need the help of the 199 | [mathematical module](https://docs.python.org/3/library/math.html) for real 200 | numbers and the [complex mathematical 201 | module](https://docs.python.org/3/library/cmath.html) for complex numbers. To 202 | do that, we have to `import` a library and to use its name as a prefix, in 203 | front of the functions we want to use. For those who know Python, you might 204 | have been tempted to write `from math import *` but this is almost always a bad 205 | idea. 206 | 207 | 208 | **Power and logarithmic functions** 209 | 210 | ```pycon 211 | >>> import math 212 | >>> math.log( math.exp( 1.234 ) ) 213 | 1.234 214 | ``` 215 | 216 | **Trigonometric functions** 217 | 218 | ```pycon 219 | >>> import math 220 | >>> math.asin( math.sin( 1.234 ) ) 221 | 1.234 222 | ``` 223 | 224 | **Hyperbolic functions** 225 | 226 | ```pycon 227 | >>> import math 228 | >>> math.asinh( math.sinh( 1.234 ) ) 229 | 1.234 230 | ``` 231 | 232 | **Special functions** 233 | 234 | ```pycon 235 | >>> import math 236 | >>> math.gamma( 2.0 ) 237 | 1.0 238 | ``` 239 | 240 | **Constants** 241 | 242 | ```pycon 243 | >>> import math 244 | >>> math.pi 245 | 3.141592653589793 246 | >>> math.e 247 | 2.718281828459045 248 | >>> math.nan # Not A Number 249 | nan 250 | >>> math.inf # Infinite 251 | inf 252 | ``` 253 | 254 | 255 | ### Logical operations 256 | 257 | Logic is an important part of Python because this allows to manipulate and 258 | compare quantities, including numbers, and we'll see later that it works for 259 | all kind of objects. 260 | 261 | ```pycon 262 | >>> True and True # Logical and 263 | >>> 42 or 57 # Logical or 264 | >>> 1 == 2-1 # Equality test 265 | >>> 1 != 2 # Inequality test 266 | >>> 1 is 2-1 # Identity test 267 | >>> not 24 # Negation 268 | ``` 269 | 270 | Note that the `is` keyword really means identity (the two terms point to the 271 | same object), it is not a test for equality. 272 | 273 | ```pycon 274 | >>> 1 is 1.0 275 | False 276 | >>> True is 1 277 | False 278 | >>> True and 1 279 | True 280 | ``` 281 | 282 | ### Bitwise operations 283 | 284 | Bitwise operations are logical operations that operate a the bit level. They 285 | might be useful in some situations but we won't use them much in this course. 286 | 287 | ```pycon 288 | >>> 1 | 2 # bitwise or 289 | >>> 1 & 2 # bitwise and 290 | >>> 1 ^ 2 # bitwise xor 291 | >>> 8 << 2 # bitwise left shift 292 | >>> 8 >> 2 # bitwise right shift 293 | >>> ~8 # bitwise negation 294 | ``` 295 | 296 | 297 | 298 |

299 | ## Exercises 300 | 301 | Before moving to the [next lesson](02-introduction.md), here are some simple 302 | exercises that should take you only a few minutes to solve. If you want the 303 | solution, just type these expression in a Python console. 304 | 305 | 306 | ### Find the type of the following expressions 307 | 308 | ``` 309 | .0 310 | -1 311 | 1, 312 | 'float(4) + 5' 313 | 1e2 314 | 1j 315 | math.nan 316 | ``` 317 | 318 | ### Are these legal Python expressions? 319 | 320 | ``` 321 | 1 + 1 == 2 322 | 1 = 2 323 | 1 + 1i 324 | 1 <- 2 325 | 0.+.0 326 | 3***3 327 | 3 <<2>> 3 328 | ``` 329 | 330 | ### Find the result of the following expressions 331 | 332 | ``` 333 | 1.+.1 334 | 0b1+0xb1 335 | (1,)*3 336 | 1e1000 - 1e1000 337 | 'abc'*3 338 | 3 or 10 339 | 3 <2 > 3 340 | ``` 341 | 342 | 343 |
344 | 345 |

346 | 347 | ## Basic types 348 | 349 | 350 | 351 | 352 | Beside being a convenient calculator, Python is also (and mostly) a powerful 353 | programming language with an elegant and intuitive syntax. Furthermore, you 354 | have to know that Python is an interpreted langage, meaning each time you enter 355 | a set of instructions, they need to be intepreted by the Python interpreter. This 356 | can make Python quite slow in some situation but we'll later how to overcome most 357 | of Python slowness. 358 | 359 | ### Variables 360 | 361 | Until now, we have been playing in the console, throwing some expressions in 362 | the interpreted and checked the result. Problem is that those expression cannot 363 | be re-used. It's thus time to save us some trouble and assign those expressions 364 | to variables. This can be done quite naturally. 365 | 366 | ``` python 367 | >>> width = 1 368 | >>> height = 2 369 | ``` 370 | 371 | What is really cool though is that you can assign several variables at once: 372 | 373 | ``` python 374 | >>> width, height = 2,1 375 | >>> width 376 | 1 377 | >>> height 378 | 2 379 | ``` 380 | 381 | However, you cannot refer a new variable on the same line 382 | 383 | ``` python 384 | >>> width, height = 2, 2*width 385 | Traceback (most recent call last): 386 | File "", line 1, in 387 | NameError: name 'width' is not defined 388 | ``` 389 | 390 | In this case, you have to split the expression in two distinct lines. 391 | 392 | ``` python 393 | >>> width = 2 394 | >>> height = 2*width 395 | ``` 396 | 397 | Variables can be manipulated just as any expression but they need to have been 398 | defined previously. 399 | 400 | ``` python 401 | >>> a = 2*b 402 | Traceback (most recent call last): 403 | File "", line 1, in 404 | NameError: name 'b' is not defined 405 | ``` 406 | 407 | In interactive mode, that is, the console mode we've been using from the start, 408 | there is a special variable whose name is '_' and that contains the last 409 | **printed** expression. 410 | 411 | ``` python 412 | >>> very_long_name = 10 413 | >>> very_long_name 414 | 10 415 | >>> b = 2 + _ # here, _ = very_long_name 416 | >>> b 417 | 12 418 | ``` 419 | 420 | Don't assign explicitely a value to the `_` variable or you'll kill the magic, 421 | and you don't want to do that, do you ? 422 | 423 | 424 | 425 | ### Containers 426 | 427 | Beside the numeric types, Python also offers native container type (also known 428 | as collections), one is dedicated to the storing of ordered sequence of 429 | characters (i.e. strings) while some others allows to store just anything and 430 | offers different properties. In a nutshell: 431 | 432 | ``` python 433 | >>> "1,2,3,4" # String (ordered, character only, immutable, indexable) 434 | >>> (1,2,3,4) # Tuple (ordered, immutable, indexable) 435 | >>> [1,2,3,4] # List (ordered, mutable, indexable) 436 | >>> {1,2,3,4} # Set (unordered, mutable, unique elements) 437 | >>> {1:2,3:4} # Dictionnary (unordered, mutable, hashable) 438 | ``` 439 | 440 | **Strings** 441 | 442 | Strings are expressed by enclosing a text using pairs of " or \' 443 | characters. Depending on the character you chose, you can use the other inside 444 | the string. 445 | 446 | ``` python 447 | >>> "Hello 'world!'" 448 | "Hello 'world!'" 449 | >>> 'Hello "world"!' 450 | 'Hello "world!"' 451 | >>> "" # empty string 452 | '' 453 | ``` 454 | 455 | Note that you can split a string using spaces and Python will concatenate all 456 | the pieces together. 457 | 458 | ``` python 459 | >>> "Hello" " " "world!" 460 | 'Hello world!' 461 | ``` 462 | 463 | 464 | But you can also explicitely concatenate the different pieces together. 465 | 466 | ``` python 467 | >>> "Hello" + " " + "world!" 468 | 'Hello world!' 469 | ``` 470 | 471 | For multiline strings, you need to triple the enclosing quotes or to use parentheses. 472 | 473 | ``` python 474 | >>> """Hello 475 | ... world!""" 476 | 'Hello\nworld!' 477 | 478 | >>> '''Hello 479 | ... world!''' 480 | 'Hello\nworld!' 481 | 482 | >>>("Hello" 483 | ... " world!") 484 | 'Hello world!' 485 | ``` 486 | 487 | In the output above, you can seen the "\n" character has been added, it 488 | expresses the newline character. There are several backslashed characters: 489 | 490 | Escape Sequence | Meaning 491 | ----------------|--------------------------- 492 | \\\\ | Backslash (\) 493 | \\\' | Single quote (') 494 | \\\" | Double quote (") 495 | \a | ASCII Bell (BEL) 496 | \b | ASCII Backspace (BS) 497 | \n | ASCII Linefeed (LF) 498 | \r | ASCII Carriage Return (CR) 499 | \t | ASCII Horizontal Tab (TAB) 500 | \v | ASCII Vertical Tab (TAB) 501 | 502 | This means the '\n' will be interpreted as a new line character, but what if we 503 | want to really have '\n' in our string as in 'C:\\some\\name'? Either we 504 | "escape" all the backslash or we prefix the string with `r` meaning special 505 | characters won't be interpeted. 506 | 507 | ``` python 508 | >>> print('C:\some\name') 509 | 'C:\some 510 | ame' 511 | >>> print('C:\\some\\name') 512 | C:\some\name 513 | >>> print(r'C:\some\name') 514 | C:\some\name 515 | ``` 516 | 517 | Strings in Python 3 are encoded using UTF-8 ([Unicode]), meaning you can encode 518 | pretty much any glyphs fom any languages (and emojis as well). 519 | 520 | ``` python 521 | >>> "ℕ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ" 522 | 'ℕ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ' 523 | ``` 524 | 525 | **Tuples** 526 | 527 | Tuples are immutable containers, meaning they cannot be changed after they've 528 | been created. They allow to store pretty much anything, including other tuples. 529 | To create a tuple, you simply write a comma-separated list of values, 530 | optionally enclosed by parentheses. 531 | 532 | ``` python 533 | >>> 1,2,3 534 | (1, 2, 3) 535 | >>> 1, "2", (1,2) 536 | (1, '2', (1, 2)) 537 | >>> () # empty tuple 538 | () 539 | ``` 540 | 541 | **Lists** 542 | 543 | Lists are mutable containers quite similar to tuple, but they can be modified 544 | after creation. They allow to store pretty much anything. To create a 545 | list, you need to write a comma-separated list of values enclosed by square 546 | brackets. 547 | 548 | ``` python 549 | >>> [1,2,3] 550 | [1, 2, 3] 551 | 552 | >>> [1, "2", (1,2)] 553 | [1, '2', (1, 2)] 554 | 555 | >>> [] # empty list 556 | [] 557 | ``` 558 | 559 | **Sets** 560 | 561 | Sets are mutable containers (they can be modified) and contains only unique 562 | elements, i.e. they prevent to have duplicated elements. 563 | 564 | ``` python 565 | >>> {1, 2, 2} 566 | {1, 2} 567 | 568 | >>> {1, 2, "2"} 569 | {1, 2, '2'} 570 | ``` 571 | 572 | **Dictionnary** 573 | 574 | Dictionnary can be considered as a kind of associative memory where items are 575 | indexed by a key (instead of integer). The type of the key can be pretty much 576 | anything. 577 | 578 | ``` python 579 | >>> { "item 1" : 1, "item 2" : 2} 580 | {'item 2': 2, 'item 1': 1} 581 | >>> { 1 : 2, 3 : 4} 582 | {1: 2, 3: 4} 583 | ``` 584 | 585 | 586 | ### Indexing and slicing 587 | 588 | Individual items of a list, tuple and strings can be accessed invidually using 589 | their position as index. Note that first element has index 0 590 | 591 | ``` python 592 | >>> d = [1,2,3,4,5] 593 | >>> d[0] 594 | 1 595 | ``` 596 | 597 | This also work using negative indices, meaning the position has to be taken 598 | from the end. Note that last element has index -1. 599 | 600 | ``` python 601 | >>> s = "Hello world!" 602 | >>> s[-1] 603 | '!' 604 | ``` 605 | 606 | Furthermore, we can also access a **range** of items using the slice notation 607 | `start:end`. Note that both start and end are optional. 608 | 609 | ``` python 610 | >>> d = [1,2,3,4,5] 611 | >>> d[1:3] 612 | [2, 3] 613 | ``` 614 | 615 | If start is missing, Python will implicitly replace it by the start of the 616 | list. If end is missing, Python will implicitly replace it by the end of the 617 | list. 618 | 619 | 620 | ``` python 621 | >>> d = [1,2,3,4,5] 622 | 623 | >>> d[1:] 624 | [2, 3, 4, 5] 625 | 626 | >>> d[:2] 627 | [1, 2] 628 | 629 | >>> d[:] 630 | [1, 2, 3, 4, 5] 631 | ``` 632 | 633 | We can further refine our slice by giving the step between elements. The new 634 | syntax is thus `start:end:step`. 635 | 636 | ``` python 637 | >>> d = [1,2,3,4,5,6] 638 | >>> d[0:5:2] 639 | [1, 3, 5] 640 | 641 | # Can be abbreviated into 642 | >>> d[::2] # 643 | [1, 3, 5] 644 | ``` 645 | 646 | What if we use a negative step? We get the reversed sequence. 647 | 648 | ``` python 649 | >>> d = [1,2,3,4,5,6] 650 | >>> d[::-1] 651 | [6, 5, 4, 3, 2, 1] 652 | ``` 653 | 654 | Because strings are indexable, indexing and slicing work just the same. 655 | 656 | 657 | ``` python 658 | >>> s = "Hello world!" 659 | >>> s[6:-1] 660 | " world" 661 | >>> s[6:] 662 | " world!" 663 | ``` 664 | 665 | 666 | ### Adding and removing 667 | 668 | Adding an element to a mutable container can be done in two distinct 669 | ways. Either by creating a new container that is the container plus the new 670 | item, or by inserting the new item into the container, hence modyfying it. 671 | 672 | ``` python 673 | >>> l1 = [1, 2, 3] 674 | >>> l2 = l1 + [4] 675 | >>> l2 676 | [1, 2, 3, 4] 677 | >>> l1.append(4) 678 | >>> l1 679 | [1, 2, 3, 4] 680 | ``` 681 | 682 | For removing items, we need to use the **del** keyword and give indices where 683 | to delete items. 684 | 685 | ``` python 686 | >>> l1 = [1, 2, 3, 4, 5, 6] 687 | >>> del l1[0 ] 688 | >>> l1 689 | [2, 3, 4, 5, 6] 690 | ``` 691 | 692 | But we can also delete a range of indices at once. 693 | 694 | ``` python 695 | >>> l1 = [1, 2, 3, 4, 5, 6] 696 | >>> del l1[::2] 697 | >>> l1 698 | [2,4,6] 699 | ``` 700 | 701 | Something you will discover soon enough (or maybe you've already discovered it) 702 | is that Python is rather nitpicking about indentation. 703 | 704 | ``` python 705 | >>> a = 1 706 | >>> a = 1 707 | File "", line 1 708 | a = 1 709 | ^ 710 | IndentationError: unexpected indent 711 | ``` 712 | 713 | The reason is that indentation has a semantic meaning but we'll see that later. 714 | 715 | 716 | 717 | 718 | ### Exercises 719 | 720 | 721 | 722 | 723 | ### Find the result of the following expressions 724 | 725 | ``` 726 | 1.+1, 727 | 1,+1. 728 | (1,)*3 729 | 1e1000 - 1e1000 730 | 'abc'*3 731 | 3 or 10 732 | 3 <2> 3 733 | ``` 734 |
735 | Click to see solution 736 |

737 | 738 | ``` 739 | 1.+1, # (2.0,) 740 | 1,+1. # (1, 1.0) 741 | (1,)*3 # (1, 1, 1) 742 | 1e1000 - 1e1000 # nan 743 | 'abc'*3 # 'abcabcabc' 744 | 3 or 10 # 3 745 | 3 <2> 3 # False 746 | ``` 747 | 748 | 749 |
750 | 751 | ### How to... 752 | 753 |
754 | ... build the empty set? 755 |

756 | 757 | ```Python 758 | empty = {} # Wrong: this builds an empty dictionnary 759 | empty = set() # Right 760 | ``` 761 |

762 |
763 | 764 | 765 |
766 | ... get the list of unique letters composing "abracadabra"? 767 |

768 | 769 | ```Python 770 | letters = set("abracadabra") 771 | ``` 772 |

773 | 774 | 775 |
776 | ... build a tuple of two empty lists? 777 |

778 | 779 | ```Python 780 | a = ([], []) # Right but parenthesis are not necessary 781 | a = [], [] # Right 782 | ``` 783 |

784 | 785 | 786 |
787 | ... generate a list of all even numbers between 20 and 40 (included)? 788 |

789 | 790 | ```Python 791 | numbers = list(range(20, 41, 2) 792 | ``` 793 |

794 | 795 |
796 | ... check if a word is a palindrom? 797 |

798 | 799 | ```Python 800 | word = "kayak" 801 | print(word == word[::-1]) # Note that this does not work with "Kayak" 802 | 803 | word = "Kayak".lower() 804 | print(word == word[::-1]) # This works thanks to the lower method 805 | ``` 806 |

807 | 808 |
809 | ... transform the string "1.2" into a float? 810 |

811 | 812 | ```Python 813 | a = float("1.2) 814 | ``` 815 |

816 | 817 |
818 | ... count the number of unique elements in a list? 819 |

820 | 821 | ```Python 822 | mylist = [1,2,3,4,3,2,1] 823 | size = len(set(mylist)) 824 | ``` 825 |

826 | 827 |
828 | ... print the string `"Isn't it, he said"` (including quotes)? 829 |

830 | 831 | ```Python 832 | print('''"Isn't it, he said"''') 833 | ``` 834 |

835 | 836 |
837 | ... swap the content of two variables? 838 |

839 | 840 | ```Python 841 | a,b = 1,2 842 | a,b = b,a 843 | ``` 844 |

845 | 846 | 847 |

848 | ## Bibliography 849 | 850 | 851 | Here are a set of resources for those who want to go further in their knowledge 852 | of Python. 853 | 854 | * [**The (official) Python tutorial**](https://docs.python.org/3/tutorial/index.html) 855 | does not attempt to be comprehensive and cover every single feature, or even 856 | every commonly used feature. Instead, it introduces many of Python's most 857 | noteworthy features, and will give you a good idea of the language's flavor 858 | and style. 859 | 860 | * [**Dive into python**](http://www.diveintopython3.net) is a teach-by-example 861 | guide to the paradigms of programming in Python and modern software 862 | development techniques. It assumes some preexisting knowledge of programming, 863 | although not necessarily in Python. 864 | 865 | 866 |

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