.. _ch03-python-fortran: =============================================================== Introduction to Python =============================================================== ------------------------------------------------------------------------------- Reading Materials for This Chapter ------------------------------------------------------------------------------- This chapter of the lecture note has been partially extracted and modified from the following materials: * `Prof. LeVeque's (Univ. of Washington) online note on Python `_ * Note: These notes assume Python 2, while we will be using Python 3. They do remain useful as a reference though. * `Dive Into Python 3 `_ ------------------------------------------------------------------------------- Fortran vs. Python ------------------------------------------------------------------------------- So far we have studied Fortran, and will now begin studying Python. Let's take a moment and consider why these two choices of language are good for scientific computing. They share several key features that are useful for scientific computing: * Both are good examples of **high-level languages** which are much easier to program than **low-level languages** (e.g., machine language, assembly language). * Note: High and low level are relative terms. * Being high-level languages, they both have to be *processed* into some low-level representation before they can run. * Both are very useful for certain common tasks in scientific computing. They can easily be combined together to take advantage of the best of both worlds. * Many scientific programs are written in (at least) one of these languages, so it's really worthwhile to learn them. * Both are freely available and easy to get set up on personal machines. Of course, they also have some differences: * They are different types of languages which are processed in different ways. Python is an **interpreted** language, while Fortran is a **compiled** language. With the interpreter, Python is processed at runtime, as opposed to Fortran which must be compiled before being executed. * They follow two different programming paradigms: **object-oriented** (e.g., Python) vs. **procedural** (e.g., Fortran 90). Object-oriented programming in Python allows one to encapsulate code and data within classes. An *object* is an instance of a class which knows how to perform certain actions on its own data, and possibly how to interact with other elements of the program. On the other hand, the procedural programming in Fortran carries out step-by-step instructions as implemented in the code based on *procedures*, which we called subroutines in Fortran. Among those listed above, one of the biggest differences between Python and Fortran lies in the how they are processed into a low-level machine friendly representation. For Python, an interpreter reads your high-level, human-readable, program and executes it by literally following what the program says. It processes the program a little at a time, reading lines and performing computations exactly as they are written in the program. Contrast this with Fortran, which is compiled. The compiler, depending on selected flags, may optimize the written code heavily before fixing the representation that will be executed. Operations may be re-ordered, data may be re-packed, or segments may be completely removed/inlined. This generally makes interpreted languages slower than compiled languages. However there are ways to close this gap somewhat, as we'll see later. Python can be executed by a Python interpreter in two different ways: **interactive mode** and **script mode**. Let's start an interactive session by typing ``python`` in the terminal. If we now type ``1+1`` and hit enter, the interpreter will evaluate the statement and display the result .. code-block:: console >>> 1+1 # this is what you type 2 # this is how the interpreter replies The triple chevron ``>>>`` is the prompt the interpreter uses in order to indicate that it is ready for your input. The interactive mode is particularly handy when running small, perhaps exploratory, pieces of code, because you can type and execute them immediately at the prompt. Alternatively, you can write and save a code in a file with the file extension ``.py`` (e.g., ``yourCode.py``) .. literalinclude:: ./codes/examples/yourCode.py :language: python :linenos: :download:`Download this code <./codes/examples/yourCode.py>` and use the interpreter to execute the contents of the file. This is called *script mode*, and is called as follows: .. code-block:: console $ python yourCode.py hello python! a = 1 + 4 = 5 This is correct Should we print more? Will this be printed? The script mode should be the default way you run your code for anything beyond a few lines. This way you can re-run your code as often as you like, without needing to re-enter everything. Compared to an interpreter, a compiler reads the program and *translates it completely* before the program starts running. In this context, the high-level program is called the **source code**, and the translated program is called the **object code** or **executable**. Once a program is compiled, we can execute the executable as many as we can without further *translation*. **Remark:** Obviously there is no interactive mode in a compiled language. Learning multiple languages in one quarter, along with other topics, may seem overwhelming, but in many ways, it makes sense to learn them together. By comparing features in these languages, it may help clarify what the essential concepts are, and what is truly different about the languages vs. simple differences in syntax or convention. ------------------------------------------------------------------------------- Running Python ------------------------------------------------------------------------------- By now you should have already installed software packages for Python on your machine(s). Please make sure the following essential items are operational on your computer before we proceed to learn Python: 1. Check the pre-installed Python version by typing; .. code-block:: console $ python --version If you see the version number start with 2, for example; .. code-block:: console $ python --version Python 2.7.10 Then, you need to install `python3` by using your package manager (e.g., `brew`, `apt install`, `pacman -S`, `dnf`, etc.) 2. Check whether you have the python package manager, called `pip` or `pip3` by typing; .. code-block:: console $ pip3 --version and (or) .. code-block:: console $ pip --version Please ensure that your `pip` is pointing exactly your `python` version **3**. e.g., .. code-block:: console $ pip3 --version pip 10.0.1 from /usr/local/lib/python3.6/site-packages/pip (python 3.6) Then, you can install a Python package by executing .. code-block:: console $ pip3 install [packageName] 3. Alternatively, you can use `Anaconda `_, which includes many of the commonly used scientific packages for Python (and also Python itself). To install Anaconda, go to the official website, download the package, and install it. If you use Anaconda, then you need to install Python packages by using the `conda` command instead of using `pip`, e.g., .. code-block:: console $ conda install [packageName] See more `Managing Python using conda `_. The good news is that every package that will used in this course will be installed with one-time Anaconda installation. However, in case you haven't had a chance to install these yet, you can still use an online terminal where you can run basic Python commands in *interactive mode* using the free online interpreters available below: #. `NumPy online `_ (via tutorialspoint) #. `SciPy online `_ (via tutorialspoint) **Remark:** These online interpreters are only useful for very simple operations. You should get your own local environment set up ASAP. ------------------------------------------------------------------------------- Python 2 vs. Python 3? ------------------------------------------------------------------------------- The class lecture notes will assume the use of Python 3 as the default choice and examples will be given in Python 3. Python 2 has reached its *end-of-life*. To see discussions on the comparing the two, see: * `article written in 2014 `_ * `article written in 2017 `_ You may need to keep both version 2 and version 3 present on your system. Typically if both versions are present they will named ``python2`` and ``python3``, with ``python`` simply being a soft-link to one of those. Similarly, the python package managers will be named ``pip2`` and ``pip3`` respectively. If you need to coordinate the usage of these different versions to a greater extent, you may want to look into `virtual environments`, which can be installed easily on your machine. To see how to install and use it, take a look at the ``venv`` documentation: * `Python venv `_ ----------------------- Interactive Interpreter ----------------------- Even though the Python interpreter can be used *interactively*, you may want to use a slightly improved wrapper around that interpreter to make your life a bit easier. One nice option is `IPython `_, which you can install by: .. code-block:: console $ pip3 install ipython By typing ``ipython`` in your terminal, you will see a more flexible and functional wrapper around the Python interpreter. This wrapper on the python interpreter is part of a larger project called **Jupyter**. Another interface provided under this project is the **Jupyter notebook**. This tool provides a web-application development tool for Python within your browser (e.g. Firefox, Chrome, Safari). Again, you can install the Jupyter by using ``pip``. .. code-block:: console $ pip3 install jupyter To execute Jupyter type .. code-block:: console $ jupyter notebook which will open the notebook in your default web browser, and you can make a new `notebook` by clicking `new` button on the top-right. .. note:: ``jupyter`` and ``ipython`` are installed by default with `Anaconda`, so if you installed that then you'll already be set. .. note:: You are free to use Jupyter notebooks if you like, **but** you must submit regular Python scripts (``stuff.py``) for the homework assignments. Notebook files (``stuff.ipynb``) will **not** be graded.