├── .gitignore
├── Lecture-0-Scientific-Computing-with-Python.ipynb
├── Lecture-1-Introduction-to-Python-Programming.ipynb
├── Lecture-2-Numpy.ipynb
├── Lecture-3-Scipy.ipynb
├── Lecture-4-Matplotlib.ipynb
├── Lecture-5-Sympy.ipynb
├── Lecture-6A-Fortran-and-C.ipynb
├── Lecture-6B-HPC.ipynb
├── Lecture-7-Revision-Control-Software.ipynb
├── Makefile
├── README.md
├── Scientific-Computing-with-Python.pdf
├── Scientific-Computing-with-Python.tex
├── chapter.tplx
├── images
├── github-diff.png
├── github-project-page.png
├── gitk.png
├── ipython-notebook-screenshot.jpg
├── ipython-screenshot.jpg
├── optimizing-what-2.png
├── optimizing-what.png
├── python-screenshot.jpg
├── scientific-python-stack.png
├── scientific-python-stack.svg
├── spyder-screenshot.jpg
├── theory-experiment-computation.png
└── theory-experiment-computation.svg
├── scripts
├── hello-world-in-swedish.py
└── hello-world.py
└── stockholm_td_adj.dat
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 |
3 | # C extensions
4 | *.so
5 |
6 | # Packages
7 | *.egg
8 | *.egg-info
9 | dist
10 | build
11 | eggs
12 | parts
13 | bin
14 | var
15 | sdist
16 | develop-eggs
17 | .installed.cfg
18 | lib
19 | lib64
20 |
21 | # Installer logs
22 | pip-log.txt
23 |
24 | # Unit test / coverage reports
25 | .coverage
26 | .tox
27 | nosetests.xml
28 |
29 | # Translations
30 | *.mo
31 |
32 | # Mr Developer
33 | .mr.developer.cfg
34 | .project
35 | .pydevproject
36 |
--------------------------------------------------------------------------------
/Lecture-0-Scientific-Computing-with-Python.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "raw",
5 | "metadata": {},
6 | "source": [
7 | "# Introduction to scientific computing with Python"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "J.R. Johansson (jrjohansson at gmail.com)\n",
15 | "\n",
16 | "The latest version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures).\n",
17 | "\n",
18 | "The other notebooks in this lecture series are indexed at [http://jrjohansson.github.io](http://jrjohansson.github.io)."
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "metadata": {},
24 | "source": [
25 | "## The role of computing in science"
26 | ]
27 | },
28 | {
29 | "cell_type": "markdown",
30 | "metadata": {},
31 | "source": [
32 | "Science has traditionally been divided into experimental and theoretical disciplines, but during the last several decades computing has emerged as a very important part of science. Scientific computing is often closely related to theory, but it also has many characteristics in common with experimental work. It is therefore often viewed as a new third branch of science. In most fields of science, computational work is an important complement to both experiments and theory, and nowadays a vast majority of both experimental and theoretical papers involve some numerical calculations, simulations or computer modeling.\n",
33 | "
\n",
34 | " \n",
35 | " \n",
36 | "\n",
37 | "In experimental and theoretical sciences there are well established codes of conducts for how results and methods are published and made available to other scientists. For example, in theoretical sciences, derivations, proofs and other results are published in full detail, or made available upon request. Likewise, in experimental sciences, the methods used and the results are published, and all experimental data should be available upon request. It is considered unscientific to withhold crucial details in a theoretical proof or experimental method, that would hinder other scientists from replicating and reproducing the results.\n",
38 | "\n",
39 | "In computational sciences there are not yet any well established guidelines for how source code and generated data should be handled. For example, it is relatively rare that source code used in simulations for published papers are provided to readers, in contrast to the open nature of experimental and theoretical work. And it is not uncommon that source code for simulation software is withheld and considered a competitive advantage (or unnecessary to publish). \n",
40 | "\n",
41 | "However, this issue has recently started to attract increasing attention, and a number of editorials in high-profile journals have called for increased openness in computational sciences. Some prestigious journals, including Science, have even started to demand of authors to provide the source code for simulation software used in publications to readers upon request. \n",
42 | "\n",
43 | "Discussions are also ongoing on how to facilitate distribution of scientific software, for example as supplementary materials to scientific papers."
44 | ]
45 | },
46 | {
47 | "cell_type": "markdown",
48 | "metadata": {},
49 | "source": [
50 | "### References"
51 | ]
52 | },
53 | {
54 | "cell_type": "markdown",
55 | "metadata": {},
56 | "source": [
57 | " * [Reproducible Research in Computational Science](http://dx.doi.org/10.1126/science.1213847), Roger D. Peng, Science 334, 1226 (2011).\n",
58 | "\n",
59 | " * [Shining Light into Black Boxes](http://dx.doi.org/10.1126/science.1218263), A. Morin et al., Science 336, 159-160 (2012).\n",
60 | " \n",
61 | " * [The case for open computer programs](http://dx.doi.org/doi:10.1038/nature10836), D.C. Ince, Nature 482, 485 (2012)."
62 | ]
63 | },
64 | {
65 | "cell_type": "markdown",
66 | "metadata": {},
67 | "source": [
68 | "## Requirements on scientific computing"
69 | ]
70 | },
71 | {
72 | "cell_type": "markdown",
73 | "metadata": {},
74 | "source": [
75 | "**Replication** and **reproducibility** are two of the cornerstones in the scientific method. With respect to numerical work, complying with these concepts have the following practical implications:\n",
76 | "\n",
77 | "* Replication: An author of a scientific paper that involves numerical calculations should be able to rerun the simulations and replicate the results upon request. Other scientist should also be able to perform the same calculations and obtain the same results, given the information about the methods used in a publication.\n",
78 | "\n",
79 | "* Reproducibility: The results obtained from numerical simulations should be reproducible with an independent implementation of the method, or using a different method altogether. \n",
80 | "\n",
81 | "\n",
82 | "In summary: A sound scientific result should be reproducible, and a sound scientific study should be replicable.\n",
83 | "\n",
84 | "\n",
85 | "To achieve these goals, we need to:\n",
86 | "\n",
87 | "* Keep and take note of *exactly* which source code and version that was used to produce data and figures in published papers.\n",
88 | "\n",
89 | "* Record information of which version of external software that was used. Keep access to the environment that was used.\n",
90 | "\n",
91 | "* Make sure that old codes and notes are backed up and kept for future reference. \n",
92 | "\n",
93 | "* Be ready to give additional information about the methods used, and perhaps also the simulation codes, to an interested reader who requests it (even years after the paper was published!).\n",
94 | "\n",
95 | "* Ideally codes should be published online, to make it easier for other scientists interested in the codes to access it."
96 | ]
97 | },
98 | {
99 | "cell_type": "markdown",
100 | "metadata": {},
101 | "source": [
102 | "### Tools for managing source code"
103 | ]
104 | },
105 | {
106 | "cell_type": "markdown",
107 | "metadata": {},
108 | "source": [
109 | "Ensuring replicability and reproducibility of scientific simulations is a *complicated problem*, but there are good tools to help with this:\n",
110 | "\n",
111 | "* Revision Control System (RCS) software. \n",
112 | " * Good choices include:\n",
113 | " * git - http://git-scm.com\n",
114 | " * mercurial - http://mercurial.selenic.com. Also known as `hg`.\n",
115 | " * subversion - http://subversion.apache.org. Also known as `svn`.\n",
116 | "\n",
117 | "* Online repositories for source code. Available as both private and public repositories. \n",
118 | " * Some good alternatives are\n",
119 | " * Github - http://www.github.com\n",
120 | " * Bitbucket - http://www.bitbucket.com\n",
121 | " * Privately hosted repositories on the university's or department's servers.\n",
122 | "\n",
123 | "#### Note\n",
124 | "\t\n",
125 | "Repositories are also excellent for version controlling manuscripts, figures, thesis files, data files, lab logs, etc. Basically for any digital content that must be preserved and is frequently updated. Again, both public and private repositories are readily available. They are also excellent collaboration tools!"
126 | ]
127 | },
128 | {
129 | "cell_type": "markdown",
130 | "metadata": {},
131 | "source": [
132 | "## What is Python?"
133 | ]
134 | },
135 | {
136 | "cell_type": "markdown",
137 | "metadata": {},
138 | "source": [
139 | "[Python](http://www.python.org/) is a modern, general-purpose, object-oriented, high-level programming language.\n",
140 | "\n",
141 | "General characteristics of Python:\n",
142 | "\n",
143 | "* **clean and simple language:** Easy-to-read and intuitive code, easy-to-learn minimalistic syntax, maintainability scales well with size of projects.\n",
144 | "* **expressive language:** Fewer lines of code, fewer bugs, easier to maintain.\n",
145 | "\n",
146 | "Technical details:\n",
147 | "\n",
148 | "* **dynamically typed:** No need to define the type of variables, function arguments or return types.\n",
149 | "* **automatic memory management:** No need to explicitly allocate and deallocate memory for variables and data arrays. No memory leak bugs. \n",
150 | "* **interpreted:** No need to compile the code. The Python interpreter reads and executes the python code directly.\n",
151 | "\n",
152 | "Advantages:\n",
153 | "\n",
154 | "* The main advantage is ease of programming, minimizing the time required to develop, debug and maintain the code.\n",
155 | "* Well designed language that encourage many good programming practices:\n",
156 | " * Modular and object-oriented programming, good system for packaging and re-use of code. This often results in more transparent, maintainable and bug-free code.\n",
157 | " * Documentation tightly integrated with the code.\n",
158 | "* A large standard library, and a large collection of add-on packages.\n",
159 | "\n",
160 | "Disadvantages:\n",
161 | "\n",
162 | "* Since Python is an interpreted and dynamically typed programming language, the execution of python code can be slow compared to compiled statically typed programming languages, such as C and Fortran. \n",
163 | "* Somewhat decentralized, with different environment, packages and documentation spread out at different places. Can make it harder to get started."
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "metadata": {},
169 | "source": [
170 | "## What makes python suitable for scientific computing?"
171 | ]
172 | },
173 | {
174 | "cell_type": "markdown",
175 | "metadata": {},
176 | "source": [
177 | " \n",
178 | "\n",
179 | "* Python has a strong position in scientific computing: \n",
180 | " * Large community of users, easy to find help and documentation.\n",
181 | "\n",
182 | "* Extensive ecosystem of scientific libraries and environments\n",
183 | " * numpy: http://numpy.scipy.org - Numerical Python\n",
184 | " * scipy: http://www.scipy.org - Scientific Python\n",
185 | " * matplotlib: http://www.matplotlib.org - graphics library\n",
186 | "\n",
187 | "* Great performance due to close integration with time-tested and highly optimized codes written in C and Fortran:\n",
188 | " * blas, atlas blas, lapack, arpack, Intel MKL, ...\n",
189 | "\n",
190 | "* Good support for \n",
191 | " * Parallel processing with processes and threads\n",
192 | " * Interprocess communication (MPI)\n",
193 | " * GPU computing (OpenCL and CUDA)\n",
194 | "\n",
195 | "* Readily available and suitable for use on high-performance computing clusters. \n",
196 | "\n",
197 | "* No license costs, no unnecessary use of research budget.\n"
198 | ]
199 | },
200 | {
201 | "cell_type": "markdown",
202 | "metadata": {},
203 | "source": [
204 | "### The scientific python software stack"
205 | ]
206 | },
207 | {
208 | "cell_type": "raw",
209 | "metadata": {},
210 | "source": [
211 | "\n",
212 | " "
213 | ]
214 | },
215 | {
216 | "cell_type": "markdown",
217 | "metadata": {},
218 | "source": [
219 | "### Python environments"
220 | ]
221 | },
222 | {
223 | "cell_type": "markdown",
224 | "metadata": {},
225 | "source": [
226 | "Python is not only a programming language, but often also refers to the standard implementation of the interpreter (technically referred to as [CPython](http://en.wikipedia.org/wiki/CPython)) that actually runs the python code on a computer.\n",
227 | "\n",
228 | "There are also many different environments through which the python interpreter can be used. Each environment has different advantages and is suitable for different workflows. One strength of python is that it is versatile and can be used in complementary ways, but it can be confusing for beginners so we will start with a brief survey of python environments that are useful for scientific computing."
229 | ]
230 | },
231 | {
232 | "cell_type": "markdown",
233 | "metadata": {},
234 | "source": [
235 | "### Python interpreter"
236 | ]
237 | },
238 | {
239 | "cell_type": "markdown",
240 | "metadata": {},
241 | "source": [
242 | "The standard way to use the Python programming language is to use the Python interpreter to run python code. The python interpreter is a program that reads and execute the python code in files passed to it as arguments. At the command prompt, the command ``python`` is used to invoke the Python interpreter.\n",
243 | "\n",
244 | "For example, to run a file ``my-program.py`` that contains python code from the command prompt, use::\n",
245 | "\n",
246 | " $ python my-program.py\n",
247 | "\n",
248 | "We can also start the interpreter by simply typing ``python`` at the command line, and interactively type python code into the interpreter. \n",
249 | "\n",
250 | "\n",
251 | " \n",
252 | "\n",
253 | "\n",
254 | "This is often how we want to work when developing scientific applications, or when doing small calculations. But the standard python interpreter is not very convenient for this kind of work, due to a number of limitations."
255 | ]
256 | },
257 | {
258 | "cell_type": "markdown",
259 | "metadata": {},
260 | "source": [
261 | "### IPython"
262 | ]
263 | },
264 | {
265 | "cell_type": "markdown",
266 | "metadata": {},
267 | "source": [
268 | "IPython is an interactive shell that addresses the limitation of the standard python interpreter, and it is a work-horse for scientific use of python. It provides an interactive prompt to the python interpreter with a greatly improved user-friendliness.\n",
269 | "\n",
270 | "\n",
271 | " \n",
272 | "\n",
273 | "Some of the many useful features of IPython includes:\n",
274 | "\n",
275 | "* Command history, which can be browsed with the up and down arrows on the keyboard.\n",
276 | "* Tab auto-completion.\n",
277 | "* In-line editing of code.\n",
278 | "* Object introspection, and automatic extract of documentation strings from python objects like classes and functions.\n",
279 | "* Good interaction with operating system shell.\n",
280 | "* Support for multiple parallel back-end processes, that can run on computing clusters or cloud services like Amazon EC2.\n"
281 | ]
282 | },
283 | {
284 | "cell_type": "markdown",
285 | "metadata": {},
286 | "source": [
287 | "### IPython notebook"
288 | ]
289 | },
290 | {
291 | "cell_type": "markdown",
292 | "metadata": {},
293 | "source": [
294 | "[IPython notebook](http://ipython.org/notebook.html) is an HTML-based notebook environment for Python, similar to Mathematica or Maple. It is based on the IPython shell, but provides a cell-based environment with great interactivity, where calculations can be organized and documented in a structured way.\n",
295 | "\n",
296 | "\n",
297 | " \n",
298 | "\n",
299 | "Although using a web browser as graphical interface, IPython notebooks are usually run locally, from the same computer that run the browser. To start a new IPython notebook session, run the following command:\n",
300 | "\n",
301 | " $ ipython notebook\n",
302 | "\n",
303 | "from a directory where you want the notebooks to be stored. This will open a new browser window (or a new tab in an existing window) with an index page where existing notebooks are shown and from which new notebooks can be created."
304 | ]
305 | },
306 | {
307 | "cell_type": "markdown",
308 | "metadata": {},
309 | "source": [
310 | "### Spyder"
311 | ]
312 | },
313 | {
314 | "cell_type": "markdown",
315 | "metadata": {},
316 | "source": [
317 | "[Spyder](http://code.google.com/p/spyderlib/) is a MATLAB-like IDE for scientific computing with python. It has the many advantages of a traditional IDE environment, for example that everything from code editing, execution and debugging is carried out in a single environment, and work on different calculations can be organized as projects in the IDE environment.\n",
318 | "\n",
319 | "\n",
320 | " \n",
321 | "\n",
322 | "Some advantages of Spyder:\n",
323 | "\n",
324 | "* Powerful code editor, with syntax high-lighting, dynamic code introspection and integration with the python debugger.\n",
325 | "* Variable explorer, IPython command prompt.\n",
326 | "* Integrated documentation and help."
327 | ]
328 | },
329 | {
330 | "cell_type": "markdown",
331 | "metadata": {},
332 | "source": [
333 | "## Versions of Python"
334 | ]
335 | },
336 | {
337 | "cell_type": "markdown",
338 | "metadata": {},
339 | "source": [
340 | "There are currently two versions of python: Python 2 and Python 3. Python 3 will eventually supersede Python 2, but it is not backward-compatible with Python 2. A lot of existing python code and packages has been written for Python 2, and it is still the most wide-spread version. For these lectures either version will be fine, but it is probably easier to stick with Python 2 for now, because it is more readily available via prebuilt packages and binary installers.\n",
341 | "\n",
342 | "To see which version of Python you have, run\n",
343 | " \n",
344 | " $ python --version\n",
345 | " Python 2.7.3\n",
346 | " $ python3.2 --version\n",
347 | " Python 3.2.3\n",
348 | "\n",
349 | "Several versions of Python can be installed in parallel, as shown above.\n"
350 | ]
351 | },
352 | {
353 | "cell_type": "markdown",
354 | "metadata": {},
355 | "source": [
356 | "## Installation"
357 | ]
358 | },
359 | {
360 | "cell_type": "markdown",
361 | "metadata": {},
362 | "source": [
363 | "### Conda"
364 | ]
365 | },
366 | {
367 | "cell_type": "markdown",
368 | "metadata": {},
369 | "source": [
370 | "The best way to set-up a scientific Python environment is to use the cross-platform package manager `conda` from Continuum Analytics. First download and install miniconda http://conda.pydata.org/miniconda.html or Anaconda (see below). Next, to install the required libraries for these notebooks, simply run:\n",
371 | "\n",
372 | " $ conda install ipython ipython-notebook spyder numpy scipy sympy matplotlib cython\n",
373 | "\n",
374 | "This should be sufficient to get a working environment on any platform supported by `conda`."
375 | ]
376 | },
377 | {
378 | "cell_type": "markdown",
379 | "metadata": {},
380 | "source": [
381 | "### Linux"
382 | ]
383 | },
384 | {
385 | "cell_type": "markdown",
386 | "metadata": {},
387 | "source": [
388 | "In Ubuntu Linux, to installing python and all the requirements run:\n",
389 | "\n",
390 | " $ sudo apt-get install python ipython ipython-notebook\n",
391 | "$ sudo apt-get install python-numpy python-scipy python-matplotlib python-sympy\n",
392 | " $ sudo apt-get install spyder"
393 | ]
394 | },
395 | {
396 | "cell_type": "markdown",
397 | "metadata": {},
398 | "source": [
399 | "### MacOS X"
400 | ]
401 | },
402 | {
403 | "cell_type": "markdown",
404 | "metadata": {},
405 | "source": [
406 | "*Macports*\n",
407 | "\n",
408 | "Python is included by default in Mac OS X, but for our purposes it will be useful to install a new python environment using [Macports](http://www.macports.org/), because it makes it much easier to install all the required additional packages. Using Macports, we can install what we need with:\n",
409 | "\n",
410 | " $ sudo port install py27-ipython +pyside+notebook+parallel+scientific\n",
411 | " $ sudo port install py27-scipy py27-matplotlib py27-sympy\n",
412 | " $ sudo port install py27-spyder\n",
413 | "\n",
414 | "These will associate the commands `python` and `ipython` with the versions installed via macports (instead of the one that is shipped with Mac OS X), run the following commands:\n",
415 | "\n",
416 | " $ sudo port select python python27\n",
417 | " $ sudo port select ipython ipython27\n",
418 | "\n",
419 | "*Fink*\n",
420 | "\n",
421 | "Or, alternatively, you can use the [Fink](http://www.finkproject.org/) package manager. After installing Fink, use the following command to install python and the packages that we need:\n",
422 | "\n",
423 | " $ sudo fink install python27 ipython-py27 numpy-py27 matplotlib-py27 scipy-py27 sympy-py27\n",
424 | " $ sudo fink install spyder-mac-py27"
425 | ]
426 | },
427 | {
428 | "cell_type": "markdown",
429 | "metadata": {},
430 | "source": [
431 | "### Windows"
432 | ]
433 | },
434 | {
435 | "cell_type": "markdown",
436 | "metadata": {},
437 | "source": [
438 | "Windows lacks a good packaging system, so the easiest way to setup a Python environment is to install a pre-packaged distribution. Some good alternatives are:\n",
439 | "\n",
440 | " * [Enthought Python Distribution](http://www.enthought.com/products/epd.php). EPD is a commercial product but is available free for academic use.\n",
441 | " * [Anaconda](http://continuum.io/downloads.html). The Anaconda Python distribution comes with many scientific computing and data science packages and is free, including for commercial use and redistribution. It also has add-on products such as Accelerate, IOPro, and MKL Optimizations, which have free trials and are free for academic use.\n",
442 | " * [Python(x,y)](http://code.google.com/p/pythonxy/). Fully open source.\n",
443 | "\n",
444 | "\n",
445 | "\n",
446 | "#### Note\n",
447 | "\n",
448 | "EPD and Anaconda are also available for Linux and Max OS X."
449 | ]
450 | },
451 | {
452 | "cell_type": "markdown",
453 | "metadata": {},
454 | "source": [
455 | "## Further reading"
456 | ]
457 | },
458 | {
459 | "cell_type": "markdown",
460 | "metadata": {},
461 | "source": [
462 | " * [Python](http://www.python.org). The official Python web site.\n",
463 | " * [Python tutorials](http://docs.python.org/2/tutorial). The official Python tutorials.\n",
464 | " * [Think Python](http://www.greenteapress.com/thinkpython). A free book on Python."
465 | ]
466 | },
467 | {
468 | "cell_type": "markdown",
469 | "metadata": {},
470 | "source": [
471 | "## Python and module versions"
472 | ]
473 | },
474 | {
475 | "cell_type": "markdown",
476 | "metadata": {},
477 | "source": [
478 | "Since there are several different versions of Python and each Python package has its own release cycle and version number (for example scipy, numpy, matplotlib, etc., which we installed above and will discuss in detail in the following lectures), it is important for the reproducibility of an IPython notebook to record the versions of all these different software packages. If this is done properly it will be easy to reproduce the environment that was used to run a notebook, but if not it can be hard to know what was used to produce the results in a notebook.\n",
479 | "\n",
480 | "To encourage the practice of recording Python and module versions in notebooks, I've created a simple IPython extension that produces a table with versions numbers of selected software components. I believe that it is a good practice to include this kind of table in every notebook you create. \n",
481 | "\n",
482 | "To install this IPython extension, use `pip install version_information`:"
483 | ]
484 | },
485 | {
486 | "cell_type": "code",
487 | "execution_count": 1,
488 | "metadata": {
489 | "collapsed": false,
490 | "jupyter": {
491 | "outputs_hidden": false
492 | }
493 | },
494 | "outputs": [
495 | {
496 | "name": "stdout",
497 | "output_type": "stream",
498 | "text": [
499 | "Collecting version-information\n",
500 | "Installing collected packages: version-information\n",
501 | "Successfully installed version-information-1.0.3\n"
502 | ]
503 | }
504 | ],
505 | "source": [
506 | "# you only need to do this once\n",
507 | "!pip install --upgrade version_information"
508 | ]
509 | },
510 | {
511 | "cell_type": "markdown",
512 | "metadata": {},
513 | "source": [
514 | "or alternatively run (deprecated method):"
515 | ]
516 | },
517 | {
518 | "cell_type": "raw",
519 | "metadata": {},
520 | "source": [
521 | "# you only need to do this once\n",
522 | "%install_ext http://raw.github.com/jrjohansson/version_information/master/version_information.py"
523 | ]
524 | },
525 | {
526 | "cell_type": "markdown",
527 | "metadata": {},
528 | "source": [
529 | "Now, to load the extension and produce the version table"
530 | ]
531 | },
532 | {
533 | "cell_type": "code",
534 | "execution_count": 2,
535 | "metadata": {
536 | "collapsed": false,
537 | "jupyter": {
538 | "outputs_hidden": false
539 | }
540 | },
541 | "outputs": [
542 | {
543 | "data": {
544 | "application/json": {
545 | "Software versions": [
546 | {
547 | "module": "Python",
548 | "version": "2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)]"
549 | },
550 | {
551 | "module": "IPython",
552 | "version": "3.2.1"
553 | },
554 | {
555 | "module": "OS",
556 | "version": "Darwin 14.1.0 x86_64 i386 64bit"
557 | },
558 | {
559 | "module": "numpy",
560 | "version": "1.9.2"
561 | },
562 | {
563 | "module": "scipy",
564 | "version": "0.16.0"
565 | },
566 | {
567 | "module": "matplotlib",
568 | "version": "1.4.3"
569 | },
570 | {
571 | "module": "sympy",
572 | "version": "0.7.6"
573 | },
574 | {
575 | "module": "version_information",
576 | "version": "1.0.3"
577 | }
578 | ]
579 | },
580 | "text/html": [
581 | "Software Version Python 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)] IPython 3.2.1 OS Darwin 14.1.0 x86_64 i386 64bit numpy 1.9.2 scipy 0.16.0 matplotlib 1.4.3 sympy 0.7.6 version_information 1.0.3 Sat Aug 15 10:38:48 2015 JST
"
582 | ],
583 | "text/latex": [
584 | "\\begin{tabular}{|l|l|}\\hline\n",
585 | "{\\bf Software} & {\\bf Version} \\\\ \\hline\\hline\n",
586 | "Python & 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)] \\\\ \\hline\n",
587 | "IPython & 3.2.1 \\\\ \\hline\n",
588 | "OS & Darwin 14.1.0 x86\\_64 i386 64bit \\\\ \\hline\n",
589 | "numpy & 1.9.2 \\\\ \\hline\n",
590 | "scipy & 0.16.0 \\\\ \\hline\n",
591 | "matplotlib & 1.4.3 \\\\ \\hline\n",
592 | "sympy & 0.7.6 \\\\ \\hline\n",
593 | "version_information & 1.0.3 \\\\ \\hline\n",
594 | "\\hline \\multicolumn{2}{|l|}{Sat Aug 15 10:38:48 2015 JST} \\\\ \\hline\n",
595 | "\\end{tabular}\n"
596 | ],
597 | "text/plain": [
598 | "Software versions\n",
599 | "Python 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)]\n",
600 | "IPython 3.2.1\n",
601 | "OS Darwin 14.1.0 x86_64 i386 64bit\n",
602 | "numpy 1.9.2\n",
603 | "scipy 0.16.0\n",
604 | "matplotlib 1.4.3\n",
605 | "sympy 0.7.6\n",
606 | "version_information 1.0.3\n",
607 | "Sat Aug 15 10:38:48 2015 JST"
608 | ]
609 | },
610 | "execution_count": 2,
611 | "metadata": {},
612 | "output_type": "execute_result"
613 | }
614 | ],
615 | "source": [
616 | "%load_ext version_information\n",
617 | "\n",
618 | "%version_information numpy, scipy, matplotlib, sympy, version_information"
619 | ]
620 | }
621 | ],
622 | "metadata": {
623 | "kernelspec": {
624 | "display_name": "Python 3",
625 | "language": "python",
626 | "name": "python3"
627 | },
628 | "language_info": {
629 | "codemirror_mode": {
630 | "name": "ipython",
631 | "version": 3
632 | },
633 | "file_extension": ".py",
634 | "mimetype": "text/x-python",
635 | "name": "python",
636 | "nbconvert_exporter": "python",
637 | "pygments_lexer": "ipython3",
638 | "version": "3.8.1"
639 | }
640 | },
641 | "nbformat": 4,
642 | "nbformat_minor": 4
643 | }
644 |
--------------------------------------------------------------------------------
/Lecture-1-Introduction-to-Python-Programming.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Introduction to Python programming"
8 | ]
9 | },
10 | {
11 | "cell_type": "markdown",
12 | "metadata": {},
13 | "source": [
14 | "J.R. Johansson (jrjohansson at gmail.com)\n",
15 | "\n",
16 | "The latest version of this [IPython notebook](http://ipython.org/notebook.html) lecture is available at [http://github.com/jrjohansson/scientific-python-lectures](http://github.com/jrjohansson/scientific-python-lectures).\n",
17 | "\n",
18 | "The other notebooks in this lecture series are indexed at [http://jrjohansson.github.io](http://jrjohansson.github.io)."
19 | ]
20 | },
21 | {
22 | "cell_type": "markdown",
23 | "metadata": {},
24 | "source": [
25 | "## Python program files"
26 | ]
27 | },
28 | {
29 | "cell_type": "markdown",
30 | "metadata": {},
31 | "source": [
32 | "* Python code is usually stored in text files with the file ending \"`.py`\":\n",
33 | "\n",
34 | " myprogram.py\n",
35 | "\n",
36 | "* Every line in a Python program file is assumed to be a Python statement, or part thereof. \n",
37 | "\n",
38 | " * The only exception is comment lines, which start with the character `#` (optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter.\n",
39 | "\n",
40 | "\n",
41 | "* To run our Python program from the command line we use:\n",
42 | "\n",
43 | " $ python myprogram.py\n",
44 | "\n",
45 | "* On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned):\n",
46 | "\n",
47 | " #!/usr/bin/env python\n",
48 | "\n",
49 | " If we do, and if we additionally set the file script to be executable, we can run the program like this:\n",
50 | "\n",
51 | " $ myprogram.py"
52 | ]
53 | },
54 | {
55 | "cell_type": "markdown",
56 | "metadata": {},
57 | "source": [
58 | "### Example:"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": 1,
64 | "metadata": {
65 | "collapsed": false
66 | },
67 | "outputs": [
68 | {
69 | "name": "stdout",
70 | "output_type": "stream",
71 | "text": [
72 | "scripts/hello-world-in-swedish.py scripts/hello-world.py\r\n"
73 | ]
74 | }
75 | ],
76 | "source": [
77 | "ls scripts/hello-world*.py"
78 | ]
79 | },
80 | {
81 | "cell_type": "code",
82 | "execution_count": 2,
83 | "metadata": {
84 | "collapsed": false
85 | },
86 | "outputs": [
87 | {
88 | "name": "stdout",
89 | "output_type": "stream",
90 | "text": [
91 | "#!/usr/bin/env python\r\n",
92 | "\r\n",
93 | "print(\"Hello world!\")\r\n"
94 | ]
95 | }
96 | ],
97 | "source": [
98 | "cat scripts/hello-world.py"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 3,
104 | "metadata": {
105 | "collapsed": false
106 | },
107 | "outputs": [
108 | {
109 | "name": "stdout",
110 | "output_type": "stream",
111 | "text": [
112 | "Hello world!\r\n"
113 | ]
114 | }
115 | ],
116 | "source": [
117 | "!python scripts/hello-world.py"
118 | ]
119 | },
120 | {
121 | "cell_type": "markdown",
122 | "metadata": {},
123 | "source": [
124 | "### Character encoding"
125 | ]
126 | },
127 | {
128 | "cell_type": "markdown",
129 | "metadata": {},
130 | "source": [
131 | "The standard character encoding is ASCII, but we can use any other encoding, for example UTF-8. To specify that UTF-8 is used we include the special line\n",
132 | "\n",
133 | " # -*- coding: UTF-8 -*-\n",
134 | "\n",
135 | "at the top of the file."
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": 4,
141 | "metadata": {
142 | "collapsed": false
143 | },
144 | "outputs": [
145 | {
146 | "name": "stdout",
147 | "output_type": "stream",
148 | "text": [
149 | "#!/usr/bin/env python\r\n",
150 | "# -*- coding: UTF-8 -*-\r\n",
151 | "\r\n",
152 | "print(\"Hej världen!\")\r\n"
153 | ]
154 | }
155 | ],
156 | "source": [
157 | "cat scripts/hello-world-in-swedish.py"
158 | ]
159 | },
160 | {
161 | "cell_type": "code",
162 | "execution_count": 5,
163 | "metadata": {
164 | "collapsed": false
165 | },
166 | "outputs": [
167 | {
168 | "name": "stdout",
169 | "output_type": "stream",
170 | "text": [
171 | "Hej världen!\r\n"
172 | ]
173 | }
174 | ],
175 | "source": [
176 | "!python scripts/hello-world-in-swedish.py"
177 | ]
178 | },
179 | {
180 | "cell_type": "markdown",
181 | "metadata": {},
182 | "source": [
183 | "Other than these two *optional* lines in the beginning of a Python code file, no additional code is required for initializing a program. "
184 | ]
185 | },
186 | {
187 | "cell_type": "markdown",
188 | "metadata": {},
189 | "source": [
190 | "## IPython notebooks"
191 | ]
192 | },
193 | {
194 | "cell_type": "markdown",
195 | "metadata": {},
196 | "source": [
197 | "This file - an IPython notebook - does not follow the standard pattern with Python code in a text file. Instead, an IPython notebook is stored as a file in the [JSON](http://en.wikipedia.org/wiki/JSON) format. The advantage is that we can mix formatted text, Python code and code output. It requires the IPython notebook server to run it though, and therefore isn't a stand-alone Python program as described above. Other than that, there is no difference between the Python code that goes into a program file or an IPython notebook."
198 | ]
199 | },
200 | {
201 | "cell_type": "markdown",
202 | "metadata": {},
203 | "source": [
204 | "## Modules"
205 | ]
206 | },
207 | {
208 | "cell_type": "markdown",
209 | "metadata": {},
210 | "source": [
211 | "Most of the functionality in Python is provided by *modules*. The Python Standard Library is a large collection of modules that provides *cross-platform* implementations of common facilities such as access to the operating system, file I/O, string management, network communication, and much more."
212 | ]
213 | },
214 | {
215 | "cell_type": "markdown",
216 | "metadata": {},
217 | "source": [
218 | "### References"
219 | ]
220 | },
221 | {
222 | "cell_type": "markdown",
223 | "metadata": {},
224 | "source": [
225 | " * The Python Language Reference: http://docs.python.org/2/reference/index.html\n",
226 | " * The Python Standard Library: http://docs.python.org/2/library/\n",
227 | "\n",
228 | "To use a module in a Python program it first has to be imported. A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do:"
229 | ]
230 | },
231 | {
232 | "cell_type": "code",
233 | "execution_count": 6,
234 | "metadata": {
235 | "collapsed": false
236 | },
237 | "outputs": [],
238 | "source": [
239 | "import math"
240 | ]
241 | },
242 | {
243 | "cell_type": "markdown",
244 | "metadata": {},
245 | "source": [
246 | "This includes the whole module and makes it available for use later in the program. For example, we can do:"
247 | ]
248 | },
249 | {
250 | "cell_type": "code",
251 | "execution_count": 7,
252 | "metadata": {
253 | "collapsed": false
254 | },
255 | "outputs": [
256 | {
257 | "name": "stdout",
258 | "output_type": "stream",
259 | "text": [
260 | "1.0\n"
261 | ]
262 | }
263 | ],
264 | "source": [
265 | "import math\n",
266 | "\n",
267 | "x = math.cos(2 * math.pi)\n",
268 | "\n",
269 | "print(x)"
270 | ]
271 | },
272 | {
273 | "cell_type": "markdown",
274 | "metadata": {},
275 | "source": [
276 | "Alternatively, we can choose to import all symbols (functions and variables) in a module to the current namespace so that we don't need to use the prefix \"`math.`\" every time we use something from the `math` module:"
277 | ]
278 | },
279 | {
280 | "cell_type": "code",
281 | "execution_count": 8,
282 | "metadata": {
283 | "collapsed": false
284 | },
285 | "outputs": [
286 | {
287 | "name": "stdout",
288 | "output_type": "stream",
289 | "text": [
290 | "1.0\n"
291 | ]
292 | }
293 | ],
294 | "source": [
295 | "from math import *\n",
296 | "\n",
297 | "x = cos(2 * pi)\n",
298 | "\n",
299 | "print(x)"
300 | ]
301 | },
302 | {
303 | "cell_type": "markdown",
304 | "metadata": {},
305 | "source": [
306 | "This pattern can be very convenient, but in large programs that include many modules it is often a good idea to keep the symbols from each module in their own namespaces, by using the `import math` pattern. This would eliminate potentially confusing problems with name space collisions.\n",
307 | "\n",
308 | "As a third alternative, we can choose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character `*`:"
309 | ]
310 | },
311 | {
312 | "cell_type": "code",
313 | "execution_count": 9,
314 | "metadata": {
315 | "collapsed": false
316 | },
317 | "outputs": [
318 | {
319 | "name": "stdout",
320 | "output_type": "stream",
321 | "text": [
322 | "1.0\n"
323 | ]
324 | }
325 | ],
326 | "source": [
327 | "from math import cos, pi\n",
328 | "\n",
329 | "x = cos(2 * pi)\n",
330 | "\n",
331 | "print(x)"
332 | ]
333 | },
334 | {
335 | "cell_type": "markdown",
336 | "metadata": {},
337 | "source": [
338 | "### Looking at what a module contains, and its documentation"
339 | ]
340 | },
341 | {
342 | "cell_type": "markdown",
343 | "metadata": {},
344 | "source": [
345 | "Once a module is imported, we can list the symbols it provides using the `dir` function:"
346 | ]
347 | },
348 | {
349 | "cell_type": "code",
350 | "execution_count": 10,
351 | "metadata": {
352 | "collapsed": false
353 | },
354 | "outputs": [
355 | {
356 | "name": "stdout",
357 | "output_type": "stream",
358 | "text": [
359 | "['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n"
360 | ]
361 | }
362 | ],
363 | "source": [
364 | "import math\n",
365 | "\n",
366 | "print(dir(math))"
367 | ]
368 | },
369 | {
370 | "cell_type": "markdown",
371 | "metadata": {},
372 | "source": [
373 | "And using the function `help` we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way). "
374 | ]
375 | },
376 | {
377 | "cell_type": "code",
378 | "execution_count": 11,
379 | "metadata": {
380 | "collapsed": false
381 | },
382 | "outputs": [
383 | {
384 | "name": "stdout",
385 | "output_type": "stream",
386 | "text": [
387 | "Help on built-in function log in module math:\n",
388 | "\n",
389 | "log(...)\n",
390 | " log(x[, base])\n",
391 | " \n",
392 | " Return the logarithm of x to the given base.\n",
393 | " If the base not specified, returns the natural logarithm (base e) of x.\n",
394 | "\n"
395 | ]
396 | }
397 | ],
398 | "source": [
399 | "help(math.log)"
400 | ]
401 | },
402 | {
403 | "cell_type": "code",
404 | "execution_count": 12,
405 | "metadata": {
406 | "collapsed": false
407 | },
408 | "outputs": [
409 | {
410 | "data": {
411 | "text/plain": [
412 | "2.302585092994046"
413 | ]
414 | },
415 | "execution_count": 12,
416 | "metadata": {},
417 | "output_type": "execute_result"
418 | }
419 | ],
420 | "source": [
421 | "log(10)"
422 | ]
423 | },
424 | {
425 | "cell_type": "code",
426 | "execution_count": 13,
427 | "metadata": {
428 | "collapsed": false
429 | },
430 | "outputs": [
431 | {
432 | "data": {
433 | "text/plain": [
434 | "3.3219280948873626"
435 | ]
436 | },
437 | "execution_count": 13,
438 | "metadata": {},
439 | "output_type": "execute_result"
440 | }
441 | ],
442 | "source": [
443 | "log(10, 2)"
444 | ]
445 | },
446 | {
447 | "cell_type": "markdown",
448 | "metadata": {},
449 | "source": [
450 | "We can also use the `help` function directly on modules: Try\n",
451 | "\n",
452 | " help(math) \n",
453 | "\n",
454 | "Some very useful modules form the Python standard library are `os`, `sys`, `math`, `shutil`, `re`, `subprocess`, `multiprocessing`, `threading`. \n",
455 | "\n",
456 | "A complete lists of standard modules for Python 2 and Python 3 are available at http://docs.python.org/2/library/ and http://docs.python.org/3/library/, respectively."
457 | ]
458 | },
459 | {
460 | "cell_type": "markdown",
461 | "metadata": {},
462 | "source": [
463 | "## Variables and types"
464 | ]
465 | },
466 | {
467 | "cell_type": "markdown",
468 | "metadata": {},
469 | "source": [
470 | "### Symbol names "
471 | ]
472 | },
473 | {
474 | "cell_type": "markdown",
475 | "metadata": {},
476 | "source": [
477 | "Variable names in Python can contain alphanumerical characters `a-z`, `A-Z`, `0-9` and some special characters such as `_`. Normal variable names must start with a letter. \n",
478 | "\n",
479 | "By convention, variable names start with a lower-case letter, and Class names start with a capital letter. \n",
480 | "\n",
481 | "In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:\n",
482 | "\n",
483 | " and, as, assert, break, class, continue, def, del, elif, else, except, \n",
484 | " exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n",
485 | " pass, print, raise, return, try, while, with, yield\n",
486 | "\n",
487 | "Note: Be aware of the keyword `lambda`, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name."
488 | ]
489 | },
490 | {
491 | "cell_type": "markdown",
492 | "metadata": {},
493 | "source": [
494 | "### Assignment"
495 | ]
496 | },
497 | {
498 | "cell_type": "markdown",
499 | "metadata": {},
500 | "source": [
501 | "\n",
502 | "\n",
503 | "The assignment operator in Python is `=`. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one.\n",
504 | "\n",
505 | "Assigning a value to a new variable creates the variable:"
506 | ]
507 | },
508 | {
509 | "cell_type": "code",
510 | "execution_count": 14,
511 | "metadata": {
512 | "collapsed": false
513 | },
514 | "outputs": [],
515 | "source": [
516 | "# variable assignments\n",
517 | "x = 1.0\n",
518 | "my_variable = 12.2"
519 | ]
520 | },
521 | {
522 | "cell_type": "markdown",
523 | "metadata": {},
524 | "source": [
525 | "Although not explicitly specified, a variable does have a type associated with it. The type is derived from the value that was assigned to it."
526 | ]
527 | },
528 | {
529 | "cell_type": "code",
530 | "execution_count": 15,
531 | "metadata": {
532 | "collapsed": false
533 | },
534 | "outputs": [
535 | {
536 | "data": {
537 | "text/plain": [
538 | "float"
539 | ]
540 | },
541 | "execution_count": 15,
542 | "metadata": {},
543 | "output_type": "execute_result"
544 | }
545 | ],
546 | "source": [
547 | "type(x)"
548 | ]
549 | },
550 | {
551 | "cell_type": "markdown",
552 | "metadata": {},
553 | "source": [
554 | "If we assign a new value to a variable, its type can change."
555 | ]
556 | },
557 | {
558 | "cell_type": "code",
559 | "execution_count": 16,
560 | "metadata": {
561 | "collapsed": false
562 | },
563 | "outputs": [],
564 | "source": [
565 | "x = 1"
566 | ]
567 | },
568 | {
569 | "cell_type": "code",
570 | "execution_count": 17,
571 | "metadata": {
572 | "collapsed": false
573 | },
574 | "outputs": [
575 | {
576 | "data": {
577 | "text/plain": [
578 | "int"
579 | ]
580 | },
581 | "execution_count": 17,
582 | "metadata": {},
583 | "output_type": "execute_result"
584 | }
585 | ],
586 | "source": [
587 | "type(x)"
588 | ]
589 | },
590 | {
591 | "cell_type": "markdown",
592 | "metadata": {},
593 | "source": [
594 | "If we try to use a variable that has not yet been defined we get an `NameError`:"
595 | ]
596 | },
597 | {
598 | "cell_type": "code",
599 | "execution_count": 18,
600 | "metadata": {
601 | "collapsed": false
602 | },
603 | "outputs": [
604 | {
605 | "ename": "NameError",
606 | "evalue": "name 'y' is not defined",
607 | "output_type": "error",
608 | "traceback": [
609 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
610 | "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
611 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0my\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
612 | "\u001b[0;31mNameError\u001b[0m: name 'y' is not defined"
613 | ]
614 | }
615 | ],
616 | "source": [
617 | "print(y)"
618 | ]
619 | },
620 | {
621 | "cell_type": "markdown",
622 | "metadata": {},
623 | "source": [
624 | "### Fundamental types"
625 | ]
626 | },
627 | {
628 | "cell_type": "code",
629 | "execution_count": 19,
630 | "metadata": {
631 | "collapsed": false
632 | },
633 | "outputs": [
634 | {
635 | "data": {
636 | "text/plain": [
637 | "int"
638 | ]
639 | },
640 | "execution_count": 19,
641 | "metadata": {},
642 | "output_type": "execute_result"
643 | }
644 | ],
645 | "source": [
646 | "# integers\n",
647 | "x = 1\n",
648 | "type(x)"
649 | ]
650 | },
651 | {
652 | "cell_type": "code",
653 | "execution_count": 20,
654 | "metadata": {
655 | "collapsed": false
656 | },
657 | "outputs": [
658 | {
659 | "data": {
660 | "text/plain": [
661 | "float"
662 | ]
663 | },
664 | "execution_count": 20,
665 | "metadata": {},
666 | "output_type": "execute_result"
667 | }
668 | ],
669 | "source": [
670 | "# float\n",
671 | "x = 1.0\n",
672 | "type(x)"
673 | ]
674 | },
675 | {
676 | "cell_type": "code",
677 | "execution_count": 21,
678 | "metadata": {
679 | "collapsed": false
680 | },
681 | "outputs": [
682 | {
683 | "data": {
684 | "text/plain": [
685 | "bool"
686 | ]
687 | },
688 | "execution_count": 21,
689 | "metadata": {},
690 | "output_type": "execute_result"
691 | }
692 | ],
693 | "source": [
694 | "# boolean\n",
695 | "b1 = True\n",
696 | "b2 = False\n",
697 | "\n",
698 | "type(b1)"
699 | ]
700 | },
701 | {
702 | "cell_type": "code",
703 | "execution_count": 22,
704 | "metadata": {
705 | "collapsed": false
706 | },
707 | "outputs": [
708 | {
709 | "data": {
710 | "text/plain": [
711 | "complex"
712 | ]
713 | },
714 | "execution_count": 22,
715 | "metadata": {},
716 | "output_type": "execute_result"
717 | }
718 | ],
719 | "source": [
720 | "# complex numbers: note the use of `j` to specify the imaginary part\n",
721 | "x = 1.0 - 1.0j\n",
722 | "type(x)"
723 | ]
724 | },
725 | {
726 | "cell_type": "code",
727 | "execution_count": 23,
728 | "metadata": {
729 | "collapsed": false
730 | },
731 | "outputs": [
732 | {
733 | "name": "stdout",
734 | "output_type": "stream",
735 | "text": [
736 | "(1-1j)\n"
737 | ]
738 | }
739 | ],
740 | "source": [
741 | "print(x)"
742 | ]
743 | },
744 | {
745 | "cell_type": "code",
746 | "execution_count": 24,
747 | "metadata": {
748 | "collapsed": false
749 | },
750 | "outputs": [
751 | {
752 | "name": "stdout",
753 | "output_type": "stream",
754 | "text": [
755 | "(1.0, -1.0)\n"
756 | ]
757 | }
758 | ],
759 | "source": [
760 | "print(x.real, x.imag)"
761 | ]
762 | },
763 | {
764 | "cell_type": "markdown",
765 | "metadata": {},
766 | "source": [
767 | "### Type utility functions"
768 | ]
769 | },
770 | {
771 | "cell_type": "markdown",
772 | "metadata": {},
773 | "source": [
774 | "\n",
775 | "The module `types` contains a number of type name definitions that can be used to test if variables are of certain types:"
776 | ]
777 | },
778 | {
779 | "cell_type": "code",
780 | "execution_count": 25,
781 | "metadata": {
782 | "collapsed": false
783 | },
784 | "outputs": [
785 | {
786 | "name": "stdout",
787 | "output_type": "stream",
788 | "text": [
789 | "['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__']\n"
790 | ]
791 | }
792 | ],
793 | "source": [
794 | "import types\n",
795 | "\n",
796 | "# print all types defined in the `types` module\n",
797 | "print(dir(types))"
798 | ]
799 | },
800 | {
801 | "cell_type": "code",
802 | "execution_count": 26,
803 | "metadata": {
804 | "collapsed": false
805 | },
806 | "outputs": [
807 | {
808 | "data": {
809 | "text/plain": [
810 | "True"
811 | ]
812 | },
813 | "execution_count": 26,
814 | "metadata": {},
815 | "output_type": "execute_result"
816 | }
817 | ],
818 | "source": [
819 | "x = 1.0\n",
820 | "\n",
821 | "# check if the variable x is a float\n",
822 | "type(x) is float"
823 | ]
824 | },
825 | {
826 | "cell_type": "code",
827 | "execution_count": 27,
828 | "metadata": {
829 | "collapsed": false
830 | },
831 | "outputs": [
832 | {
833 | "data": {
834 | "text/plain": [
835 | "False"
836 | ]
837 | },
838 | "execution_count": 27,
839 | "metadata": {},
840 | "output_type": "execute_result"
841 | }
842 | ],
843 | "source": [
844 | "# check if the variable x is an int\n",
845 | "type(x) is int"
846 | ]
847 | },
848 | {
849 | "cell_type": "markdown",
850 | "metadata": {},
851 | "source": [
852 | "We can also use the `isinstance` method for testing types of variables:"
853 | ]
854 | },
855 | {
856 | "cell_type": "code",
857 | "execution_count": 28,
858 | "metadata": {
859 | "collapsed": false
860 | },
861 | "outputs": [
862 | {
863 | "data": {
864 | "text/plain": [
865 | "True"
866 | ]
867 | },
868 | "execution_count": 28,
869 | "metadata": {},
870 | "output_type": "execute_result"
871 | }
872 | ],
873 | "source": [
874 | "isinstance(x, float)"
875 | ]
876 | },
877 | {
878 | "cell_type": "markdown",
879 | "metadata": {},
880 | "source": [
881 | "### Type casting"
882 | ]
883 | },
884 | {
885 | "cell_type": "code",
886 | "execution_count": 29,
887 | "metadata": {
888 | "collapsed": false
889 | },
890 | "outputs": [
891 | {
892 | "name": "stdout",
893 | "output_type": "stream",
894 | "text": [
895 | "(1.5, )\n"
896 | ]
897 | }
898 | ],
899 | "source": [
900 | "x = 1.5\n",
901 | "\n",
902 | "print(x, type(x))"
903 | ]
904 | },
905 | {
906 | "cell_type": "code",
907 | "execution_count": 30,
908 | "metadata": {
909 | "collapsed": false
910 | },
911 | "outputs": [
912 | {
913 | "name": "stdout",
914 | "output_type": "stream",
915 | "text": [
916 | "(1, )\n"
917 | ]
918 | }
919 | ],
920 | "source": [
921 | "x = int(x)\n",
922 | "\n",
923 | "print(x, type(x))"
924 | ]
925 | },
926 | {
927 | "cell_type": "code",
928 | "execution_count": 31,
929 | "metadata": {
930 | "collapsed": false
931 | },
932 | "outputs": [
933 | {
934 | "name": "stdout",
935 | "output_type": "stream",
936 | "text": [
937 | "((1+0j), )\n"
938 | ]
939 | }
940 | ],
941 | "source": [
942 | "z = complex(x)\n",
943 | "\n",
944 | "print(z, type(z))"
945 | ]
946 | },
947 | {
948 | "cell_type": "code",
949 | "execution_count": 32,
950 | "metadata": {
951 | "collapsed": false
952 | },
953 | "outputs": [
954 | {
955 | "ename": "TypeError",
956 | "evalue": "can't convert complex to float",
957 | "output_type": "error",
958 | "traceback": [
959 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
960 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
961 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mfloat\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mz\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
962 | "\u001b[0;31mTypeError\u001b[0m: can't convert complex to float"
963 | ]
964 | }
965 | ],
966 | "source": [
967 | "x = float(z)"
968 | ]
969 | },
970 | {
971 | "cell_type": "markdown",
972 | "metadata": {},
973 | "source": [
974 | "Complex variables cannot be cast to floats or integers. We need to use `z.real` or `z.imag` to extract the part of the complex number we want:"
975 | ]
976 | },
977 | {
978 | "cell_type": "code",
979 | "execution_count": 33,
980 | "metadata": {
981 | "collapsed": false
982 | },
983 | "outputs": [
984 | {
985 | "name": "stdout",
986 | "output_type": "stream",
987 | "text": [
988 | "(1.0, ' -> ', True, )\n",
989 | "(0.0, ' -> ', False, )\n"
990 | ]
991 | }
992 | ],
993 | "source": [
994 | "y = bool(z.real)\n",
995 | "\n",
996 | "print(z.real, \" -> \", y, type(y))\n",
997 | "\n",
998 | "y = bool(z.imag)\n",
999 | "\n",
1000 | "print(z.imag, \" -> \", y, type(y))"
1001 | ]
1002 | },
1003 | {
1004 | "cell_type": "markdown",
1005 | "metadata": {},
1006 | "source": [
1007 | "## Operators and comparisons"
1008 | ]
1009 | },
1010 | {
1011 | "cell_type": "markdown",
1012 | "metadata": {},
1013 | "source": [
1014 | "Most operators and comparisons in Python work as one would expect:\n",
1015 | "\n",
1016 | "* Arithmetic operators `+`, `-`, `*`, `/`, `//` (integer division), '**' power\n"
1017 | ]
1018 | },
1019 | {
1020 | "cell_type": "code",
1021 | "execution_count": 34,
1022 | "metadata": {
1023 | "collapsed": false
1024 | },
1025 | "outputs": [
1026 | {
1027 | "data": {
1028 | "text/plain": [
1029 | "(3, -1, 2, 0)"
1030 | ]
1031 | },
1032 | "execution_count": 34,
1033 | "metadata": {},
1034 | "output_type": "execute_result"
1035 | }
1036 | ],
1037 | "source": [
1038 | "1 + 2, 1 - 2, 1 * 2, 1 / 2"
1039 | ]
1040 | },
1041 | {
1042 | "cell_type": "code",
1043 | "execution_count": 35,
1044 | "metadata": {
1045 | "collapsed": false
1046 | },
1047 | "outputs": [
1048 | {
1049 | "data": {
1050 | "text/plain": [
1051 | "(3.0, -1.0, 2.0, 0.5)"
1052 | ]
1053 | },
1054 | "execution_count": 35,
1055 | "metadata": {},
1056 | "output_type": "execute_result"
1057 | }
1058 | ],
1059 | "source": [
1060 | "1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0"
1061 | ]
1062 | },
1063 | {
1064 | "cell_type": "code",
1065 | "execution_count": 36,
1066 | "metadata": {
1067 | "collapsed": false
1068 | },
1069 | "outputs": [
1070 | {
1071 | "data": {
1072 | "text/plain": [
1073 | "1.0"
1074 | ]
1075 | },
1076 | "execution_count": 36,
1077 | "metadata": {},
1078 | "output_type": "execute_result"
1079 | }
1080 | ],
1081 | "source": [
1082 | "# Integer division of float numbers\n",
1083 | "3.0 // 2.0"
1084 | ]
1085 | },
1086 | {
1087 | "cell_type": "code",
1088 | "execution_count": 37,
1089 | "metadata": {
1090 | "collapsed": false
1091 | },
1092 | "outputs": [
1093 | {
1094 | "data": {
1095 | "text/plain": [
1096 | "4"
1097 | ]
1098 | },
1099 | "execution_count": 37,
1100 | "metadata": {},
1101 | "output_type": "execute_result"
1102 | }
1103 | ],
1104 | "source": [
1105 | "# Note! The power operators in python isn't ^, but **\n",
1106 | "2 ** 2"
1107 | ]
1108 | },
1109 | {
1110 | "cell_type": "markdown",
1111 | "metadata": {},
1112 | "source": [
1113 | "Note: The `/` operator always performs a floating point division in Python 3.x.\n",
1114 | "This is not true in Python 2.x, where the result of `/` is always an integer if the operands are integers.\n",
1115 | "to be more specific, `1/2 = 0.5` (`float`) in Python 3.x, and `1/2 = 0` (`int`) in Python 2.x (but `1.0/2 = 0.5` in Python 2.x)."
1116 | ]
1117 | },
1118 | {
1119 | "cell_type": "markdown",
1120 | "metadata": {},
1121 | "source": [
1122 | "* The boolean operators are spelled out as the words `and`, `not`, `or`. "
1123 | ]
1124 | },
1125 | {
1126 | "cell_type": "code",
1127 | "execution_count": 38,
1128 | "metadata": {
1129 | "collapsed": false
1130 | },
1131 | "outputs": [
1132 | {
1133 | "data": {
1134 | "text/plain": [
1135 | "False"
1136 | ]
1137 | },
1138 | "execution_count": 38,
1139 | "metadata": {},
1140 | "output_type": "execute_result"
1141 | }
1142 | ],
1143 | "source": [
1144 | "True and False"
1145 | ]
1146 | },
1147 | {
1148 | "cell_type": "code",
1149 | "execution_count": 39,
1150 | "metadata": {
1151 | "collapsed": false
1152 | },
1153 | "outputs": [
1154 | {
1155 | "data": {
1156 | "text/plain": [
1157 | "True"
1158 | ]
1159 | },
1160 | "execution_count": 39,
1161 | "metadata": {},
1162 | "output_type": "execute_result"
1163 | }
1164 | ],
1165 | "source": [
1166 | "not False"
1167 | ]
1168 | },
1169 | {
1170 | "cell_type": "code",
1171 | "execution_count": 40,
1172 | "metadata": {
1173 | "collapsed": false
1174 | },
1175 | "outputs": [
1176 | {
1177 | "data": {
1178 | "text/plain": [
1179 | "True"
1180 | ]
1181 | },
1182 | "execution_count": 40,
1183 | "metadata": {},
1184 | "output_type": "execute_result"
1185 | }
1186 | ],
1187 | "source": [
1188 | "True or False"
1189 | ]
1190 | },
1191 | {
1192 | "cell_type": "markdown",
1193 | "metadata": {},
1194 | "source": [
1195 | "* Comparison operators `>`, `<`, `>=` (greater or equal), `<=` (less or equal), `==` equality, `is` identical."
1196 | ]
1197 | },
1198 | {
1199 | "cell_type": "code",
1200 | "execution_count": 41,
1201 | "metadata": {
1202 | "collapsed": false
1203 | },
1204 | "outputs": [
1205 | {
1206 | "data": {
1207 | "text/plain": [
1208 | "(True, False)"
1209 | ]
1210 | },
1211 | "execution_count": 41,
1212 | "metadata": {},
1213 | "output_type": "execute_result"
1214 | }
1215 | ],
1216 | "source": [
1217 | "2 > 1, 2 < 1"
1218 | ]
1219 | },
1220 | {
1221 | "cell_type": "code",
1222 | "execution_count": 42,
1223 | "metadata": {
1224 | "collapsed": false
1225 | },
1226 | "outputs": [
1227 | {
1228 | "data": {
1229 | "text/plain": [
1230 | "(False, False)"
1231 | ]
1232 | },
1233 | "execution_count": 42,
1234 | "metadata": {},
1235 | "output_type": "execute_result"
1236 | }
1237 | ],
1238 | "source": [
1239 | "2 > 2, 2 < 2"
1240 | ]
1241 | },
1242 | {
1243 | "cell_type": "code",
1244 | "execution_count": 43,
1245 | "metadata": {
1246 | "collapsed": false
1247 | },
1248 | "outputs": [
1249 | {
1250 | "data": {
1251 | "text/plain": [
1252 | "(True, True)"
1253 | ]
1254 | },
1255 | "execution_count": 43,
1256 | "metadata": {},
1257 | "output_type": "execute_result"
1258 | }
1259 | ],
1260 | "source": [
1261 | "2 >= 2, 2 <= 2"
1262 | ]
1263 | },
1264 | {
1265 | "cell_type": "code",
1266 | "execution_count": 44,
1267 | "metadata": {
1268 | "collapsed": false
1269 | },
1270 | "outputs": [
1271 | {
1272 | "data": {
1273 | "text/plain": [
1274 | "True"
1275 | ]
1276 | },
1277 | "execution_count": 44,
1278 | "metadata": {},
1279 | "output_type": "execute_result"
1280 | }
1281 | ],
1282 | "source": [
1283 | "# equality\n",
1284 | "[1,2] == [1,2]"
1285 | ]
1286 | },
1287 | {
1288 | "cell_type": "code",
1289 | "execution_count": 45,
1290 | "metadata": {
1291 | "collapsed": false
1292 | },
1293 | "outputs": [
1294 | {
1295 | "data": {
1296 | "text/plain": [
1297 | "True"
1298 | ]
1299 | },
1300 | "execution_count": 45,
1301 | "metadata": {},
1302 | "output_type": "execute_result"
1303 | }
1304 | ],
1305 | "source": [
1306 | "# objects identical?\n",
1307 | "l1 = l2 = [1,2]\n",
1308 | "\n",
1309 | "l1 is l2"
1310 | ]
1311 | },
1312 | {
1313 | "cell_type": "markdown",
1314 | "metadata": {},
1315 | "source": [
1316 | "## Compound types: Strings, List and dictionaries"
1317 | ]
1318 | },
1319 | {
1320 | "cell_type": "markdown",
1321 | "metadata": {},
1322 | "source": [
1323 | "### Strings"
1324 | ]
1325 | },
1326 | {
1327 | "cell_type": "markdown",
1328 | "metadata": {},
1329 | "source": [
1330 | "Strings are the variable type that is used for storing text messages. "
1331 | ]
1332 | },
1333 | {
1334 | "cell_type": "code",
1335 | "execution_count": 46,
1336 | "metadata": {
1337 | "collapsed": false
1338 | },
1339 | "outputs": [
1340 | {
1341 | "data": {
1342 | "text/plain": [
1343 | "str"
1344 | ]
1345 | },
1346 | "execution_count": 46,
1347 | "metadata": {},
1348 | "output_type": "execute_result"
1349 | }
1350 | ],
1351 | "source": [
1352 | "s = \"Hello world\"\n",
1353 | "type(s)"
1354 | ]
1355 | },
1356 | {
1357 | "cell_type": "code",
1358 | "execution_count": 47,
1359 | "metadata": {
1360 | "collapsed": false
1361 | },
1362 | "outputs": [
1363 | {
1364 | "data": {
1365 | "text/plain": [
1366 | "11"
1367 | ]
1368 | },
1369 | "execution_count": 47,
1370 | "metadata": {},
1371 | "output_type": "execute_result"
1372 | }
1373 | ],
1374 | "source": [
1375 | "# length of the string: the number of characters\n",
1376 | "len(s)"
1377 | ]
1378 | },
1379 | {
1380 | "cell_type": "code",
1381 | "execution_count": 48,
1382 | "metadata": {
1383 | "collapsed": false
1384 | },
1385 | "outputs": [
1386 | {
1387 | "name": "stdout",
1388 | "output_type": "stream",
1389 | "text": [
1390 | "Hello test\n"
1391 | ]
1392 | }
1393 | ],
1394 | "source": [
1395 | "# replace a substring in a string with something else\n",
1396 | "s2 = s.replace(\"world\", \"test\")\n",
1397 | "print(s2)"
1398 | ]
1399 | },
1400 | {
1401 | "cell_type": "markdown",
1402 | "metadata": {},
1403 | "source": [
1404 | "We can index a character in a string using `[]`:"
1405 | ]
1406 | },
1407 | {
1408 | "cell_type": "code",
1409 | "execution_count": 49,
1410 | "metadata": {
1411 | "collapsed": false
1412 | },
1413 | "outputs": [
1414 | {
1415 | "data": {
1416 | "text/plain": [
1417 | "'H'"
1418 | ]
1419 | },
1420 | "execution_count": 49,
1421 | "metadata": {},
1422 | "output_type": "execute_result"
1423 | }
1424 | ],
1425 | "source": [
1426 | "s[0]"
1427 | ]
1428 | },
1429 | {
1430 | "cell_type": "markdown",
1431 | "metadata": {},
1432 | "source": [
1433 | "**Heads up MATLAB users:** Indexing start at 0!\n",
1434 | "\n",
1435 | "We can extract a part of a string using the syntax `[start:stop]`, which extracts characters between index `start` and `stop` -1 (the character at index `stop` is not included):"
1436 | ]
1437 | },
1438 | {
1439 | "cell_type": "code",
1440 | "execution_count": 50,
1441 | "metadata": {
1442 | "collapsed": false
1443 | },
1444 | "outputs": [
1445 | {
1446 | "data": {
1447 | "text/plain": [
1448 | "'Hello'"
1449 | ]
1450 | },
1451 | "execution_count": 50,
1452 | "metadata": {},
1453 | "output_type": "execute_result"
1454 | }
1455 | ],
1456 | "source": [
1457 | "s[0:5]"
1458 | ]
1459 | },
1460 | {
1461 | "cell_type": "code",
1462 | "execution_count": 51,
1463 | "metadata": {
1464 | "collapsed": false
1465 | },
1466 | "outputs": [
1467 | {
1468 | "data": {
1469 | "text/plain": [
1470 | "'o'"
1471 | ]
1472 | },
1473 | "execution_count": 51,
1474 | "metadata": {},
1475 | "output_type": "execute_result"
1476 | }
1477 | ],
1478 | "source": [
1479 | "s[4:5]"
1480 | ]
1481 | },
1482 | {
1483 | "cell_type": "markdown",
1484 | "metadata": {},
1485 | "source": [
1486 | "If we omit either (or both) of `start` or `stop` from `[start:stop]`, the default is the beginning and the end of the string, respectively:"
1487 | ]
1488 | },
1489 | {
1490 | "cell_type": "code",
1491 | "execution_count": 52,
1492 | "metadata": {
1493 | "collapsed": false
1494 | },
1495 | "outputs": [
1496 | {
1497 | "data": {
1498 | "text/plain": [
1499 | "'Hello'"
1500 | ]
1501 | },
1502 | "execution_count": 52,
1503 | "metadata": {},
1504 | "output_type": "execute_result"
1505 | }
1506 | ],
1507 | "source": [
1508 | "s[:5]"
1509 | ]
1510 | },
1511 | {
1512 | "cell_type": "code",
1513 | "execution_count": 53,
1514 | "metadata": {
1515 | "collapsed": false
1516 | },
1517 | "outputs": [
1518 | {
1519 | "data": {
1520 | "text/plain": [
1521 | "'world'"
1522 | ]
1523 | },
1524 | "execution_count": 53,
1525 | "metadata": {},
1526 | "output_type": "execute_result"
1527 | }
1528 | ],
1529 | "source": [
1530 | "s[6:]"
1531 | ]
1532 | },
1533 | {
1534 | "cell_type": "code",
1535 | "execution_count": 54,
1536 | "metadata": {
1537 | "collapsed": false
1538 | },
1539 | "outputs": [
1540 | {
1541 | "data": {
1542 | "text/plain": [
1543 | "'Hello world'"
1544 | ]
1545 | },
1546 | "execution_count": 54,
1547 | "metadata": {},
1548 | "output_type": "execute_result"
1549 | }
1550 | ],
1551 | "source": [
1552 | "s[:]"
1553 | ]
1554 | },
1555 | {
1556 | "cell_type": "markdown",
1557 | "metadata": {},
1558 | "source": [
1559 | "We can also define the step size using the syntax `[start:end:step]` (the default value for `step` is 1, as we saw above):"
1560 | ]
1561 | },
1562 | {
1563 | "cell_type": "code",
1564 | "execution_count": 55,
1565 | "metadata": {
1566 | "collapsed": false
1567 | },
1568 | "outputs": [
1569 | {
1570 | "data": {
1571 | "text/plain": [
1572 | "'Hello world'"
1573 | ]
1574 | },
1575 | "execution_count": 55,
1576 | "metadata": {},
1577 | "output_type": "execute_result"
1578 | }
1579 | ],
1580 | "source": [
1581 | "s[::1]"
1582 | ]
1583 | },
1584 | {
1585 | "cell_type": "code",
1586 | "execution_count": 56,
1587 | "metadata": {
1588 | "collapsed": false
1589 | },
1590 | "outputs": [
1591 | {
1592 | "data": {
1593 | "text/plain": [
1594 | "'Hlowrd'"
1595 | ]
1596 | },
1597 | "execution_count": 56,
1598 | "metadata": {},
1599 | "output_type": "execute_result"
1600 | }
1601 | ],
1602 | "source": [
1603 | "s[::2]"
1604 | ]
1605 | },
1606 | {
1607 | "cell_type": "markdown",
1608 | "metadata": {},
1609 | "source": [
1610 | "This technique is called *slicing*. Read more about the syntax here: http://docs.python.org/release/2.7.3/library/functions.html?highlight=slice#slice"
1611 | ]
1612 | },
1613 | {
1614 | "cell_type": "markdown",
1615 | "metadata": {},
1616 | "source": [
1617 | "Python has a very rich set of functions for text processing. See for example http://docs.python.org/2/library/string.html for more information."
1618 | ]
1619 | },
1620 | {
1621 | "cell_type": "markdown",
1622 | "metadata": {},
1623 | "source": [
1624 | "#### String formatting examples"
1625 | ]
1626 | },
1627 | {
1628 | "cell_type": "code",
1629 | "execution_count": 57,
1630 | "metadata": {
1631 | "collapsed": false
1632 | },
1633 | "outputs": [
1634 | {
1635 | "name": "stdout",
1636 | "output_type": "stream",
1637 | "text": [
1638 | "('str1', 'str2', 'str3')\n"
1639 | ]
1640 | }
1641 | ],
1642 | "source": [
1643 | "print(\"str1\", \"str2\", \"str3\") # The print statement concatenates strings with a space"
1644 | ]
1645 | },
1646 | {
1647 | "cell_type": "code",
1648 | "execution_count": 58,
1649 | "metadata": {
1650 | "collapsed": false
1651 | },
1652 | "outputs": [
1653 | {
1654 | "name": "stdout",
1655 | "output_type": "stream",
1656 | "text": [
1657 | "('str1', 1.0, False, -1j)\n"
1658 | ]
1659 | }
1660 | ],
1661 | "source": [
1662 | "print(\"str1\", 1.0, False, -1j) # The print statements converts all arguments to strings"
1663 | ]
1664 | },
1665 | {
1666 | "cell_type": "code",
1667 | "execution_count": 59,
1668 | "metadata": {
1669 | "collapsed": false
1670 | },
1671 | "outputs": [
1672 | {
1673 | "name": "stdout",
1674 | "output_type": "stream",
1675 | "text": [
1676 | "str1str2str3\n"
1677 | ]
1678 | }
1679 | ],
1680 | "source": [
1681 | "print(\"str1\" + \"str2\" + \"str3\") # strings added with + are concatenated without space"
1682 | ]
1683 | },
1684 | {
1685 | "cell_type": "code",
1686 | "execution_count": 60,
1687 | "metadata": {
1688 | "collapsed": false
1689 | },
1690 | "outputs": [
1691 | {
1692 | "name": "stdout",
1693 | "output_type": "stream",
1694 | "text": [
1695 | "value = 1.000000\n"
1696 | ]
1697 | }
1698 | ],
1699 | "source": [
1700 | "print(\"value = %f\" % 1.0) # we can use C-style string formatting"
1701 | ]
1702 | },
1703 | {
1704 | "cell_type": "code",
1705 | "execution_count": 61,
1706 | "metadata": {
1707 | "collapsed": false
1708 | },
1709 | "outputs": [
1710 | {
1711 | "name": "stdout",
1712 | "output_type": "stream",
1713 | "text": [
1714 | "value1 = 3.14. value2 = 1\n"
1715 | ]
1716 | }
1717 | ],
1718 | "source": [
1719 | "# this formatting creates a string\n",
1720 | "s2 = \"value1 = %.2f. value2 = %d\" % (3.1415, 1.5)\n",
1721 | "\n",
1722 | "print(s2)"
1723 | ]
1724 | },
1725 | {
1726 | "cell_type": "code",
1727 | "execution_count": 62,
1728 | "metadata": {
1729 | "collapsed": false
1730 | },
1731 | "outputs": [
1732 | {
1733 | "name": "stdout",
1734 | "output_type": "stream",
1735 | "text": [
1736 | "value1 = 3.1415, value2 = 1.5\n"
1737 | ]
1738 | }
1739 | ],
1740 | "source": [
1741 | "# alternative, more intuitive way of formatting a string \n",
1742 | "s3 = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)\n",
1743 | "\n",
1744 | "print(s3)"
1745 | ]
1746 | },
1747 | {
1748 | "cell_type": "markdown",
1749 | "metadata": {},
1750 | "source": [
1751 | "### List"
1752 | ]
1753 | },
1754 | {
1755 | "cell_type": "markdown",
1756 | "metadata": {},
1757 | "source": [
1758 | "Lists are very similar to strings, except that each element can be of any type.\n",
1759 | "\n",
1760 | "The syntax for creating lists in Python is `[...]`:"
1761 | ]
1762 | },
1763 | {
1764 | "cell_type": "code",
1765 | "execution_count": 63,
1766 | "metadata": {
1767 | "collapsed": false
1768 | },
1769 | "outputs": [
1770 | {
1771 | "name": "stdout",
1772 | "output_type": "stream",
1773 | "text": [
1774 | "\n",
1775 | "[1, 2, 3, 4]\n"
1776 | ]
1777 | }
1778 | ],
1779 | "source": [
1780 | "l = [1,2,3,4]\n",
1781 | "\n",
1782 | "print(type(l))\n",
1783 | "print(l)"
1784 | ]
1785 | },
1786 | {
1787 | "cell_type": "markdown",
1788 | "metadata": {},
1789 | "source": [
1790 | "We can use the same slicing techniques to manipulate lists as we could use on strings:"
1791 | ]
1792 | },
1793 | {
1794 | "cell_type": "code",
1795 | "execution_count": 64,
1796 | "metadata": {
1797 | "collapsed": false
1798 | },
1799 | "outputs": [
1800 | {
1801 | "name": "stdout",
1802 | "output_type": "stream",
1803 | "text": [
1804 | "[1, 2, 3, 4]\n",
1805 | "[2, 3]\n",
1806 | "[1, 3]\n"
1807 | ]
1808 | }
1809 | ],
1810 | "source": [
1811 | "print(l)\n",
1812 | "\n",
1813 | "print(l[1:3])\n",
1814 | "\n",
1815 | "print(l[::2])"
1816 | ]
1817 | },
1818 | {
1819 | "cell_type": "markdown",
1820 | "metadata": {},
1821 | "source": [
1822 | "**Heads up MATLAB users:** Indexing starts at 0!"
1823 | ]
1824 | },
1825 | {
1826 | "cell_type": "code",
1827 | "execution_count": 65,
1828 | "metadata": {
1829 | "collapsed": false
1830 | },
1831 | "outputs": [
1832 | {
1833 | "data": {
1834 | "text/plain": [
1835 | "1"
1836 | ]
1837 | },
1838 | "execution_count": 65,
1839 | "metadata": {},
1840 | "output_type": "execute_result"
1841 | }
1842 | ],
1843 | "source": [
1844 | "l[0]"
1845 | ]
1846 | },
1847 | {
1848 | "cell_type": "markdown",
1849 | "metadata": {},
1850 | "source": [
1851 | "Elements in a list do not all have to be of the same type:"
1852 | ]
1853 | },
1854 | {
1855 | "cell_type": "code",
1856 | "execution_count": 66,
1857 | "metadata": {
1858 | "collapsed": false
1859 | },
1860 | "outputs": [
1861 | {
1862 | "name": "stdout",
1863 | "output_type": "stream",
1864 | "text": [
1865 | "[1, 'a', 1.0, (1-1j)]\n"
1866 | ]
1867 | }
1868 | ],
1869 | "source": [
1870 | "l = [1, 'a', 1.0, 1-1j]\n",
1871 | "\n",
1872 | "print(l)"
1873 | ]
1874 | },
1875 | {
1876 | "cell_type": "markdown",
1877 | "metadata": {},
1878 | "source": [
1879 | "Python lists can be inhomogeneous and arbitrarily nested:"
1880 | ]
1881 | },
1882 | {
1883 | "cell_type": "code",
1884 | "execution_count": 67,
1885 | "metadata": {
1886 | "collapsed": false
1887 | },
1888 | "outputs": [
1889 | {
1890 | "data": {
1891 | "text/plain": [
1892 | "[1, [2, [3, [4, [5]]]]]"
1893 | ]
1894 | },
1895 | "execution_count": 67,
1896 | "metadata": {},
1897 | "output_type": "execute_result"
1898 | }
1899 | ],
1900 | "source": [
1901 | "nested_list = [1, [2, [3, [4, [5]]]]]\n",
1902 | "\n",
1903 | "nested_list"
1904 | ]
1905 | },
1906 | {
1907 | "cell_type": "markdown",
1908 | "metadata": {},
1909 | "source": [
1910 | "Lists play a very important role in Python. For example they are used in loops and other flow control structures (discussed below). There are a number of convenient functions for generating lists of various types, for example the `range` function:"
1911 | ]
1912 | },
1913 | {
1914 | "cell_type": "code",
1915 | "execution_count": 68,
1916 | "metadata": {
1917 | "collapsed": false
1918 | },
1919 | "outputs": [
1920 | {
1921 | "data": {
1922 | "text/plain": [
1923 | "[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]"
1924 | ]
1925 | },
1926 | "execution_count": 68,
1927 | "metadata": {},
1928 | "output_type": "execute_result"
1929 | }
1930 | ],
1931 | "source": [
1932 | "start = 10\n",
1933 | "stop = 30\n",
1934 | "step = 2\n",
1935 | "\n",
1936 | "range(start, stop, step)"
1937 | ]
1938 | },
1939 | {
1940 | "cell_type": "code",
1941 | "execution_count": 69,
1942 | "metadata": {
1943 | "collapsed": false
1944 | },
1945 | "outputs": [
1946 | {
1947 | "data": {
1948 | "text/plain": [
1949 | "[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]"
1950 | ]
1951 | },
1952 | "execution_count": 69,
1953 | "metadata": {},
1954 | "output_type": "execute_result"
1955 | }
1956 | ],
1957 | "source": [
1958 | "# in python 3 range generates an iterator, which can be converted to a list using 'list(...)'.\n",
1959 | "# It has no effect in python 2\n",
1960 | "list(range(start, stop, step))"
1961 | ]
1962 | },
1963 | {
1964 | "cell_type": "code",
1965 | "execution_count": 70,
1966 | "metadata": {
1967 | "collapsed": false
1968 | },
1969 | "outputs": [
1970 | {
1971 | "data": {
1972 | "text/plain": [
1973 | "[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
1974 | ]
1975 | },
1976 | "execution_count": 70,
1977 | "metadata": {},
1978 | "output_type": "execute_result"
1979 | }
1980 | ],
1981 | "source": [
1982 | "list(range(-10, 10))"
1983 | ]
1984 | },
1985 | {
1986 | "cell_type": "code",
1987 | "execution_count": 71,
1988 | "metadata": {
1989 | "collapsed": false
1990 | },
1991 | "outputs": [
1992 | {
1993 | "data": {
1994 | "text/plain": [
1995 | "'Hello world'"
1996 | ]
1997 | },
1998 | "execution_count": 71,
1999 | "metadata": {},
2000 | "output_type": "execute_result"
2001 | }
2002 | ],
2003 | "source": [
2004 | "s"
2005 | ]
2006 | },
2007 | {
2008 | "cell_type": "code",
2009 | "execution_count": 72,
2010 | "metadata": {
2011 | "collapsed": false
2012 | },
2013 | "outputs": [
2014 | {
2015 | "data": {
2016 | "text/plain": [
2017 | "['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']"
2018 | ]
2019 | },
2020 | "execution_count": 72,
2021 | "metadata": {},
2022 | "output_type": "execute_result"
2023 | }
2024 | ],
2025 | "source": [
2026 | "# convert a string to a list by type casting:\n",
2027 | "s2 = list(s)\n",
2028 | "\n",
2029 | "s2"
2030 | ]
2031 | },
2032 | {
2033 | "cell_type": "code",
2034 | "execution_count": 73,
2035 | "metadata": {
2036 | "collapsed": false
2037 | },
2038 | "outputs": [
2039 | {
2040 | "name": "stdout",
2041 | "output_type": "stream",
2042 | "text": [
2043 | "[' ', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']\n"
2044 | ]
2045 | }
2046 | ],
2047 | "source": [
2048 | "# sorting lists\n",
2049 | "s2.sort()\n",
2050 | "\n",
2051 | "print(s2)"
2052 | ]
2053 | },
2054 | {
2055 | "cell_type": "markdown",
2056 | "metadata": {},
2057 | "source": [
2058 | "#### Adding, inserting, modifying, and removing elements from lists"
2059 | ]
2060 | },
2061 | {
2062 | "cell_type": "code",
2063 | "execution_count": 74,
2064 | "metadata": {
2065 | "collapsed": false
2066 | },
2067 | "outputs": [
2068 | {
2069 | "name": "stdout",
2070 | "output_type": "stream",
2071 | "text": [
2072 | "['A', 'd', 'd']\n"
2073 | ]
2074 | }
2075 | ],
2076 | "source": [
2077 | "# create a new empty list\n",
2078 | "l = []\n",
2079 | "\n",
2080 | "# add an elements using `append`\n",
2081 | "l.append(\"A\")\n",
2082 | "l.append(\"d\")\n",
2083 | "l.append(\"d\")\n",
2084 | "\n",
2085 | "print(l)"
2086 | ]
2087 | },
2088 | {
2089 | "cell_type": "markdown",
2090 | "metadata": {},
2091 | "source": [
2092 | "We can modify lists by assigning new values to elements in the list. In technical jargon, lists are *mutable*."
2093 | ]
2094 | },
2095 | {
2096 | "cell_type": "code",
2097 | "execution_count": 75,
2098 | "metadata": {
2099 | "collapsed": false
2100 | },
2101 | "outputs": [
2102 | {
2103 | "name": "stdout",
2104 | "output_type": "stream",
2105 | "text": [
2106 | "['A', 'p', 'p']\n"
2107 | ]
2108 | }
2109 | ],
2110 | "source": [
2111 | "l[1] = \"p\"\n",
2112 | "l[2] = \"p\"\n",
2113 | "\n",
2114 | "print(l)"
2115 | ]
2116 | },
2117 | {
2118 | "cell_type": "code",
2119 | "execution_count": 76,
2120 | "metadata": {
2121 | "collapsed": false
2122 | },
2123 | "outputs": [
2124 | {
2125 | "name": "stdout",
2126 | "output_type": "stream",
2127 | "text": [
2128 | "['A', 'd', 'd']\n"
2129 | ]
2130 | }
2131 | ],
2132 | "source": [
2133 | "l[1:3] = [\"d\", \"d\"]\n",
2134 | "\n",
2135 | "print(l)"
2136 | ]
2137 | },
2138 | {
2139 | "cell_type": "markdown",
2140 | "metadata": {},
2141 | "source": [
2142 | "Insert an element at an specific index using `insert`"
2143 | ]
2144 | },
2145 | {
2146 | "cell_type": "code",
2147 | "execution_count": 77,
2148 | "metadata": {
2149 | "collapsed": false
2150 | },
2151 | "outputs": [
2152 | {
2153 | "name": "stdout",
2154 | "output_type": "stream",
2155 | "text": [
2156 | "['i', 'n', 's', 'e', 'r', 't', 'A', 'd', 'd']\n"
2157 | ]
2158 | }
2159 | ],
2160 | "source": [
2161 | "l.insert(0, \"i\")\n",
2162 | "l.insert(1, \"n\")\n",
2163 | "l.insert(2, \"s\")\n",
2164 | "l.insert(3, \"e\")\n",
2165 | "l.insert(4, \"r\")\n",
2166 | "l.insert(5, \"t\")\n",
2167 | "\n",
2168 | "print(l)"
2169 | ]
2170 | },
2171 | {
2172 | "cell_type": "markdown",
2173 | "metadata": {},
2174 | "source": [
2175 | "Remove first element with specific value using 'remove'"
2176 | ]
2177 | },
2178 | {
2179 | "cell_type": "code",
2180 | "execution_count": 78,
2181 | "metadata": {
2182 | "collapsed": false
2183 | },
2184 | "outputs": [
2185 | {
2186 | "name": "stdout",
2187 | "output_type": "stream",
2188 | "text": [
2189 | "['i', 'n', 's', 'e', 'r', 't', 'd', 'd']\n"
2190 | ]
2191 | }
2192 | ],
2193 | "source": [
2194 | "l.remove(\"A\")\n",
2195 | "\n",
2196 | "print(l)"
2197 | ]
2198 | },
2199 | {
2200 | "cell_type": "markdown",
2201 | "metadata": {},
2202 | "source": [
2203 | "Remove an element at a specific location using `del`:"
2204 | ]
2205 | },
2206 | {
2207 | "cell_type": "code",
2208 | "execution_count": 79,
2209 | "metadata": {
2210 | "collapsed": false
2211 | },
2212 | "outputs": [
2213 | {
2214 | "name": "stdout",
2215 | "output_type": "stream",
2216 | "text": [
2217 | "['i', 'n', 's', 'e', 'r', 't']\n"
2218 | ]
2219 | }
2220 | ],
2221 | "source": [
2222 | "del l[7]\n",
2223 | "del l[6]\n",
2224 | "\n",
2225 | "print(l)"
2226 | ]
2227 | },
2228 | {
2229 | "cell_type": "markdown",
2230 | "metadata": {},
2231 | "source": [
2232 | "See `help(list)` for more details, or read the online documentation "
2233 | ]
2234 | },
2235 | {
2236 | "cell_type": "markdown",
2237 | "metadata": {},
2238 | "source": [
2239 | "### Tuples"
2240 | ]
2241 | },
2242 | {
2243 | "cell_type": "markdown",
2244 | "metadata": {},
2245 | "source": [
2246 | "Tuples are like lists, except that they cannot be modified once created, that is they are *immutable*. \n",
2247 | "\n",
2248 | "In Python, tuples are created using the syntax `(..., ..., ...)`, or even `..., ...`:"
2249 | ]
2250 | },
2251 | {
2252 | "cell_type": "code",
2253 | "execution_count": 80,
2254 | "metadata": {
2255 | "collapsed": false
2256 | },
2257 | "outputs": [
2258 | {
2259 | "name": "stdout",
2260 | "output_type": "stream",
2261 | "text": [
2262 | "((10, 20), )\n"
2263 | ]
2264 | }
2265 | ],
2266 | "source": [
2267 | "point = (10, 20)\n",
2268 | "\n",
2269 | "print(point, type(point))"
2270 | ]
2271 | },
2272 | {
2273 | "cell_type": "code",
2274 | "execution_count": 81,
2275 | "metadata": {
2276 | "collapsed": false
2277 | },
2278 | "outputs": [
2279 | {
2280 | "name": "stdout",
2281 | "output_type": "stream",
2282 | "text": [
2283 | "((10, 20), )\n"
2284 | ]
2285 | }
2286 | ],
2287 | "source": [
2288 | "point = 10, 20\n",
2289 | "\n",
2290 | "print(point, type(point))"
2291 | ]
2292 | },
2293 | {
2294 | "cell_type": "markdown",
2295 | "metadata": {},
2296 | "source": [
2297 | "We can unpack a tuple by assigning it to a comma-separated list of variables:"
2298 | ]
2299 | },
2300 | {
2301 | "cell_type": "code",
2302 | "execution_count": 82,
2303 | "metadata": {
2304 | "collapsed": false
2305 | },
2306 | "outputs": [
2307 | {
2308 | "name": "stdout",
2309 | "output_type": "stream",
2310 | "text": [
2311 | "('x =', 10)\n",
2312 | "('y =', 20)\n"
2313 | ]
2314 | }
2315 | ],
2316 | "source": [
2317 | "x, y = point\n",
2318 | "\n",
2319 | "print(\"x =\", x)\n",
2320 | "print(\"y =\", y)"
2321 | ]
2322 | },
2323 | {
2324 | "cell_type": "markdown",
2325 | "metadata": {},
2326 | "source": [
2327 | "If we try to assign a new value to an element in a tuple we get an error:"
2328 | ]
2329 | },
2330 | {
2331 | "cell_type": "code",
2332 | "execution_count": 83,
2333 | "metadata": {
2334 | "collapsed": false
2335 | },
2336 | "outputs": [
2337 | {
2338 | "ename": "TypeError",
2339 | "evalue": "'tuple' object does not support item assignment",
2340 | "output_type": "error",
2341 | "traceback": [
2342 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
2343 | "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
2344 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mpoint\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m20\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
2345 | "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"
2346 | ]
2347 | }
2348 | ],
2349 | "source": [
2350 | "point[0] = 20"
2351 | ]
2352 | },
2353 | {
2354 | "cell_type": "markdown",
2355 | "metadata": {},
2356 | "source": [
2357 | "### Dictionaries"
2358 | ]
2359 | },
2360 | {
2361 | "cell_type": "markdown",
2362 | "metadata": {},
2363 | "source": [
2364 | "Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is `{key1 : value1, ...}`:"
2365 | ]
2366 | },
2367 | {
2368 | "cell_type": "code",
2369 | "execution_count": 84,
2370 | "metadata": {
2371 | "collapsed": false
2372 | },
2373 | "outputs": [
2374 | {
2375 | "name": "stdout",
2376 | "output_type": "stream",
2377 | "text": [
2378 | "\n",
2379 | "{'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}\n"
2380 | ]
2381 | }
2382 | ],
2383 | "source": [
2384 | "params = {\"parameter1\" : 1.0,\n",
2385 | " \"parameter2\" : 2.0,\n",
2386 | " \"parameter3\" : 3.0,}\n",
2387 | "\n",
2388 | "print(type(params))\n",
2389 | "print(params)"
2390 | ]
2391 | },
2392 | {
2393 | "cell_type": "code",
2394 | "execution_count": 85,
2395 | "metadata": {
2396 | "collapsed": false
2397 | },
2398 | "outputs": [
2399 | {
2400 | "name": "stdout",
2401 | "output_type": "stream",
2402 | "text": [
2403 | "parameter1 = 1.0\n",
2404 | "parameter2 = 2.0\n",
2405 | "parameter3 = 3.0\n"
2406 | ]
2407 | }
2408 | ],
2409 | "source": [
2410 | "print(\"parameter1 = \" + str(params[\"parameter1\"]))\n",
2411 | "print(\"parameter2 = \" + str(params[\"parameter2\"]))\n",
2412 | "print(\"parameter3 = \" + str(params[\"parameter3\"]))"
2413 | ]
2414 | },
2415 | {
2416 | "cell_type": "code",
2417 | "execution_count": 86,
2418 | "metadata": {
2419 | "collapsed": false
2420 | },
2421 | "outputs": [
2422 | {
2423 | "name": "stdout",
2424 | "output_type": "stream",
2425 | "text": [
2426 | "parameter1 = A\n",
2427 | "parameter2 = B\n",
2428 | "parameter3 = 3.0\n",
2429 | "parameter4 = D\n"
2430 | ]
2431 | }
2432 | ],
2433 | "source": [
2434 | "params[\"parameter1\"] = \"A\"\n",
2435 | "params[\"parameter2\"] = \"B\"\n",
2436 | "\n",
2437 | "# add a new entry\n",
2438 | "params[\"parameter4\"] = \"D\"\n",
2439 | "\n",
2440 | "print(\"parameter1 = \" + str(params[\"parameter1\"]))\n",
2441 | "print(\"parameter2 = \" + str(params[\"parameter2\"]))\n",
2442 | "print(\"parameter3 = \" + str(params[\"parameter3\"]))\n",
2443 | "print(\"parameter4 = \" + str(params[\"parameter4\"]))"
2444 | ]
2445 | },
2446 | {
2447 | "cell_type": "markdown",
2448 | "metadata": {},
2449 | "source": [
2450 | "## Control Flow"
2451 | ]
2452 | },
2453 | {
2454 | "cell_type": "markdown",
2455 | "metadata": {},
2456 | "source": [
2457 | "### Conditional statements: if, elif, else"
2458 | ]
2459 | },
2460 | {
2461 | "cell_type": "markdown",
2462 | "metadata": {},
2463 | "source": [
2464 | "The Python syntax for conditional execution of code uses the keywords `if`, `elif` (else if), `else`:"
2465 | ]
2466 | },
2467 | {
2468 | "cell_type": "code",
2469 | "execution_count": 87,
2470 | "metadata": {
2471 | "collapsed": false
2472 | },
2473 | "outputs": [
2474 | {
2475 | "name": "stdout",
2476 | "output_type": "stream",
2477 | "text": [
2478 | "statement1 and statement2 are False\n"
2479 | ]
2480 | }
2481 | ],
2482 | "source": [
2483 | "statement1 = False\n",
2484 | "statement2 = False\n",
2485 | "\n",
2486 | "if statement1:\n",
2487 | " print(\"statement1 is True\")\n",
2488 | " \n",
2489 | "elif statement2:\n",
2490 | " print(\"statement2 is True\")\n",
2491 | " \n",
2492 | "else:\n",
2493 | " print(\"statement1 and statement2 are False\")"
2494 | ]
2495 | },
2496 | {
2497 | "cell_type": "markdown",
2498 | "metadata": {},
2499 | "source": [
2500 | "For the first time, here we encounter a peculiar and unusual aspect of the Python programming language: Program blocks are defined by their indentation level. \n",
2501 | "\n",
2502 | "Compare to the equivalent C code:\n",
2503 | "\n",
2504 | " if (statement1)\n",
2505 | " {\n",
2506 | " printf(\"statement1 is True\\n\");\n",
2507 | " }\n",
2508 | " else if (statement2)\n",
2509 | " {\n",
2510 | " printf(\"statement2 is True\\n\");\n",
2511 | " }\n",
2512 | " else\n",
2513 | " {\n",
2514 | " printf(\"statement1 and statement2 are False\\n\");\n",
2515 | " }\n",
2516 | "\n",
2517 | "In C blocks are defined by the enclosing curly brackets `{` and `}`. And the level of indentation (white space before the code statements) does not matter (completely optional). \n",
2518 | "\n",
2519 | "But in Python, the extent of a code block is defined by the indentation level (usually a tab or say four white spaces). This means that we have to be careful to indent our code correctly, or else we will get syntax errors. "
2520 | ]
2521 | },
2522 | {
2523 | "cell_type": "markdown",
2524 | "metadata": {},
2525 | "source": [
2526 | "#### Examples:"
2527 | ]
2528 | },
2529 | {
2530 | "cell_type": "code",
2531 | "execution_count": 88,
2532 | "metadata": {
2533 | "collapsed": false
2534 | },
2535 | "outputs": [
2536 | {
2537 | "name": "stdout",
2538 | "output_type": "stream",
2539 | "text": [
2540 | "both statement1 and statement2 are True\n"
2541 | ]
2542 | }
2543 | ],
2544 | "source": [
2545 | "statement1 = statement2 = True\n",
2546 | "\n",
2547 | "if statement1:\n",
2548 | " if statement2:\n",
2549 | " print(\"both statement1 and statement2 are True\")"
2550 | ]
2551 | },
2552 | {
2553 | "cell_type": "code",
2554 | "execution_count": 89,
2555 | "metadata": {
2556 | "collapsed": false
2557 | },
2558 | "outputs": [
2559 | {
2560 | "ename": "IndentationError",
2561 | "evalue": "expected an indented block (, line 4)",
2562 | "output_type": "error",
2563 | "traceback": [
2564 | "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m print(\"both statement1 and statement2 are True\") # this line is not properly indented\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n"
2565 | ]
2566 | }
2567 | ],
2568 | "source": [
2569 | "# Bad indentation!\n",
2570 | "if statement1:\n",
2571 | " if statement2:\n",
2572 | " print(\"both statement1 and statement2 are True\") # this line is not properly indented"
2573 | ]
2574 | },
2575 | {
2576 | "cell_type": "code",
2577 | "execution_count": 90,
2578 | "metadata": {
2579 | "collapsed": false
2580 | },
2581 | "outputs": [],
2582 | "source": [
2583 | "statement1 = False \n",
2584 | "\n",
2585 | "if statement1:\n",
2586 | " print(\"printed if statement1 is True\")\n",
2587 | " \n",
2588 | " print(\"still inside the if block\")"
2589 | ]
2590 | },
2591 | {
2592 | "cell_type": "code",
2593 | "execution_count": 91,
2594 | "metadata": {
2595 | "collapsed": false
2596 | },
2597 | "outputs": [
2598 | {
2599 | "name": "stdout",
2600 | "output_type": "stream",
2601 | "text": [
2602 | "now outside the if block\n"
2603 | ]
2604 | }
2605 | ],
2606 | "source": [
2607 | "if statement1:\n",
2608 | " print(\"printed if statement1 is True\")\n",
2609 | " \n",
2610 | "print(\"now outside the if block\")"
2611 | ]
2612 | },
2613 | {
2614 | "cell_type": "markdown",
2615 | "metadata": {},
2616 | "source": [
2617 | "## Loops"
2618 | ]
2619 | },
2620 | {
2621 | "cell_type": "markdown",
2622 | "metadata": {},
2623 | "source": [
2624 | "In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. The basic syntax is:"
2625 | ]
2626 | },
2627 | {
2628 | "cell_type": "markdown",
2629 | "metadata": {},
2630 | "source": [
2631 | "### **`for` loops**:"
2632 | ]
2633 | },
2634 | {
2635 | "cell_type": "code",
2636 | "execution_count": 92,
2637 | "metadata": {
2638 | "collapsed": false
2639 | },
2640 | "outputs": [
2641 | {
2642 | "name": "stdout",
2643 | "output_type": "stream",
2644 | "text": [
2645 | "1\n",
2646 | "2\n",
2647 | "3\n"
2648 | ]
2649 | }
2650 | ],
2651 | "source": [
2652 | "for x in [1,2,3]:\n",
2653 | " print(x)"
2654 | ]
2655 | },
2656 | {
2657 | "cell_type": "markdown",
2658 | "metadata": {},
2659 | "source": [
2660 | "The `for` loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the `for` loop. For example:"
2661 | ]
2662 | },
2663 | {
2664 | "cell_type": "code",
2665 | "execution_count": 93,
2666 | "metadata": {
2667 | "collapsed": false
2668 | },
2669 | "outputs": [
2670 | {
2671 | "name": "stdout",
2672 | "output_type": "stream",
2673 | "text": [
2674 | "0\n",
2675 | "1\n",
2676 | "2\n",
2677 | "3\n"
2678 | ]
2679 | }
2680 | ],
2681 | "source": [
2682 | "for x in range(4): # by default range start at 0\n",
2683 | " print(x)"
2684 | ]
2685 | },
2686 | {
2687 | "cell_type": "markdown",
2688 | "metadata": {},
2689 | "source": [
2690 | "Note: `range(4)` does not include 4 !"
2691 | ]
2692 | },
2693 | {
2694 | "cell_type": "code",
2695 | "execution_count": 94,
2696 | "metadata": {
2697 | "collapsed": false
2698 | },
2699 | "outputs": [
2700 | {
2701 | "name": "stdout",
2702 | "output_type": "stream",
2703 | "text": [
2704 | "-3\n",
2705 | "-2\n",
2706 | "-1\n",
2707 | "0\n",
2708 | "1\n",
2709 | "2\n"
2710 | ]
2711 | }
2712 | ],
2713 | "source": [
2714 | "for x in range(-3,3):\n",
2715 | " print(x)"
2716 | ]
2717 | },
2718 | {
2719 | "cell_type": "code",
2720 | "execution_count": 95,
2721 | "metadata": {
2722 | "collapsed": false
2723 | },
2724 | "outputs": [
2725 | {
2726 | "name": "stdout",
2727 | "output_type": "stream",
2728 | "text": [
2729 | "scientific\n",
2730 | "computing\n",
2731 | "with\n",
2732 | "python\n"
2733 | ]
2734 | }
2735 | ],
2736 | "source": [
2737 | "for word in [\"scientific\", \"computing\", \"with\", \"python\"]:\n",
2738 | " print(word)"
2739 | ]
2740 | },
2741 | {
2742 | "cell_type": "markdown",
2743 | "metadata": {},
2744 | "source": [
2745 | "To iterate over key-value pairs of a dictionary:"
2746 | ]
2747 | },
2748 | {
2749 | "cell_type": "code",
2750 | "execution_count": 96,
2751 | "metadata": {
2752 | "collapsed": false
2753 | },
2754 | "outputs": [
2755 | {
2756 | "name": "stdout",
2757 | "output_type": "stream",
2758 | "text": [
2759 | "parameter4 = D\n",
2760 | "parameter1 = A\n",
2761 | "parameter3 = 3.0\n",
2762 | "parameter2 = B\n"
2763 | ]
2764 | }
2765 | ],
2766 | "source": [
2767 | "for key, value in params.items():\n",
2768 | " print(key + \" = \" + str(value))"
2769 | ]
2770 | },
2771 | {
2772 | "cell_type": "markdown",
2773 | "metadata": {},
2774 | "source": [
2775 | "Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the `enumerate` function for this:"
2776 | ]
2777 | },
2778 | {
2779 | "cell_type": "code",
2780 | "execution_count": 97,
2781 | "metadata": {
2782 | "collapsed": false
2783 | },
2784 | "outputs": [
2785 | {
2786 | "name": "stdout",
2787 | "output_type": "stream",
2788 | "text": [
2789 | "(0, -3)\n",
2790 | "(1, -2)\n",
2791 | "(2, -1)\n",
2792 | "(3, 0)\n",
2793 | "(4, 1)\n",
2794 | "(5, 2)\n"
2795 | ]
2796 | }
2797 | ],
2798 | "source": [
2799 | "for idx, x in enumerate(range(-3,3)):\n",
2800 | " print(idx, x)"
2801 | ]
2802 | },
2803 | {
2804 | "cell_type": "markdown",
2805 | "metadata": {},
2806 | "source": [
2807 | "### List comprehensions: Creating lists using `for` loops:"
2808 | ]
2809 | },
2810 | {
2811 | "cell_type": "markdown",
2812 | "metadata": {},
2813 | "source": [
2814 | "A convenient and compact way to initialize lists:"
2815 | ]
2816 | },
2817 | {
2818 | "cell_type": "code",
2819 | "execution_count": 98,
2820 | "metadata": {
2821 | "collapsed": false
2822 | },
2823 | "outputs": [
2824 | {
2825 | "name": "stdout",
2826 | "output_type": "stream",
2827 | "text": [
2828 | "[0, 1, 4, 9, 16]\n"
2829 | ]
2830 | }
2831 | ],
2832 | "source": [
2833 | "l1 = [x**2 for x in range(0,5)]\n",
2834 | "\n",
2835 | "print(l1)"
2836 | ]
2837 | },
2838 | {
2839 | "cell_type": "markdown",
2840 | "metadata": {},
2841 | "source": [
2842 | "### `while` loops:"
2843 | ]
2844 | },
2845 | {
2846 | "cell_type": "code",
2847 | "execution_count": 99,
2848 | "metadata": {
2849 | "collapsed": false
2850 | },
2851 | "outputs": [
2852 | {
2853 | "name": "stdout",
2854 | "output_type": "stream",
2855 | "text": [
2856 | "0\n",
2857 | "1\n",
2858 | "2\n",
2859 | "3\n",
2860 | "4\n",
2861 | "done\n"
2862 | ]
2863 | }
2864 | ],
2865 | "source": [
2866 | "i = 0\n",
2867 | "\n",
2868 | "while i < 5:\n",
2869 | " print(i)\n",
2870 | " \n",
2871 | " i = i + 1\n",
2872 | " \n",
2873 | "print(\"done\")"
2874 | ]
2875 | },
2876 | {
2877 | "cell_type": "markdown",
2878 | "metadata": {},
2879 | "source": [
2880 | "Note that the `print(\"done\")` statement is not part of the `while` loop body because of the difference in indentation."
2881 | ]
2882 | },
2883 | {
2884 | "cell_type": "markdown",
2885 | "metadata": {},
2886 | "source": [
2887 | "## Functions"
2888 | ]
2889 | },
2890 | {
2891 | "cell_type": "markdown",
2892 | "metadata": {},
2893 | "source": [
2894 | "A function in Python is defined using the keyword `def`, followed by a function name, a signature within parentheses `()`, and a colon `:`. The following code, with one additional level of indentation, is the function body."
2895 | ]
2896 | },
2897 | {
2898 | "cell_type": "code",
2899 | "execution_count": 100,
2900 | "metadata": {
2901 | "collapsed": false
2902 | },
2903 | "outputs": [],
2904 | "source": [
2905 | "def func0(): \n",
2906 | " print(\"test\")"
2907 | ]
2908 | },
2909 | {
2910 | "cell_type": "code",
2911 | "execution_count": 101,
2912 | "metadata": {
2913 | "collapsed": false
2914 | },
2915 | "outputs": [
2916 | {
2917 | "name": "stdout",
2918 | "output_type": "stream",
2919 | "text": [
2920 | "test\n"
2921 | ]
2922 | }
2923 | ],
2924 | "source": [
2925 | "func0()"
2926 | ]
2927 | },
2928 | {
2929 | "cell_type": "markdown",
2930 | "metadata": {},
2931 | "source": [
2932 | "Optionally, but highly recommended, we can define a so called \"docstring\", which is a description of the functions purpose and behavior. The docstring should follow directly after the function definition, before the code in the function body."
2933 | ]
2934 | },
2935 | {
2936 | "cell_type": "code",
2937 | "execution_count": 102,
2938 | "metadata": {
2939 | "collapsed": false
2940 | },
2941 | "outputs": [],
2942 | "source": [
2943 | "def func1(s):\n",
2944 | " \"\"\"\n",
2945 | " Print a string 's' and tell how many characters it has \n",
2946 | " \"\"\"\n",
2947 | " \n",
2948 | " print(s + \" has \" + str(len(s)) + \" characters\")"
2949 | ]
2950 | },
2951 | {
2952 | "cell_type": "code",
2953 | "execution_count": 103,
2954 | "metadata": {
2955 | "collapsed": false
2956 | },
2957 | "outputs": [
2958 | {
2959 | "name": "stdout",
2960 | "output_type": "stream",
2961 | "text": [
2962 | "Help on function func1 in module __main__:\n",
2963 | "\n",
2964 | "func1(s)\n",
2965 | " Print a string 's' and tell how many characters it has\n",
2966 | "\n"
2967 | ]
2968 | }
2969 | ],
2970 | "source": [
2971 | "help(func1)"
2972 | ]
2973 | },
2974 | {
2975 | "cell_type": "code",
2976 | "execution_count": 104,
2977 | "metadata": {
2978 | "collapsed": false
2979 | },
2980 | "outputs": [
2981 | {
2982 | "name": "stdout",
2983 | "output_type": "stream",
2984 | "text": [
2985 | "test has 4 characters\n"
2986 | ]
2987 | }
2988 | ],
2989 | "source": [
2990 | "func1(\"test\")"
2991 | ]
2992 | },
2993 | {
2994 | "cell_type": "markdown",
2995 | "metadata": {},
2996 | "source": [
2997 | "Functions that returns a value use the `return` keyword:"
2998 | ]
2999 | },
3000 | {
3001 | "cell_type": "code",
3002 | "execution_count": 105,
3003 | "metadata": {
3004 | "collapsed": false
3005 | },
3006 | "outputs": [],
3007 | "source": [
3008 | "def square(x):\n",
3009 | " \"\"\"\n",
3010 | " Return the square of x.\n",
3011 | " \"\"\"\n",
3012 | " return x ** 2"
3013 | ]
3014 | },
3015 | {
3016 | "cell_type": "code",
3017 | "execution_count": 106,
3018 | "metadata": {
3019 | "collapsed": false
3020 | },
3021 | "outputs": [
3022 | {
3023 | "data": {
3024 | "text/plain": [
3025 | "16"
3026 | ]
3027 | },
3028 | "execution_count": 106,
3029 | "metadata": {},
3030 | "output_type": "execute_result"
3031 | }
3032 | ],
3033 | "source": [
3034 | "square(4)"
3035 | ]
3036 | },
3037 | {
3038 | "cell_type": "markdown",
3039 | "metadata": {},
3040 | "source": [
3041 | "We can return multiple values from a function using tuples (see above):"
3042 | ]
3043 | },
3044 | {
3045 | "cell_type": "code",
3046 | "execution_count": 107,
3047 | "metadata": {
3048 | "collapsed": false
3049 | },
3050 | "outputs": [],
3051 | "source": [
3052 | "def powers(x):\n",
3053 | " \"\"\"\n",
3054 | " Return a few powers of x.\n",
3055 | " \"\"\"\n",
3056 | " return x ** 2, x ** 3, x ** 4"
3057 | ]
3058 | },
3059 | {
3060 | "cell_type": "code",
3061 | "execution_count": 108,
3062 | "metadata": {
3063 | "collapsed": false
3064 | },
3065 | "outputs": [
3066 | {
3067 | "data": {
3068 | "text/plain": [
3069 | "(9, 27, 81)"
3070 | ]
3071 | },
3072 | "execution_count": 108,
3073 | "metadata": {},
3074 | "output_type": "execute_result"
3075 | }
3076 | ],
3077 | "source": [
3078 | "powers(3)"
3079 | ]
3080 | },
3081 | {
3082 | "cell_type": "code",
3083 | "execution_count": 109,
3084 | "metadata": {
3085 | "collapsed": false
3086 | },
3087 | "outputs": [
3088 | {
3089 | "name": "stdout",
3090 | "output_type": "stream",
3091 | "text": [
3092 | "27\n"
3093 | ]
3094 | }
3095 | ],
3096 | "source": [
3097 | "x2, x3, x4 = powers(3)\n",
3098 | "\n",
3099 | "print(x3)"
3100 | ]
3101 | },
3102 | {
3103 | "cell_type": "markdown",
3104 | "metadata": {},
3105 | "source": [
3106 | "### Default argument and keyword arguments"
3107 | ]
3108 | },
3109 | {
3110 | "cell_type": "markdown",
3111 | "metadata": {},
3112 | "source": [
3113 | "In a definition of a function, we can give default values to the arguments the function takes:"
3114 | ]
3115 | },
3116 | {
3117 | "cell_type": "code",
3118 | "execution_count": 110,
3119 | "metadata": {
3120 | "collapsed": false
3121 | },
3122 | "outputs": [],
3123 | "source": [
3124 | "def myfunc(x, p=2, debug=False):\n",
3125 | " if debug:\n",
3126 | " print(\"evaluating myfunc for x = \" + str(x) + \" using exponent p = \" + str(p))\n",
3127 | " return x**p"
3128 | ]
3129 | },
3130 | {
3131 | "cell_type": "markdown",
3132 | "metadata": {},
3133 | "source": [
3134 | "If we don't provide a value of the `debug` argument when calling the the function `myfunc` it defaults to the value provided in the function definition:"
3135 | ]
3136 | },
3137 | {
3138 | "cell_type": "code",
3139 | "execution_count": 111,
3140 | "metadata": {
3141 | "collapsed": false
3142 | },
3143 | "outputs": [
3144 | {
3145 | "data": {
3146 | "text/plain": [
3147 | "25"
3148 | ]
3149 | },
3150 | "execution_count": 111,
3151 | "metadata": {},
3152 | "output_type": "execute_result"
3153 | }
3154 | ],
3155 | "source": [
3156 | "myfunc(5)"
3157 | ]
3158 | },
3159 | {
3160 | "cell_type": "code",
3161 | "execution_count": 112,
3162 | "metadata": {
3163 | "collapsed": false
3164 | },
3165 | "outputs": [
3166 | {
3167 | "name": "stdout",
3168 | "output_type": "stream",
3169 | "text": [
3170 | "evaluating myfunc for x = 5 using exponent p = 2\n"
3171 | ]
3172 | },
3173 | {
3174 | "data": {
3175 | "text/plain": [
3176 | "25"
3177 | ]
3178 | },
3179 | "execution_count": 112,
3180 | "metadata": {},
3181 | "output_type": "execute_result"
3182 | }
3183 | ],
3184 | "source": [
3185 | "myfunc(5, debug=True)"
3186 | ]
3187 | },
3188 | {
3189 | "cell_type": "markdown",
3190 | "metadata": {},
3191 | "source": [
3192 | "If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called *keyword* arguments, and is often very useful in functions that takes a lot of optional arguments."
3193 | ]
3194 | },
3195 | {
3196 | "cell_type": "code",
3197 | "execution_count": 113,
3198 | "metadata": {
3199 | "collapsed": false
3200 | },
3201 | "outputs": [
3202 | {
3203 | "name": "stdout",
3204 | "output_type": "stream",
3205 | "text": [
3206 | "evaluating myfunc for x = 7 using exponent p = 3\n"
3207 | ]
3208 | },
3209 | {
3210 | "data": {
3211 | "text/plain": [
3212 | "343"
3213 | ]
3214 | },
3215 | "execution_count": 113,
3216 | "metadata": {},
3217 | "output_type": "execute_result"
3218 | }
3219 | ],
3220 | "source": [
3221 | "myfunc(p=3, debug=True, x=7)"
3222 | ]
3223 | },
3224 | {
3225 | "cell_type": "markdown",
3226 | "metadata": {},
3227 | "source": [
3228 | "### Unnamed functions (lambda function)"
3229 | ]
3230 | },
3231 | {
3232 | "cell_type": "markdown",
3233 | "metadata": {},
3234 | "source": [
3235 | "In Python we can also create unnamed functions, using the `lambda` keyword:"
3236 | ]
3237 | },
3238 | {
3239 | "cell_type": "code",
3240 | "execution_count": 114,
3241 | "metadata": {
3242 | "collapsed": false
3243 | },
3244 | "outputs": [],
3245 | "source": [
3246 | "f1 = lambda x: x**2\n",
3247 | " \n",
3248 | "# is equivalent to \n",
3249 | "\n",
3250 | "def f2(x):\n",
3251 | " return x**2"
3252 | ]
3253 | },
3254 | {
3255 | "cell_type": "code",
3256 | "execution_count": 115,
3257 | "metadata": {
3258 | "collapsed": false
3259 | },
3260 | "outputs": [
3261 | {
3262 | "data": {
3263 | "text/plain": [
3264 | "(4, 4)"
3265 | ]
3266 | },
3267 | "execution_count": 115,
3268 | "metadata": {},
3269 | "output_type": "execute_result"
3270 | }
3271 | ],
3272 | "source": [
3273 | "f1(2), f2(2)"
3274 | ]
3275 | },
3276 | {
3277 | "cell_type": "markdown",
3278 | "metadata": {},
3279 | "source": [
3280 | "This technique is useful for example when we want to pass a simple function as an argument to another function, like this:"
3281 | ]
3282 | },
3283 | {
3284 | "cell_type": "code",
3285 | "execution_count": 116,
3286 | "metadata": {
3287 | "collapsed": false
3288 | },
3289 | "outputs": [
3290 | {
3291 | "data": {
3292 | "text/plain": [
3293 | "[9, 4, 1, 0, 1, 4, 9]"
3294 | ]
3295 | },
3296 | "execution_count": 116,
3297 | "metadata": {},
3298 | "output_type": "execute_result"
3299 | }
3300 | ],
3301 | "source": [
3302 | "# map is a built-in python function\n",
3303 | "map(lambda x: x**2, range(-3,4))"
3304 | ]
3305 | },
3306 | {
3307 | "cell_type": "code",
3308 | "execution_count": 117,
3309 | "metadata": {
3310 | "collapsed": false
3311 | },
3312 | "outputs": [
3313 | {
3314 | "data": {
3315 | "text/plain": [
3316 | "[9, 4, 1, 0, 1, 4, 9]"
3317 | ]
3318 | },
3319 | "execution_count": 117,
3320 | "metadata": {},
3321 | "output_type": "execute_result"
3322 | }
3323 | ],
3324 | "source": [
3325 | "# in python 3 we can use `list(...)` to convert the iterator to an explicit list\n",
3326 | "list(map(lambda x: x**2, range(-3,4)))"
3327 | ]
3328 | },
3329 | {
3330 | "cell_type": "markdown",
3331 | "metadata": {},
3332 | "source": [
3333 | "## Classes"
3334 | ]
3335 | },
3336 | {
3337 | "cell_type": "markdown",
3338 | "metadata": {},
3339 | "source": [
3340 | "Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object. \n",
3341 | "\n",
3342 | "In Python a class can contain *attributes* (variables) and *methods* (functions).\n",
3343 | "\n",
3344 | "A class is defined almost like a function, but using the `class` keyword, and the class definition usually contains a number of class method definitions (a function in a class).\n",
3345 | "\n",
3346 | "* Each class method should have an argument `self` as its first argument. This object is a self-reference.\n",
3347 | "\n",
3348 | "* Some class method names have special meaning, for example:\n",
3349 | "\n",
3350 | " * `__init__`: The name of the method that is invoked when the object is first created.\n",
3351 | " * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed.\n",
3352 | " * There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names"
3353 | ]
3354 | },
3355 | {
3356 | "cell_type": "code",
3357 | "execution_count": 118,
3358 | "metadata": {
3359 | "collapsed": false
3360 | },
3361 | "outputs": [],
3362 | "source": [
3363 | "class Point:\n",
3364 | " \"\"\"\n",
3365 | " Simple class for representing a point in a Cartesian coordinate system.\n",
3366 | " \"\"\"\n",
3367 | " \n",
3368 | " def __init__(self, x, y):\n",
3369 | " \"\"\"\n",
3370 | " Create a new Point at x, y.\n",
3371 | " \"\"\"\n",
3372 | " self.x = x\n",
3373 | " self.y = y\n",
3374 | " \n",
3375 | " def translate(self, dx, dy):\n",
3376 | " \"\"\"\n",
3377 | " Translate the point by dx and dy in the x and y direction.\n",
3378 | " \"\"\"\n",
3379 | " self.x += dx\n",
3380 | " self.y += dy\n",
3381 | " \n",
3382 | " def __str__(self):\n",
3383 | " return(\"Point at [%f, %f]\" % (self.x, self.y))"
3384 | ]
3385 | },
3386 | {
3387 | "cell_type": "markdown",
3388 | "metadata": {},
3389 | "source": [
3390 | "To create a new instance of a class:"
3391 | ]
3392 | },
3393 | {
3394 | "cell_type": "code",
3395 | "execution_count": 119,
3396 | "metadata": {
3397 | "collapsed": false
3398 | },
3399 | "outputs": [
3400 | {
3401 | "name": "stdout",
3402 | "output_type": "stream",
3403 | "text": [
3404 | "Point at [0.000000, 0.000000]\n"
3405 | ]
3406 | }
3407 | ],
3408 | "source": [
3409 | "p1 = Point(0, 0) # this will invoke the __init__ method in the Point class\n",
3410 | "\n",
3411 | "print(p1) # this will invoke the __str__ method"
3412 | ]
3413 | },
3414 | {
3415 | "cell_type": "markdown",
3416 | "metadata": {},
3417 | "source": [
3418 | "To invoke a class method in the class instance `p`:"
3419 | ]
3420 | },
3421 | {
3422 | "cell_type": "code",
3423 | "execution_count": 120,
3424 | "metadata": {
3425 | "collapsed": false
3426 | },
3427 | "outputs": [
3428 | {
3429 | "name": "stdout",
3430 | "output_type": "stream",
3431 | "text": [
3432 | "Point at [0.250000, 1.500000]\n",
3433 | "Point at [1.000000, 1.000000]\n"
3434 | ]
3435 | }
3436 | ],
3437 | "source": [
3438 | "p2 = Point(1, 1)\n",
3439 | "\n",
3440 | "p1.translate(0.25, 1.5)\n",
3441 | "\n",
3442 | "print(p1)\n",
3443 | "print(p2)"
3444 | ]
3445 | },
3446 | {
3447 | "cell_type": "markdown",
3448 | "metadata": {},
3449 | "source": [
3450 | "Note that calling class methods can modify the state of that particular class instance, but does not effect other class instances or any global variables.\n",
3451 | "\n",
3452 | "That is one of the nice things about object-oriented design: code such as functions and related variables are grouped in separate and independent entities. "
3453 | ]
3454 | },
3455 | {
3456 | "cell_type": "markdown",
3457 | "metadata": {},
3458 | "source": [
3459 | "## Modules"
3460 | ]
3461 | },
3462 | {
3463 | "cell_type": "markdown",
3464 | "metadata": {},
3465 | "source": [
3466 | "One of the most important concepts in good programming is to reuse code and avoid repetitions.\n",
3467 | "\n",
3468 | "The idea is to write functions and classes with a well-defined purpose and scope, and reuse these instead of repeating similar code in different part of a program (modular programming). The result is usually that readability and maintainability of a program is greatly improved. What this means in practice is that our programs have fewer bugs, are easier to extend and debug/troubleshoot. \n",
3469 | "\n",
3470 | "Python supports modular programming at different levels. Functions and classes are examples of tools for low-level modular programming. Python modules are a higher-level modular programming construct, where we can collect related variables, functions and classes in a module. A python module is defined in a python file (with file-ending `.py`), and it can be made accessible to other Python modules and programs using the `import` statement. \n",
3471 | "\n",
3472 | "Consider the following example: the file `mymodule.py` contains simple example implementations of a variable, function and a class:"
3473 | ]
3474 | },
3475 | {
3476 | "cell_type": "code",
3477 | "execution_count": 121,
3478 | "metadata": {
3479 | "collapsed": false
3480 | },
3481 | "outputs": [
3482 | {
3483 | "name": "stdout",
3484 | "output_type": "stream",
3485 | "text": [
3486 | "Writing mymodule.py\n"
3487 | ]
3488 | }
3489 | ],
3490 | "source": [
3491 | "%%file mymodule.py\n",
3492 | "\"\"\"\n",
3493 | "Example of a python module. Contains a variable called my_variable,\n",
3494 | "a function called my_function, and a class called MyClass.\n",
3495 | "\"\"\"\n",
3496 | "\n",
3497 | "my_variable = 0\n",
3498 | "\n",
3499 | "def my_function():\n",
3500 | " \"\"\"\n",
3501 | " Example function\n",
3502 | " \"\"\"\n",
3503 | " return my_variable\n",
3504 | " \n",
3505 | "class MyClass:\n",
3506 | " \"\"\"\n",
3507 | " Example class.\n",
3508 | " \"\"\"\n",
3509 | "\n",
3510 | " def __init__(self):\n",
3511 | " self.variable = my_variable\n",
3512 | " \n",
3513 | " def set_variable(self, new_value):\n",
3514 | " \"\"\"\n",
3515 | " Set self.variable to a new value\n",
3516 | " \"\"\"\n",
3517 | " self.variable = new_value\n",
3518 | " \n",
3519 | " def get_variable(self):\n",
3520 | " return self.variable"
3521 | ]
3522 | },
3523 | {
3524 | "cell_type": "markdown",
3525 | "metadata": {},
3526 | "source": [
3527 | "We can import the module `mymodule` into our Python program using `import`:"
3528 | ]
3529 | },
3530 | {
3531 | "cell_type": "code",
3532 | "execution_count": 122,
3533 | "metadata": {
3534 | "collapsed": false
3535 | },
3536 | "outputs": [],
3537 | "source": [
3538 | "import mymodule"
3539 | ]
3540 | },
3541 | {
3542 | "cell_type": "markdown",
3543 | "metadata": {},
3544 | "source": [
3545 | "Use `help(module)` to get a summary of what the module provides:"
3546 | ]
3547 | },
3548 | {
3549 | "cell_type": "code",
3550 | "execution_count": 123,
3551 | "metadata": {
3552 | "collapsed": false
3553 | },
3554 | "outputs": [
3555 | {
3556 | "name": "stdout",
3557 | "output_type": "stream",
3558 | "text": [
3559 | "Help on module mymodule:\n",
3560 | "\n",
3561 | "NAME\n",
3562 | " mymodule\n",
3563 | "\n",
3564 | "FILE\n",
3565 | " /Users/rob/Desktop/scientific-python-lectures/mymodule.py\n",
3566 | "\n",
3567 | "DESCRIPTION\n",
3568 | " Example of a python module. Contains a variable called my_variable,\n",
3569 | " a function called my_function, and a class called MyClass.\n",
3570 | "\n",
3571 | "CLASSES\n",
3572 | " MyClass\n",
3573 | " \n",
3574 | " class MyClass\n",
3575 | " | Example class.\n",
3576 | " | \n",
3577 | " | Methods defined here:\n",
3578 | " | \n",
3579 | " | __init__(self)\n",
3580 | " | \n",
3581 | " | get_variable(self)\n",
3582 | " | \n",
3583 | " | set_variable(self, new_value)\n",
3584 | " | Set self.variable to a new value\n",
3585 | "\n",
3586 | "FUNCTIONS\n",
3587 | " my_function()\n",
3588 | " Example function\n",
3589 | "\n",
3590 | "DATA\n",
3591 | " my_variable = 0\n",
3592 | "\n",
3593 | "\n"
3594 | ]
3595 | }
3596 | ],
3597 | "source": [
3598 | "help(mymodule)"
3599 | ]
3600 | },
3601 | {
3602 | "cell_type": "code",
3603 | "execution_count": 124,
3604 | "metadata": {
3605 | "collapsed": false
3606 | },
3607 | "outputs": [
3608 | {
3609 | "data": {
3610 | "text/plain": [
3611 | "0"
3612 | ]
3613 | },
3614 | "execution_count": 124,
3615 | "metadata": {},
3616 | "output_type": "execute_result"
3617 | }
3618 | ],
3619 | "source": [
3620 | "mymodule.my_variable"
3621 | ]
3622 | },
3623 | {
3624 | "cell_type": "code",
3625 | "execution_count": 125,
3626 | "metadata": {
3627 | "collapsed": false
3628 | },
3629 | "outputs": [
3630 | {
3631 | "data": {
3632 | "text/plain": [
3633 | "0"
3634 | ]
3635 | },
3636 | "execution_count": 125,
3637 | "metadata": {},
3638 | "output_type": "execute_result"
3639 | }
3640 | ],
3641 | "source": [
3642 | "mymodule.my_function() "
3643 | ]
3644 | },
3645 | {
3646 | "cell_type": "code",
3647 | "execution_count": 126,
3648 | "metadata": {
3649 | "collapsed": false
3650 | },
3651 | "outputs": [
3652 | {
3653 | "data": {
3654 | "text/plain": [
3655 | "10"
3656 | ]
3657 | },
3658 | "execution_count": 126,
3659 | "metadata": {},
3660 | "output_type": "execute_result"
3661 | }
3662 | ],
3663 | "source": [
3664 | "my_class = mymodule.MyClass() \n",
3665 | "my_class.set_variable(10)\n",
3666 | "my_class.get_variable()"
3667 | ]
3668 | },
3669 | {
3670 | "cell_type": "markdown",
3671 | "metadata": {},
3672 | "source": [
3673 | "If we make changes to the code in `mymodule.py`, we need to reload it using `reload`:"
3674 | ]
3675 | },
3676 | {
3677 | "cell_type": "code",
3678 | "execution_count": 127,
3679 | "metadata": {
3680 | "collapsed": false
3681 | },
3682 | "outputs": [
3683 | {
3684 | "data": {
3685 | "text/plain": [
3686 | ""
3687 | ]
3688 | },
3689 | "execution_count": 127,
3690 | "metadata": {},
3691 | "output_type": "execute_result"
3692 | }
3693 | ],
3694 | "source": [
3695 | "reload(mymodule) # works only in python 2"
3696 | ]
3697 | },
3698 | {
3699 | "cell_type": "markdown",
3700 | "metadata": {},
3701 | "source": [
3702 | "## Exceptions"
3703 | ]
3704 | },
3705 | {
3706 | "cell_type": "markdown",
3707 | "metadata": {},
3708 | "source": [
3709 | "In Python errors are managed with a special language construct called \"Exceptions\". When errors occur exceptions can be raised, which interrupts the normal program flow and fallback to somewhere else in the code where the closest try-except statement is defined."
3710 | ]
3711 | },
3712 | {
3713 | "cell_type": "markdown",
3714 | "metadata": {},
3715 | "source": [
3716 | "To generate an exception we can use the `raise` statement, which takes an argument that must be an instance of the class `BaseException` or a class derived from it. "
3717 | ]
3718 | },
3719 | {
3720 | "cell_type": "code",
3721 | "execution_count": 128,
3722 | "metadata": {
3723 | "collapsed": false
3724 | },
3725 | "outputs": [
3726 | {
3727 | "ename": "Exception",
3728 | "evalue": "description of the error",
3729 | "output_type": "error",
3730 | "traceback": [
3731 | "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
3732 | "\u001b[0;31mException\u001b[0m Traceback (most recent call last)",
3733 | "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"description of the error\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
3734 | "\u001b[0;31mException\u001b[0m: description of the error"
3735 | ]
3736 | }
3737 | ],
3738 | "source": [
3739 | "raise Exception(\"description of the error\")"
3740 | ]
3741 | },
3742 | {
3743 | "cell_type": "markdown",
3744 | "metadata": {},
3745 | "source": [
3746 | "A typical use of exceptions is to abort functions when some error condition occurs, for example:\n",
3747 | "\n",
3748 | " def my_function(arguments):\n",
3749 | " \n",
3750 | " if not verify(arguments):\n",
3751 | " raise Exception(\"Invalid arguments\")\n",
3752 | " \n",
3753 | " # rest of the code goes here"
3754 | ]
3755 | },
3756 | {
3757 | "cell_type": "markdown",
3758 | "metadata": {},
3759 | "source": [
3760 | "To gracefully catch errors that are generated by functions and class methods, or by the Python interpreter itself, use the `try` and `except` statements:\n",
3761 | "\n",
3762 | " try:\n",
3763 | " # normal code goes here\n",
3764 | " except:\n",
3765 | " # code for error handling goes here\n",
3766 | " # this code is not executed unless the code\n",
3767 | " # above generated an error\n",
3768 | "\n",
3769 | "For example:"
3770 | ]
3771 | },
3772 | {
3773 | "cell_type": "code",
3774 | "execution_count": 129,
3775 | "metadata": {
3776 | "collapsed": false
3777 | },
3778 | "outputs": [
3779 | {
3780 | "name": "stdout",
3781 | "output_type": "stream",
3782 | "text": [
3783 | "test\n",
3784 | "Caught an exception\n"
3785 | ]
3786 | }
3787 | ],
3788 | "source": [
3789 | "try:\n",
3790 | " print(\"test\")\n",
3791 | " # generate an error: the variable test is not defined\n",
3792 | " print(test)\n",
3793 | "except:\n",
3794 | " print(\"Caught an exception\")"
3795 | ]
3796 | },
3797 | {
3798 | "cell_type": "markdown",
3799 | "metadata": {},
3800 | "source": [
3801 | "To get information about the error, we can access the `Exception` class instance that describes the exception by using for example:\n",
3802 | "\n",
3803 | " except Exception as e:"
3804 | ]
3805 | },
3806 | {
3807 | "cell_type": "code",
3808 | "execution_count": 130,
3809 | "metadata": {
3810 | "collapsed": false
3811 | },
3812 | "outputs": [
3813 | {
3814 | "name": "stdout",
3815 | "output_type": "stream",
3816 | "text": [
3817 | "test\n",
3818 | "Caught an exception:name 'test' is not defined\n"
3819 | ]
3820 | }
3821 | ],
3822 | "source": [
3823 | "try:\n",
3824 | " print(\"test\")\n",
3825 | " # generate an error: the variable test is not defined\n",
3826 | " print(test)\n",
3827 | "except Exception as e:\n",
3828 | " print(\"Caught an exception:\" + str(e))"
3829 | ]
3830 | },
3831 | {
3832 | "cell_type": "markdown",
3833 | "metadata": {},
3834 | "source": [
3835 | "## Further reading"
3836 | ]
3837 | },
3838 | {
3839 | "cell_type": "markdown",
3840 | "metadata": {},
3841 | "source": [
3842 | "* http://www.python.org - The official web page of the Python programming language.\n",
3843 | "* http://www.python.org/dev/peps/pep-0008 - Style guide for Python programming. Highly recommended. \n",
3844 | "* http://www.greenteapress.com/thinkpython/ - A free book on Python programming.\n",
3845 | "* [Python Essential Reference](http://www.amazon.com/Python-Essential-Reference-4th-Edition/dp/0672329786) - A good reference book on Python programming."
3846 | ]
3847 | },
3848 | {
3849 | "cell_type": "markdown",
3850 | "metadata": {},
3851 | "source": [
3852 | "## Versions"
3853 | ]
3854 | },
3855 | {
3856 | "cell_type": "code",
3857 | "execution_count": 131,
3858 | "metadata": {
3859 | "collapsed": false
3860 | },
3861 | "outputs": [
3862 | {
3863 | "data": {
3864 | "application/json": {
3865 | "Software versions": [
3866 | {
3867 | "module": "Python",
3868 | "version": "2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)]"
3869 | },
3870 | {
3871 | "module": "IPython",
3872 | "version": "3.2.1"
3873 | },
3874 | {
3875 | "module": "OS",
3876 | "version": "Darwin 14.1.0 x86_64 i386 64bit"
3877 | }
3878 | ]
3879 | },
3880 | "text/html": [
3881 | "Software Version Python 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)] IPython 3.2.1 OS Darwin 14.1.0 x86_64 i386 64bit Sat Aug 15 10:51:55 2015 JST
"
3882 | ],
3883 | "text/latex": [
3884 | "\\begin{tabular}{|l|l|}\\hline\n",
3885 | "{\\bf Software} & {\\bf Version} \\\\ \\hline\\hline\n",
3886 | "Python & 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)] \\\\ \\hline\n",
3887 | "IPython & 3.2.1 \\\\ \\hline\n",
3888 | "OS & Darwin 14.1.0 x86\\_64 i386 64bit \\\\ \\hline\n",
3889 | "\\hline \\multicolumn{2}{|l|}{Sat Aug 15 10:51:55 2015 JST} \\\\ \\hline\n",
3890 | "\\end{tabular}\n"
3891 | ],
3892 | "text/plain": [
3893 | "Software versions\n",
3894 | "Python 2.7.10 64bit [GCC 4.2.1 (Apple Inc. build 5577)]\n",
3895 | "IPython 3.2.1\n",
3896 | "OS Darwin 14.1.0 x86_64 i386 64bit\n",
3897 | "Sat Aug 15 10:51:55 2015 JST"
3898 | ]
3899 | },
3900 | "execution_count": 131,
3901 | "metadata": {},
3902 | "output_type": "execute_result"
3903 | }
3904 | ],
3905 | "source": [
3906 | "%load_ext version_information\n",
3907 | "\n",
3908 | "%version_information"
3909 | ]
3910 | }
3911 | ],
3912 | "metadata": {
3913 | "kernelspec": {
3914 | "display_name": "Python 2",
3915 | "language": "python",
3916 | "name": "python2"
3917 | },
3918 | "language_info": {
3919 | "codemirror_mode": {
3920 | "name": "ipython",
3921 | "version": 2
3922 | },
3923 | "file_extension": ".py",
3924 | "mimetype": "text/x-python",
3925 | "name": "python",
3926 | "nbconvert_exporter": "python",
3927 | "pygments_lexer": "ipython2",
3928 | "version": "2.7.10"
3929 | }
3930 | },
3931 | "nbformat": 4,
3932 | "nbformat_minor": 0
3933 | }
3934 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | #
2 | # Build a PDF with all the notebooks
3 | #
4 | TEMPLATE=chapter
5 | NOTEBOOKS=Lecture-0-Scientific-Computing-with-Python.ipynb \
6 | Lecture-1-Introduction-to-Python-Programming.ipynb \
7 | Lecture-2-Numpy.ipynb Lecture-3-Scipy.ipynb \
8 | Lecture-4-Matplotlib.ipynb Lecture-5-Sympy.ipynb \
9 | Lecture-6A-Fortran-and-C.ipynb Lecture-6B-HPC.ipynb \
10 | Lecture-7-Revision-Control-Software.ipynb
11 |
12 | LATEXFILES=$(NOTEBOOKS:.ipynb=.tex)
13 |
14 | .ipynb.tex:
15 | jupyter nbconvert --to latex --template $(TEMPLATE) $<
16 |
17 | all: latexfiles buildpdf
18 |
19 | latexfiles:
20 | for notebook in $(NOTEBOOKS) ; do \
21 | jupyter nbconvert --to latex --template $(TEMPLATE) $$notebook ; \
22 | done
23 |
24 | buildpdf: latexfiles
25 | pdflatex Scientific-Computing-with-Python.tex
26 |
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Lectures on scientific computing with Python
2 | ============================================
3 |
4 |
5 |
6 | A set of lectures on scientific computing with Python, using IPython notebooks.
7 |
8 | To open these notebooks in IPython, download the files to a directory on your computer and from that directory run:
9 |
10 | $ ipython notebook
11 |
12 | This will open a new page in your browser with a list of the available notebooks.
13 |
14 | Should this error `[TerminalIPythonApp] WARNING | File not found: u'notebook'` pop up, please install Jupyter by following the [instructions](http://jupyter.readthedocs.io/en/latest/install.html) and execute the following command to run the notebook:
15 |
16 | $ jupyter notebook
17 |
18 |
19 | Online read-only versions
20 | =========================
21 |
22 | Use the following links:
23 |
24 | * [Lecture-0 Scientific Computing with Python](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-0-Scientific-Computing-with-Python.ipynb)
25 | * [Lecture-1 Introduction to Python Programming](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-1-Introduction-to-Python-Programming.ipynb)
26 | * [Lecture-2 Numpy - multidimensional data arrays](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-2-Numpy.ipynb)
27 | * [Lecture-3 Scipy - Library of scientific algorithms](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-3-Scipy.ipynb)
28 | * [Lecture-4 Matplotlib - 2D and 3D plotting](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-4-Matplotlib.ipynb)
29 | * [Lecture-5 Sympy - Symbolic algebra](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-5-Sympy.ipynb)
30 | * [Lecture-6A C and Fortran integration](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-6A-Fortran-and-C.ipynb)
31 | * [Lecture-6B HPC](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-6B-HPC.ipynb)
32 | * [Lecture-7 Revision Control Software](http://nbviewer.ipython.org/urls/raw.github.com/jrjohansson/scientific-python-lectures/master/Lecture-7-Revision-Control-Software.ipynb)
33 |
34 | A PDF file containing all the lectures is available here: [Scientific Computing with Python](http://raw.github.com/jrjohansson/scientific-python-lectures/master/Scientific-Computing-with-Python.pdf)
35 |
36 |
37 | License
38 | =======
39 |
40 | This work is licensed under a [Creative Commons Attribution 3.0 Unported License.](http://creativecommons.org/licenses/by/3.0/)
41 |
--------------------------------------------------------------------------------
/Scientific-Computing-with-Python.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/Scientific-Computing-with-Python.pdf
--------------------------------------------------------------------------------
/Scientific-Computing-with-Python.tex:
--------------------------------------------------------------------------------
1 | \documentclass{report}
2 | \usepackage{graphicx}
3 | \makeatletter
4 | \def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth
5 | \else\Gin@nat@width\fi}
6 | \makeatother
7 | \let\Oldincludegraphics\includegraphics
8 | \renewcommand{\includegraphics}[1]{\Oldincludegraphics[width=.8\maxwidth]{#1}}
9 | \usepackage{caption}
10 | \DeclareCaptionLabelFormat{nolabel}{}
11 | \captionsetup{labelformat=nolabel}
12 |
13 | \usepackage{adjustbox} % Used to constrain images to a maximum size
14 | \usepackage{xcolor} % Allow colors to be defined
15 | \usepackage{enumerate} % Needed for markdown enumerations to work
16 | \usepackage{geometry} % Used to adjust the document margins
17 | \usepackage{amsmath} % Equations
18 | \usepackage{amssymb} % Equations
19 | \usepackage{textcomp} % defines textquotesingle
20 | \AtBeginDocument{%
21 | \def\PYZsq{\textquotesingle}% Upright quotes in Pygmentized code
22 | }
23 | \usepackage{upquote} % Upright quotes for verbatim code
24 | \usepackage{eurosym} % defines \euro
25 | \usepackage[mathletters]{ucs} % Extended unicode (utf-8) support
26 | \usepackage[utf8x]{inputenc} % Allow utf-8 characters in the tex document
27 | \usepackage{fancyvrb} % verbatim replacement that allows latex
28 | \usepackage{grffile} % extends the file name processing of package graphics
29 | \usepackage{hyperref}
30 | \usepackage{longtable} % longtable support required by pandoc >1.10
31 | \usepackage{booktabs} % table support for pandoc > 1.12.2
32 | \usepackage[normalem]{ulem} % ulem is needed to support strikethroughs (\sout)
33 |
34 | % Colors for the hyperref package
35 | \definecolor{urlcolor}{rgb}{0,.145,.698}
36 | \definecolor{linkcolor}{rgb}{.71,0.21,0.01}
37 | \definecolor{citecolor}{rgb}{.12,.54,.11}
38 |
39 | % ANSI colors
40 | \definecolor{ansi-black}{HTML}{3E424D}
41 | \definecolor{ansi-black-intense}{HTML}{282C36}
42 | \definecolor{ansi-red}{HTML}{E75C58}
43 | \definecolor{ansi-red-intense}{HTML}{B22B31}
44 | \definecolor{ansi-green}{HTML}{00A250}
45 | \definecolor{ansi-green-intense}{HTML}{007427}
46 | \definecolor{ansi-yellow}{HTML}{DDB62B}
47 | \definecolor{ansi-yellow-intense}{HTML}{B27D12}
48 | \definecolor{ansi-blue}{HTML}{208FFB}
49 | \definecolor{ansi-blue-intense}{HTML}{0065CA}
50 | \definecolor{ansi-magenta}{HTML}{D160C4}
51 | \definecolor{ansi-magenta-intense}{HTML}{A03196}
52 | \definecolor{ansi-cyan}{HTML}{60C6C8}
53 | \definecolor{ansi-cyan-intense}{HTML}{258F8F}
54 | \definecolor{ansi-white}{HTML}{C5C1B4}
55 | \definecolor{ansi-white-intense}{HTML}{A1A6B2}
56 |
57 | % commands and environments needed by pandoc snippets
58 | % extracted from the output of `pandoc -s`
59 | \providecommand{\tightlist}{%
60 | \setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}
61 | \DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
62 | % Add ',fontsize=\small' for more characters per line
63 | \newenvironment{Shaded}{}{}
64 | \newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}}
65 | \newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.56,0.13,0.00}{{#1}}}
66 | \newcommand{\DecValTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
67 | \newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
68 | \newcommand{\FloatTok}[1]{\textcolor[rgb]{0.25,0.63,0.44}{{#1}}}
69 | \newcommand{\CharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
70 | \newcommand{\StringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
71 | \newcommand{\CommentTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textit{{#1}}}}
72 | \newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{{#1}}}
73 | \newcommand{\AlertTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
74 | \newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.02,0.16,0.49}{{#1}}}
75 | \newcommand{\RegionMarkerTok}[1]{{#1}}
76 | \newcommand{\ErrorTok}[1]{\textcolor[rgb]{1.00,0.00,0.00}{\textbf{{#1}}}}
77 | \newcommand{\NormalTok}[1]{{#1}}
78 |
79 | % Additional commands for more recent versions of Pandoc
80 | \newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.53,0.00,0.00}{{#1}}}
81 | \newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
82 | \newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.25,0.44,0.63}{{#1}}}
83 | \newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.73,0.40,0.53}{{#1}}}
84 | \newcommand{\ImportTok}[1]{{#1}}
85 | \newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{{#1}}}}
86 | \newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
87 | \newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
88 | \newcommand{\VariableTok}[1]{\textcolor[rgb]{0.10,0.09,0.49}{{#1}}}
89 | \newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.44,0.13}{\textbf{{#1}}}}
90 | \newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.40,0.40,0.40}{{#1}}}
91 | \newcommand{\BuiltInTok}[1]{{#1}}
92 | \newcommand{\ExtensionTok}[1]{{#1}}
93 | \newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.74,0.48,0.00}{{#1}}}
94 | \newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.49,0.56,0.16}{{#1}}}
95 | \newcommand{\InformationTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
96 | \newcommand{\WarningTok}[1]{\textcolor[rgb]{0.38,0.63,0.69}{\textbf{\textit{{#1}}}}}
97 |
98 |
99 | % Define a nice break command that doesn't care if a line doesn't already
100 | % exist.
101 | \def\br{\hspace*{\fill} \\* }
102 | % Math Jax compatability definitions
103 | \def\gt{>}
104 | \def\lt{<}
105 | % Pygments definitions
106 |
107 | \makeatletter
108 | \def\PY@reset{\let\PY@it=\relax \let\PY@bf=\relax%
109 | \let\PY@ul=\relax \let\PY@tc=\relax%
110 | \let\PY@bc=\relax \let\PY@ff=\relax}
111 | \def\PY@tok#1{\csname PY@tok@#1\endcsname}
112 | \def\PY@toks#1+{\ifx\relax#1\empty\else%
113 | \PY@tok{#1}\expandafter\PY@toks\fi}
114 | \def\PY@do#1{\PY@bc{\PY@tc{\PY@ul{%
115 | \PY@it{\PY@bf{\PY@ff{#1}}}}}}}
116 | \def\PY#1#2{\PY@reset\PY@toks#1+\relax+\PY@do{#2}}
117 |
118 | \expandafter\def\csname PY@tok@gd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
119 | \expandafter\def\csname PY@tok@gu\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
120 | \expandafter\def\csname PY@tok@gt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
121 | \expandafter\def\csname PY@tok@gs\endcsname{\let\PY@bf=\textbf}
122 | \expandafter\def\csname PY@tok@gr\endcsname{\def\PY@tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
123 | \expandafter\def\csname PY@tok@cm\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
124 | \expandafter\def\csname PY@tok@vg\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
125 | \expandafter\def\csname PY@tok@vi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
126 | \expandafter\def\csname PY@tok@mh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
127 | \expandafter\def\csname PY@tok@cs\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
128 | \expandafter\def\csname PY@tok@ge\endcsname{\let\PY@it=\textit}
129 | \expandafter\def\csname PY@tok@vc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
130 | \expandafter\def\csname PY@tok@il\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
131 | \expandafter\def\csname PY@tok@go\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.53,0.53}{##1}}}
132 | \expandafter\def\csname PY@tok@cp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.74,0.48,0.00}{##1}}}
133 | \expandafter\def\csname PY@tok@gi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
134 | \expandafter\def\csname PY@tok@gh\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
135 | \expandafter\def\csname PY@tok@ni\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.60,0.60,0.60}{##1}}}
136 | \expandafter\def\csname PY@tok@nl\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.63,0.63,0.00}{##1}}}
137 | \expandafter\def\csname PY@tok@nn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
138 | \expandafter\def\csname PY@tok@no\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.53,0.00,0.00}{##1}}}
139 | \expandafter\def\csname PY@tok@na\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.49,0.56,0.16}{##1}}}
140 | \expandafter\def\csname PY@tok@nb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
141 | \expandafter\def\csname PY@tok@nc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
142 | \expandafter\def\csname PY@tok@nd\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
143 | \expandafter\def\csname PY@tok@ne\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.82,0.25,0.23}{##1}}}
144 | \expandafter\def\csname PY@tok@nf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,1.00}{##1}}}
145 | \expandafter\def\csname PY@tok@si\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}}
146 | \expandafter\def\csname PY@tok@s2\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
147 | \expandafter\def\csname PY@tok@nt\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
148 | \expandafter\def\csname PY@tok@nv\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
149 | \expandafter\def\csname PY@tok@s1\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
150 | \expandafter\def\csname PY@tok@ch\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
151 | \expandafter\def\csname PY@tok@m\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
152 | \expandafter\def\csname PY@tok@gp\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
153 | \expandafter\def\csname PY@tok@sh\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
154 | \expandafter\def\csname PY@tok@ow\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.67,0.13,1.00}{##1}}}
155 | \expandafter\def\csname PY@tok@sx\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
156 | \expandafter\def\csname PY@tok@bp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
157 | \expandafter\def\csname PY@tok@c1\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
158 | \expandafter\def\csname PY@tok@o\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
159 | \expandafter\def\csname PY@tok@kc\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
160 | \expandafter\def\csname PY@tok@c\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
161 | \expandafter\def\csname PY@tok@mf\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
162 | \expandafter\def\csname PY@tok@err\endcsname{\def\PY@bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
163 | \expandafter\def\csname PY@tok@mb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
164 | \expandafter\def\csname PY@tok@ss\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.10,0.09,0.49}{##1}}}
165 | \expandafter\def\csname PY@tok@sr\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.53}{##1}}}
166 | \expandafter\def\csname PY@tok@mo\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
167 | \expandafter\def\csname PY@tok@kd\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
168 | \expandafter\def\csname PY@tok@mi\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
169 | \expandafter\def\csname PY@tok@kn\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
170 | \expandafter\def\csname PY@tok@cpf\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.25,0.50,0.50}{##1}}}
171 | \expandafter\def\csname PY@tok@kr\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
172 | \expandafter\def\csname PY@tok@s\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
173 | \expandafter\def\csname PY@tok@kp\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
174 | \expandafter\def\csname PY@tok@w\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
175 | \expandafter\def\csname PY@tok@kt\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.69,0.00,0.25}{##1}}}
176 | \expandafter\def\csname PY@tok@sc\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
177 | \expandafter\def\csname PY@tok@sb\endcsname{\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
178 | \expandafter\def\csname PY@tok@k\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.00,0.50,0.00}{##1}}}
179 | \expandafter\def\csname PY@tok@se\endcsname{\let\PY@bf=\textbf\def\PY@tc##1{\textcolor[rgb]{0.73,0.40,0.13}{##1}}}
180 | \expandafter\def\csname PY@tok@sd\endcsname{\let\PY@it=\textit\def\PY@tc##1{\textcolor[rgb]{0.73,0.13,0.13}{##1}}}
181 |
182 | \def\PYZbs{\char`\\}
183 | \def\PYZus{\char`\_}
184 | \def\PYZob{\char`\{}
185 | \def\PYZcb{\char`\}}
186 | \def\PYZca{\char`\^}
187 | \def\PYZam{\char`\&}
188 | \def\PYZlt{\char`\<}
189 | \def\PYZgt{\char`\>}
190 | \def\PYZsh{\char`\#}
191 | \def\PYZpc{\char`\%}
192 | \def\PYZdl{\char`\$}
193 | \def\PYZhy{\char`\-}
194 | \def\PYZsq{\char`\'}
195 | \def\PYZdq{\char`\"}
196 | \def\PYZti{\char`\~}
197 | % for compatibility with earlier versions
198 | \def\PYZat{@}
199 | \def\PYZlb{[}
200 | \def\PYZrb{]}
201 | \makeatother
202 |
203 |
204 | % Exact colors from NB
205 | \definecolor{incolor}{rgb}{0.0, 0.0, 0.5}
206 | \definecolor{outcolor}{rgb}{0.545, 0.0, 0.0}
207 |
208 |
209 |
210 |
211 | % Prevent overflowing lines due to hard-to-break entities
212 | \sloppy
213 | % Setup hyperref package
214 | \hypersetup{
215 | breaklinks=true, % so long urls are correctly broken across lines
216 | colorlinks=true,
217 | urlcolor=urlcolor,
218 | linkcolor=linkcolor,
219 | citecolor=citecolor,
220 | }
221 | % Slightly bigger margins than the latex defaults
222 |
223 | \geometry{verbose,tmargin=1in,bmargin=1in,lmargin=1in,rmargin=1in}
224 |
225 | \title{Introduction to Scientific Computing in Python}
226 | \author{Robert Johansson}
227 |
228 | \begin{document}
229 | \maketitle
230 |
231 | \tableofcontents
232 |
233 | \newpage
234 | \input{Lecture-0-Scientific-Computing-with-Python}
235 |
236 | \newpage
237 | \input{Lecture-1-Introduction-to-Python-Programming}
238 |
239 | \newpage
240 | \input{Lecture-2-Numpy}
241 |
242 | \newpage
243 | \input{Lecture-3-Scipy}
244 |
245 | \newpage
246 | \input{Lecture-4-Matplotlib}
247 |
248 | \newpage
249 | \input{Lecture-5-Sympy}
250 |
251 | \newpage
252 | \input{Lecture-6A-Fortran-and-C}
253 |
254 | \newpage
255 | \input{Lecture-6B-HPC}
256 |
257 | \newpage
258 | \input{Lecture-7-Revision-Control-Software}
259 |
260 | \end{document}
261 |
--------------------------------------------------------------------------------
/chapter.tplx:
--------------------------------------------------------------------------------
1 | ((*- extends 'display_priority.tplx' -*))
2 |
3 | %===============================================================================
4 | % Abstract overrides
5 | %===============================================================================
6 |
7 | ((* block header *))
8 | ((* endblock header *))
9 |
10 | ((* block body *))
11 | ((( super() )))
12 | ((* endblock body *))
13 |
14 | %===============================================================================
15 | % Support blocks
16 | %===============================================================================
17 |
18 | % Displaying simple data text
19 | ((* block data_text *))
20 | \begin{verbatim}
21 | ((( output.data['text/plain'] )))
22 | \end{verbatim}
23 | ((* endblock data_text *))
24 |
25 | % Display python error text as-is
26 | ((* block error *))
27 | \begin{Verbatim}[commandchars=\\\{\}]
28 | ((( super() )))
29 | \end{Verbatim}
30 | ((* endblock error *))
31 | ((* block traceback_line *))
32 | ((( line | indent | strip_ansi | escape_latex )))
33 | ((* endblock traceback_line *))
34 |
35 | % Display stream ouput with coloring
36 | ((* block stream *))
37 | \begin{Verbatim}[commandchars=\\\{\}]
38 | ((( output.text | escape_latex | ansi2latex )))
39 | \end{Verbatim}
40 | ((* endblock stream *))
41 |
42 | % Display latex
43 | ((* block data_latex -*))
44 | ((( output.data['text/latex'] | citation2latex | strip_files_prefix | markdown2latex )))
45 | ((* endblock data_latex *))
46 |
47 | % Display markdown
48 | ((* block data_markdown -*))
49 | ((( output.data['text/markdown'] | citation2latex | strip_files_prefix | markdown2latex )))
50 | ((* endblock data_markdown *))
51 |
52 | % Default mechanism for rendering figures
53 | ((*- block data_png -*))((( draw_figure(output.metadata.filenames['image/png']) )))((*- endblock -*))
54 | ((*- block data_jpg -*))((( draw_figure(output.metadata.filenames['image/jpeg']) )))((*- endblock -*))
55 | ((*- block data_svg -*))((( draw_figure(output.metadata.filenames['image/svg+xml']) )))((*- endblock -*))
56 | ((*- block data_pdf -*))((( draw_figure(output.metadata.filenames['application/pdf']) )))((*- endblock -*))
57 |
58 | % Draw a figure using the graphicx package.
59 | ((* macro draw_figure(filename) -*))
60 | ((* set filename = filename | posix_path *))
61 | ((*- block figure scoped -*))
62 | \begin{center}
63 | \adjustimage{max size={0.9\linewidth}{0.9\paperheight}}{((( filename )))}
64 | \end{center}
65 | { \hspace*{\fill} \\}
66 | ((*- endblock figure -*))
67 | ((*- endmacro *))
68 |
69 | % Render markdown
70 | ((* block markdowncell scoped *))
71 | ((( cell.source | citation2latex | strip_files_prefix | markdown2latex(extra_args=["--chapters"]) )))
72 | ((* endblock markdowncell *))
73 |
74 | % Don't display unknown types
75 | ((* block unknowncell scoped *))
76 | ((* endblock unknowncell *))
77 |
78 | %===============================================================================
79 | % Input
80 | %===============================================================================
81 |
82 | ((* block input scoped *))
83 | ((( add_prompt(cell.source | highlight_code(strip_verbatim=True), cell, 'In ', 'incolor') )))
84 | ((* endblock input *))
85 |
86 |
87 | %===============================================================================
88 | % Output
89 | %===============================================================================
90 |
91 | ((* block execute_result scoped *))
92 | ((*- for type in output.data | filter_data_type -*))
93 | ((*- if type in ['text/plain']*))
94 | ((( add_prompt(output.data['text/plain'] | escape_latex, cell, 'Out', 'outcolor') )))
95 | ((* else -*))
96 | \texttt{\color{outcolor}Out[{\color{outcolor}((( cell.execution_count )))}]:}((( super() )))
97 | ((*- endif -*))
98 | ((*- endfor -*))
99 | ((* endblock execute_result *))
100 |
101 |
102 | %==============================================================================
103 | % Support Macros
104 | %==============================================================================
105 |
106 | % Name: draw_prompt
107 | % Purpose: Renders an output/input prompt
108 | ((* macro add_prompt(text, cell, prompt, prompt_color) -*))
109 | ((*- if cell.execution_count is defined -*))
110 | ((*- set execution_count = "" ~ (cell.execution_count | replace(None, " ")) -*))
111 | ((*- else -*))
112 | ((*- set execution_count = " " -*))
113 | ((*- endif -*))
114 | ((*- set indention = " " * (execution_count | length + 7) -*))
115 | \begin{Verbatim}[commandchars=\\\{\}]
116 | ((( text | add_prompts(first='{\color{' ~ prompt_color ~ '}' ~ prompt ~ '[{\\color{' ~ prompt_color ~ '}' ~ execution_count ~ '}]:} ', cont=indention) )))
117 | \end{Verbatim}
118 | ((*- endmacro *))
119 |
120 |
121 |
--------------------------------------------------------------------------------
/images/github-diff.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/github-diff.png
--------------------------------------------------------------------------------
/images/github-project-page.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/github-project-page.png
--------------------------------------------------------------------------------
/images/gitk.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/gitk.png
--------------------------------------------------------------------------------
/images/ipython-notebook-screenshot.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/ipython-notebook-screenshot.jpg
--------------------------------------------------------------------------------
/images/ipython-screenshot.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/ipython-screenshot.jpg
--------------------------------------------------------------------------------
/images/optimizing-what-2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/optimizing-what-2.png
--------------------------------------------------------------------------------
/images/optimizing-what.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/optimizing-what.png
--------------------------------------------------------------------------------
/images/python-screenshot.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/python-screenshot.jpg
--------------------------------------------------------------------------------
/images/scientific-python-stack.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/scientific-python-stack.png
--------------------------------------------------------------------------------
/images/scientific-python-stack.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
21 |
23 |
35 |
41 |
47 |
53 |
54 |
78 |
87 |
88 |
90 |
91 |
93 | image/svg+xml
94 |
96 |
97 |
98 |
99 |
100 |
105 |
133 |
141 |
149 |
157 |
165 |
173 |
181 | Python Lecture 1
198 | Numpy Lecture 2
215 | Scipy Lecture 3
232 | matplotlib Lecture 4
249 | Sympy Lecture 5
266 | Other packages and toolboxes for example QuTiP
283 | User programs
295 |
307 |
308 |
--------------------------------------------------------------------------------
/images/spyder-screenshot.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/spyder-screenshot.jpg
--------------------------------------------------------------------------------
/images/theory-experiment-computation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jrjohansson/scientific-python-lectures/a2a76136ac06ff5fa91343ae095f1223c914d944/images/theory-experiment-computation.png
--------------------------------------------------------------------------------
/images/theory-experiment-computation.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
21 |
23 |
35 |
41 |
47 |
53 |
54 |
78 |
87 |
88 |
90 |
91 |
93 | image/svg+xml
94 |
96 |
97 |
98 |
99 |
100 |
105 |
117 |
129 |
141 |
147 |
153 |
159 | Experiment measurements, observations, collect data, test hypothesis, ...
192 | Theory develop models, hypothesis, predictions, conclusions, ...
234 | Computation simulate models, test hypothesis, observations, visualizations, ...
271 |
292 |
293 |
--------------------------------------------------------------------------------
/scripts/hello-world-in-swedish.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: UTF-8 -*-
3 |
4 | print("Hej världen!")
5 |
--------------------------------------------------------------------------------
/scripts/hello-world.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | print("Hello world!")
4 |
--------------------------------------------------------------------------------