{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# (I)Python introduction\n", "\n", "Python is a programming language widely used. It has a lot of benefits: \n", "* easy to pick up \n", "* interpreting language, no compiling needed \n", "* **Open Source** \n", "* and thus an active community \n", "\n", "We will use Python for programming exercises in the practicals. Theoretical background material will also be presented in this python layout, called a \"notebook\". A _Notebook_ is a programming environment ideally suited for communicating your code. It comprises formatable text (using [Markdown](https://daringfireball.net/projects/markdown/syntax)), executable code (language depending on your running Kernel, e.g.: [Python](https://www.python.org/), [Julia](https://julialang.org/), [R](https://www.r-project.org/), or [Matlab](https://github.com/imatlab/imatlab)) \n", "\n", "### Python in Geosciences \n", "Python as a programming language is used more and more within the geoscience-community. Consequently, also teaching resources are getting more and more, e.g.: \n", "\n", "* http://geologyandpython.com/ \n", "* [Python for Geosciences by Nikolay Koldunov](https://github.com/koldunovn/python_for_geosciences) \n", "* [Introduction to Python for Geoscientists by Gorman and Barral, Imperial College](http://ggorman.github.io/Introduction-to-programming-for-geoscientists/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Contents \n", "\n", "* Define variables \n", "* Use Python as a calculator \n", "* Define an array \n", "* Finding idices in an array\n", "* Creating a sequence of numbers\n", "* Define a matrix,\n", "* Finding indices in a matrix\n", "* Loops\n", "* Plotting\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python, creating a variable is easy Just type the name followed by its value:\n", " e.g. ```x=3``` \n", "Python is case-sensitive, so ```x=3``` and ```X=3``` are not the same variable. \n", "\n", "### Exercise:\n", "Create a variable x equal to 6 \n", "Create a variable y which is 2 times x \n", "Create a variable z which is y$^2$ + 6*x\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# write below this line your code for the variables x, y, and z" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define an array \n", "Creating a vector (a 1D array) is rather simple. In Python, you can use lists or numpy arrays.\n", "Numpy is a library for numerical operations. Those who know matlab, will be very familiar with numpy. \n", "Numpy is a library and can thus be imported like: \n", "```python \n", "import numpy as np \n", "```\n", "With `Numpy` you will be able to use more advanced functions, such as `np.polyfit`, `np.linspace` etc. Note that in front of the function we always write `np.`, because we imported numpy as `np`. \n", "Wenn we load a module in python as a name such as `np`, every method within this module gets called by using \n", "\n", "```python\n", "module.method(*kwargs)\n", "``` \n", "\n", "Vectors in numpy are called `arrays`. We can generate an array e.g. like: \n", "```python\n", "v = np.array([[1, 2], [3, 4]])\n", "```\n", "which would be an array with 2 columns and 2 rows.\n", "\n", "### Exercise: \n", "Create a vector with 5 rows and the values 2,4,8,5,9. \n", "e shall be the fourth index of v \n", "Create a vector v2, equal to v.*v." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "# write below this line your code for v, e, and v2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create a sequence of numbers \n", "Creating each index of a vector is tedious. If you want to create a sequence of numbers, you can use numpy functions like linspace or logspace. \n", "linspace(x,y,z), creates a sequence with z values from starting point x to end point y (with x < y). It can be called similar to matlab\n", "\n", "```python \n", "x = np.linspace(0,500,35)\n", "```\n", "\n", "### Exercise:\n", "Create a sequence x from 1 to 10\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# write below this line your code for the x array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops \n", "\n", "Loops are essential in programming, e.g. calculating\n", "y=a+b*x+c*x2 in an interval from x=1:10 and plot it.\n", "To calculate y, you first have to define x, a, b, and c.\n", "\n", "A loop starts with a key-word, like for, followed by an iterator.\n", "For y, the loop may look like this\n", "```python\n", "for i in range(len(x)):\n", " y[i]=a+b*x[i]+c*x[i]**2\n", "```\n", "you may have to pre-define y." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# write below this line your code for the y array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to calculate a polynom without a loop thanks to numpy. \n", "Try it with the polynom z. \n", "$$ z = \\frac{a}{2} + b \\times \\frac{c}{2} \\times x + \\sqrt{b \\times \\frac{c}{2}} \\times x^2 $$" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# write below this line your code for the z array" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Plotting\n", "\n", "Plotting is often one aim of a script in order to visualize your results. In Python, there are many libraries (I'll provide you a few in a follow up notebook). One is `matplotlib`. We will use `matplotlib`to plot x vs the polynoms y and z. \n", "\n", "The general syntax is fairly easy: \n", "```python \n", "plt.plot(x,y)\n", "```\n", "There are additional arguments which you can put into the `plot` command. For example, per default, values are plotted as a line in plot. If you want to plot the data points as dots, diamonds, circles, there are options:\n", "```python \n", "plt.plot(x,y,'-') # line plot\n", "plt.plot(x,y,'.') # point plot\n", "plt.plot(x,y,'o') # circles, i.e. bigger points\n", "plt.plot(x,y,'d') # diamonds\n", "```\n", "If you use different data sets in one plot, you'll need an option to distinguish between those data sets. You can do this via the symbol as above, the plot color, and a label (in order to add a legend).\n", "\n", "```python\n", "plt.plot(x, y, '.-', color=[.4,.8,.4], label='1st data')# point-line with RGB color and label \"1st data\"\n", "plt.plot(x, z, '--', color=[.9,.1,.1], label='snd data')# dash-line with RGB color and label \"2nd data\"\n", "plt.legend() # calls a legend to be visible in the plot\n", "```\n", "\n", "Normally, you can just read a plot properly, when you label your axes. In matplotlib, you do this by: \n", "```python\n", "plt.xlabel(\"x axis label\")\n", "plt.ylabel(\"y axis label\")\n", "plt.title(\"title of plot\")\n", "```\n", "### Exercise: \n", "Create a plot where we plot the two polynoms in one window. Assume those are functions of two different coffe brands with different „efficiency“.\n", "Name x „number of cups of coffee“ and y with „additional minutes awake“.\n", "\n", "Be sure that you can distinguish the two plots, maybe by different colors, line styles and a legend?\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# write here your code for the plot" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Zen of Python\n", "Finally, if you want to embrace the heart of python, try this in a codecell: \n", "\n", "```python\n", "import this\n", "```" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# import this" ] } ], "metadata": { "hide_input": false, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.8" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false }, "toc": { "base_numbering": 1, "nav_menu": { "height": "197px", "width": "253px" }, "number_sections": false, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": "block", "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }