{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bachelor Programming Course 2021\n",
    "# Python Basics\n",
    "![Python](python.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Table of Contents\n",
    "\n",
    "- How to get python on our machines\n",
    "\n",
    "1. Data types & operators\n",
    "2. Control structures\n",
    "3. Operations on data types\n",
    "\n",
    "- Excercises\n",
    "\n",
    "4. Numpy\n",
    "5. Matplotlib\n",
    "6. Functions\n",
    "7. Reading/Writing\n",
    "\n",
    "- Excercises\n",
    "\n",
    "8. Scipy\n",
    "9. Uncertainties\n",
    "10. Argparse\n",
    "11. Pathlib\n",
    "\n",
    "- Excercises"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How to get python on our machines\n",
    "\n",
    "Setting up a pre-installed `conda` environment on our interactive machines\n",
    "```\n",
    "ssh interactive\n",
    "set_conda\n",
    "source activate root_forge\n",
    "```\n",
    "Start `jupyter notebook` with an arbitrary 4-digit port\n",
    "```\n",
    "jupyter notebook --no-browser --port <port_on_machine>\n",
    "```\n",
    "Open another local terminal and do port forwarding\n",
    "```\n",
    "ssh -NfL <local_port>:localhost:<port_on_machine> <local_user>@<user_on_machine>\n",
    "```\n",
    "Copy the following-like URL from the jupyter server to your browser\n",
    "```\n",
    "http://localhost:<port_on_machine>/tree?token=<your_token>\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Data types & operators"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 182,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Boolean\n",
    "x = True\n",
    "x = False\n",
    "\n",
    "# Numbers\n",
    "x = 1\n",
    "x = 2.3\n",
    "x = 1.234e-12\n",
    "x = 1 + 2j\n",
    "\n",
    "\n",
    "# Strings: immutable sequence of characters\n",
    "x = \"Hello\"\n",
    "x = 'World'\n",
    "x = \"Hello 'World'\"\n",
    "x = \"Hello \\\"World\\\"\"\n",
    "\n",
    "# Tuple: immutable sequence of values\n",
    "x = (1, 2, 3)\n",
    "x = (1, x, \"foo\")\n",
    "\n",
    "# List: mutable sequence of values\n",
    "x = [1, x, \"foo\"]\n",
    "\n",
    "# Set: mutable set of values\n",
    "x = {1, 2, 3}\n",
    "\n",
    "# Dict: key-value pairs\n",
    "x = {\"foo\": 1, \"bar\": 2}\n",
    "\n",
    "# Special: None to create an \"empty\" variable\n",
    "x = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 183,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "d = {\"foo\": 1, \"bar\": 2}\n",
    "print(d[\"foo\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 184,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 2\n",
    "b = 3\n",
    "\n",
    "# Basic arithmetic operators\n",
    "c = a + b\n",
    "c = a - b\n",
    "c = a * b\n",
    "c = a / b\n",
    "c = a % b\n",
    "c = a // b\n",
    "c = a ** b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 185,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "False\n",
      "True\n",
      "False\n",
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "# Some comparison operators\n",
    "print(a > b)\n",
    "print(a < b)\n",
    "print(a >= b)\n",
    "print(a != b)\n",
    "print(a == b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 186,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "4.5\n",
      "9.0\n"
     ]
    }
   ],
   "source": [
    "# Some assignment operators \n",
    "a += 3\n",
    "print(a)\n",
    "a -= 0.5\n",
    "print(a)\n",
    "a *= 4 - 2\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Control structures"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### If statements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 187,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 is an odd number\n"
     ]
    }
   ],
   "source": [
    "a = 5\n",
    "if not isinstance(a, int):\n",
    "    print(f\"{a} is not an integer\")\n",
    "elif a % 2 == 0:\n",
    "    print(f\"{a} is an even number\")\n",
    "else:\n",
    "    print(f\"{a} is an odd number\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 190,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False is False\n",
      "False is not True\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "if True:\n",
    "    print(\"True\")\n",
    "if False:\n",
    "    print(\"False\")\n",
    "if False is False:\n",
    "    print(\"False is False\")\n",
    "if False is not True:\n",
    "    print(\"False is not True\")\n",
    "if True in [True, False]:\n",
    "    print(True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 192,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False, True, True]\n",
      "At least one list element is True\n"
     ]
    }
   ],
   "source": [
    "mask = [2>3, 2>=1, 2==2]\n",
    "print(mask)\n",
    "if any(mask):\n",
    "    print(\"At least one list element is True\")\n",
    "    \n",
    "if all(mask):\n",
    "    print(\"Every list element is True\")\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Loops"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "while i < 3:\n",
    "    print(i)\n",
    "    i += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "for i in range(3):\n",
    "    print(i)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mercury\n",
      "venus\n",
      "mars\n",
      "jupiter\n",
      "saturn\n",
      "uranus\n",
      "neptune\n",
      "pluto is not a planet anymore\n"
     ]
    }
   ],
   "source": [
    "planets = [\"mercury\", \"venus\", \"earth\", \"mars\", \"jupiter\", \"saturn\", \"uranus\", \"pluto\", \"neptune\"]\n",
    "\n",
    "for planet in planets:\n",
    "    if planet == \"earth\":\n",
    "        continue\n",
    "    if planet == \"pluto\":\n",
    "        print(\"pluto is not a planet anymore\")\n",
    "        break\n",
    "    else:\n",
    "        print(planet)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Operations on data types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Lists"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = []\n",
    "x = [1,2]\n",
    "x = [[1,2], [2,4]]\n",
    "x = [\"Schrödinger\", \"Pauli\", \"Hertz\"]\n",
    "x = [3.14159, \"Elektron\", (1,2), [\"Hideki Yukawa\", \"Steven Weinberg\", \"Bruno Pontecorvo\"]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Steven Weinberg\n"
     ]
    }
   ],
   "source": [
    "print(x[3][1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### List slicing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['LHCb', 'ATLAS', 'CMS', 'ALICE', 'HyperKamiokande', 'KATRIN']\n",
      "['LHCb', 'ATLAS']\n",
      "['ATLAS']\n",
      "ATLAS\n",
      "KATRIN\n"
     ]
    }
   ],
   "source": [
    "experiments = [\"LHCb\", \"ATLAS\", \"CMS\", \"ALICE\", \"SuperKamiokande\", \"KATRIN\"]\n",
    "experiments[4] = \"HyperKamiokande\"\n",
    "print(experiments)\n",
    "# syntax: start:stop:stepsize --> start at start, stop at stop-1, doing steps in stepsize !!!\n",
    "print(experiments[:2]) \n",
    "print(experiments[1:2])\n",
    "print(experiments[1])\n",
    "print(experiments[-1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 195,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['TASSO']\n",
      "[['LHCb', 'ATLAS', 'CMS', 'ALICE'], ['BaBar', 'ARGUS', 'TASSO', 'H1', 'Hera-B']]\n",
      "[['BaBar', 'ARGUS', 'TASSO', 'H1', 'Hera-B'], ['ALEPH', 'DELPHI', 'L3', 'OPAL'], ['LHCb', 'ATLAS', 'CMS', 'ALICE']]\n"
     ]
    }
   ],
   "source": [
    "experiments = [\n",
    "    [\"LHCb\", \"ATLAS\", \"CMS\", \"ALICE\"],\n",
    "    [\"ALEPH\", \"DELPHI\", \"L3\", \"OPAL\"],\n",
    "    [\"BaBar\", \"ARGUS\", \"TASSO\", \"H1\", \"Hera-B\"]\n",
    "]\n",
    "print(experiments[2][2:3])\n",
    "print(experiments[::2])\n",
    "print(experiments[::-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### List operations\n",
    "- `append()` → adds one element to the end of the list \n",
    "- `remove()` → removes the given element from the list\n",
    "- `insert()` → inserts element at given list index to the list\n",
    "- `extend()` → adds elements of iterable objects (e.g. list, numpy array, ...) to the end of a list\n",
    "- `pop()` → removes list element at given list index\n",
    "- `count()` → counts number of elements in list\n",
    "- `index()` → returns index of given element\n",
    "- `sort()` → sorts list\n",
    "- `reverse()` → reverses order of list elements\n",
    "- `copy()` → returns copied list\n",
    "- `clear()` → removes all list elements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Schrödinger', 'Pauli', 'Hertz', 'Curie']\n",
      "['Schrödinger', 'Pauli', 'Hertz', 'Schrödinger', 'Pauli', 'Hertz']\n",
      "['Schrödinger', 'Hertz']\n",
      "['Schrödinger', 'von Neumann', 'Hertz']\n",
      "['Schrödinger', 'von Neumann', 'Hertz', 1, 2]\n",
      "['Schrödinger', 'von Neumann', 'Hertz', 1, 2]\n",
      "['Curie']\n",
      "['Schrödinger', 'von Neumann', 1, 2]\n"
     ]
    }
   ],
   "source": [
    "x = [\"Schrödinger\", \"Pauli\", \"Hertz\"]\n",
    "y = []\n",
    "\n",
    "y.append(\"Curie\")\n",
    "print(x + y)\n",
    "print(2 * x)\n",
    "\n",
    "x.remove(\"Pauli\")\n",
    "print(x)\n",
    "\n",
    "x.insert(1, \"von Neumann\")\n",
    "print(x)\n",
    "\n",
    "x.extend([1,2])\n",
    "print(x)\n",
    "\n",
    "z = x.copy()\n",
    "z.pop(2)\n",
    "print(x)\n",
    "print(y)\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### List comprehensions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\n",
      "[0.0, 1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0]\n",
      "[0.0, 4.0, 16.0, 36.0, 64.0]\n",
      "[1.0, 9.0, 25.0, 49.0, 81.0]\n",
      "[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5]\n"
     ]
    }
   ],
   "source": [
    "x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]\n",
    "print(x)\n",
    "\n",
    "y = [i**2 for i in x]\n",
    "print(y)\n",
    "\n",
    "even = [i**2 for i in x if i%2 == 0] \n",
    "odd = [i**2 for i in x if i%2 != 0]\n",
    "print(even)\n",
    "print(odd)\n",
    "\n",
    "z = [x + y for x in range(3) for y in range(4)]\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Dictionaries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'particles': {'hadrons': {'baryons': ['proton',\n",
      "                                       'neutron'],\n",
      "                           'exotica': ['tetraquark',\n",
      "                                       'pentaquark'],\n",
      "                           'mesons': ['kaon',\n",
      "                                      'pion']},\n",
      "               'leptons': ['electron',\n",
      "                           'muon',\n",
      "                           'tau']},\n",
      " 'physicists': ['Curie',\n",
      "                'Einstein',\n",
      "                'Schrödinger']}\n"
     ]
    }
   ],
   "source": [
    "from pprint import pprint  # Just for some nice output\n",
    "\n",
    "dictionary = {\n",
    "    \"particles\": {\n",
    "        \"hadrons\": [\"mesons\", \"baryons\"],\n",
    "        \"leptons\": [\"electron\", \"muon\", \"tau\"]\n",
    "    }\n",
    "}\n",
    "dictionary.update({\"physicists\": [\"Curie\", \"Einstein\", \"Schrödinger\"]})\n",
    "dictionary[\"particles\"][\"hadrons\"].append(\"exotica\")\n",
    "dictionary[\"particles\"].update(\n",
    "    {\n",
    "        \"hadrons\": {\n",
    "            \"mesons\": [\"kaon\", \"pion\"],\n",
    "            \"baryons\": [\"proton\", \"neutron\"],\n",
    "            \"exotica\": [\"tetraquark\", \"pentaquark\"]\n",
    "        }\n",
    "    }\n",
    ")\n",
    "pprint(dictionary, width=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### String formatting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "simple string\n",
      "more advanced string than simple string\n",
      "a more advanced string than a simple string\n",
      "a more advanced string than a simple string\n"
     ]
    }
   ],
   "source": [
    "s1 = \"a\"\n",
    "s2 = \"simple string\"\n",
    "\n",
    "s3 = \"%s\" % s2\n",
    "s4 = \"more advanced string than {}\".format(s2)\n",
    "s5 = \"{0} more advanced string than {0} {1}\".format(s1, s2) \n",
    "s6 = f\"{s1} more advanced string than {s1} {s2}\"\n",
    "\n",
    "print(s3)\n",
    "print(s4)\n",
    "print(s5)\n",
    "print(s6)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The constant pi is approximately 3.1416\n"
     ]
    }
   ],
   "source": [
    "x = 3.14159265358979323846\n",
    "s = \"The constant pi is approximately {:.5}\".format(x)\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Excercise 1\n",
    "\n",
    "Write a short piece of code that reverses the list x without using x.reverse()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-3.14, True, 'lhcb', 1, 5, 2]\n"
     ]
    }
   ],
   "source": [
    "x = [2, 5, 1, \"lhcb\", True, -3.14]\n",
    "\n",
    "# One possible solution\n",
    "y = x[::-1]\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Excercise 2\n",
    "\n",
    "Write a short piece of code that determines the frequency of elements in list x and stores the result in a dictionary. Use only basic functionalities of python."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{2: 5, 4: 3, 1: 3, -2: 3, 8: 3, -1: 6, 0: 2}\n"
     ]
    }
   ],
   "source": [
    "x = [2, 2, 2, 2, 2, 4, 1, 1, 1, -2, -2, -2, 4, 4, 8, 8, 8, -1, -1, -1, -1, -1, -1, 0, 0]\n",
    "\n",
    "# One possible solution\n",
    "y = {i: x.count(i) for i in x}\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Excercise 3\n",
    "\n",
    "Write a short piece of code that determines the Euro coins you need to pay the amount of money x (which is given in Euro cents)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Need 6x 2 Euro\n",
      "Need 1x 1 Euro\n",
      "Need 1x 0.5 Euro\n",
      "Need 0x 0.2 Euro\n",
      "Need 1x 0.1 Euro\n",
      "Need 1x 0.05 Euro\n",
      "Need 0x 0.02 Euro\n",
      "Need 0x 0.01 Euro\n"
     ]
    }
   ],
   "source": [
    "x = 1365  # Euro cents\n",
    "\n",
    "# One possible solution\n",
    "x /= 100\n",
    "for i in [2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01]:\n",
    "    y = x // i\n",
    "    print(\"Need {}x {} Euro\".format(int(y), i))\n",
    "    x -= y * i"
   ]
  }
 ],
 "metadata": {
  "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.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
