Skip to content
Snippets Groups Projects
python-data-1-recap.ipynb 17 KiB
Newer Older
ignat's avatar
ignat committed
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Notebook 1 - Programming with Python recap\n",
ignat's avatar
ignat committed
    "\n",
    "Although this course assumes that you have basic knowledge of Python, in this notebook will be a quick recap of the fundamentals of computer programming which will be needed for the rest of the course. The notebook will cover:\n",
    "- [Types](#types)\n",
    "- [Arithmetic operations](#arith)\n",
    "- [Boolean logic](#boolean)\n",
    "- [Printing](#print)\n",
    "- [High level data structures](#hi-data)\n",
    "- [If-Else](#if)\n",
    "- [Loops](#loops)\n",
    "- [Functions](#func)\n",
    "- [Exercises](#exercise)\n",
    "\n",
    "You are intended to skim over this notebook and do the exercises at the end. Afterwards you can proceed to the next notebook.\n",
    "\n",
    "Estimated duration: 30 min\n",
    "\n",
    "You can use this notebook as a reference for the duration of the course."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Types <a name=\"types\"></a>\n",
    "| Type | Declaration | Example | Usage |\n",
    "|----|----|----|----|\n",
    "| Integer  | int | `x = 124` | Numbers without decimal point |\n",
    "| Float  | float | `x = 124.56` | Numbers with decimcal point |\n",
    "| String  | str | `x = \"Hello world\"` | Used for text |\n",
    "| Boolean  | bool | `x = True` or `x = False` | Used for conditional statements |\n",
    "| NoneType  | None | `x = None` | Whenever you want an empty variable |\n",
    "\n",
    "You can convert from one type to another:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 10    # This is an integer\n",
    "y = \"20\"  # This is a string\n",
    "x + int(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can find the type of a variable using the `type()` function:"
ignat's avatar
ignat committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "var = 13.4\n",
    "type(var)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Arithmetical operators <a name=\"arith\"></a>\n",
    "\n",
    "Python supports a range of different arithmetical operators:\n",
    "\n",
    "| Symbol | Task Performed | Example | Result\n",
    "|----|---|---|---|\n",
    "| +  | Addition | 4 + 3 | 7 |\n",
    "| -  | Subtraction | 4 - 3 | 1 |\n",
    "| /  | Division | 7 / 2 | 3.5 |\n",
    "| %  | Mod | 7 % 2 | 1 |\n",
    "| *  | Multiplication | 4 * 3 | 12 |\n",
    "| //  | Floor division | 7 // 2 | 3 |\n",
    "| **  | Power of | 7 ** 2 | 49 |"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "16 ** 2 / 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Boolean logic <a name=\"boolean\"></a>\n",
    "| Operator | Output | \n",
    "|----|---|\n",
    "| x == y | True if x and y have the same value |\n",
    "| x != y | True if x and y don't have the same value |\n",
    "| x < y | True if x is less than y |\n",
    "| x > y | True if x is more than y |\n",
    "| x <= y | True if x is less than or equal to y |\n",
    "| x >= y | True if x is more than or equal to y |\n",
    "\n",
    "Make note that these operators return Boolean values (ie. `True` or `False`). Naturally, if the operations don't return `True`, they will return `False`. Let's try some of them out:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = 5       # assign 5 to the variable x\n",
    "x == 5      # check if value of x is 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x > 7"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That is nice! How can we extend this to link multiple combinations like that? Luckily, Python offers the usual set of **logical operations**:\n",
    "\n",
    "| Operation | Result | \n",
    "|----|---|\n",
    "| x or y | True if at least on is True |\n",
    "| x and y  | True only if both are True |\n",
    "| not x | True only if x is False |\n",
    "\n",
    "\n",
    "\n",
    "With this, we can now chain different boolean operations:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check if x is divisible by both 2 and 3\n",
    "x = 42\n",
    "( x % 2 == 0 ) and ( x % 3 == 0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Printing <a name=\"print\"></a>\n",
    "Output text to the user of the program"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"Python is powerful!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = \"Python is powerful\"\n",
    "y = \" and versatile!\"\n",
    "print(x + y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "str1 = \"The string has\"\n",
    "str2 = 76\n",
    "str3 = \"methods!\"\n",
    "print(str1, str2, str3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Furthermore, there is also a way to insert variables inbetween text using placeholders like `%d` which stands for decimal. As seen from the code cell below, this is an extremely compact and easy way to print. "
ignat's avatar
ignat committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "num = 12\n",
    "print(\"You can also include a number like %d like this.\" %num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = \"\"\"To include\n",
    "multiple lines\n",
    "you have to do this\"\"\"\n",
    "y =\"or you can also\\ninclude the special\\ncharacter `\\\\n` between lines\"\n",
    "print(x)\n",
    "print(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# High level data structures <a name=\"hi-data\"></a>\n",
    "## Lists <a name=\"lists\"></a>\n",
    "Probably the most commonly used data structure in Python. Lists simply group multiple variables together."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits = [\"apple\", \"orange\", \"tomato\", \"banana\"]  # a list of strings\n",
    "print(type(fruits))\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can access each individual item within the list by **indexing** it.\n",
    "\n",
    "Recall that indices **start from 0**.\n",
ignat's avatar
ignat committed
    "\n",
    "![List Indexing](https://gdurl.com/ebW1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(fruits[0])\n",
    "print(fruits[2])\n",
    "print(fruits[-1])\n",
    "print(len(fruits))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can modify existing lists as:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruits.append(\"lime\")    # add new item to list\n",
    "print(fruits)\n",
    "fruits.append(\"orange\")\n",
    "print(fruits)\n",
ignat's avatar
ignat committed
    "fruits.remove(\"orange\")  # remove orange from list\n",
    "print(fruits)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That seems useful! Can we do the same with integers? Python actually offers various functions for generating numerical lists. The most useful out of which is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "nums = list(range(10))\n",
    "print(nums)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also get only a part of a list you have already created. This is called **slicing** and can be done in various different ways:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(nums[0:3])\n",
    "print(nums[4:])\n",
    "print(nums[-1])\n",
    "print(nums[::-1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# If Else <a name=\"if\"></a>\n",
    "The statement after `if` must evaluate to a Boolean value (`True` or `False`), if it is `True` then we execute the code between the `if` and `else` statements and skip the code after the else statement. If the Boolean expression after `if` evaluates to `False` then we skip the code between `if` and `else` and execute only the code after `else`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = True\n",
    "if x:\n",
    "    print(\"Executing if\")\n",
    "else:\n",
    "    print(\"Executing else\")\n",
    "print(\"Prints regardless of the outcome of the if-else block\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Try changing the value of x to `False`.\n",
    "\n",
    "if-else statements can also be extended with `elif` which as implied combines both else + if = elif. This is useful if you want to have multiple conditions for example:\n",
    "\n",
    "Let us illustrate this in an elaborate example. Imagine you have purchased a stock and are looking to make a profit out of it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "purchasePrice = float(input(\"Price at which you have purchased bitcoins: \"))\n",
    "currentPrice = float(input(\"Current price of the bitcoins: \"))\n",
    "\n",
    "if currentPrice < purchasePrice*0.9:\n",
    "    print(\"Not a good idea to sell your bitcoins now.\")\n",
    "    print(\"You will lose\", purchasePrice - currentPrice, \"£ per bitcoin.\")\n",
    "elif currentPrice > purchasePrice*1.2:\n",
    "    print(\"You will make\", currentPrice - purchasePrice, \"£ per bitcoin.\")\n",
    "else:\n",
    "    print(\"Not worth selling right now.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Loops <a name=\"loops\"></a>\n",
    "\n",
    "## for\n",
    "Generally useful whenever you want to iterate over a list (or other data structure) of items and apply the same operation to all items within it. In general, `for` loops look like this and have indentation just like if-else statements:\n"
ignat's avatar
ignat committed
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fruitList = [\"apple\", \"orange\", \"tomate\", \"banana\"]\n",
    "for fruit in fruitList:\n",
    "    print(\"The fruit\", fruit, \"has index\", fruitList.index(fruit))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "numbers = range(10)\n",
ignat's avatar
ignat committed
    "for num in numbers:\n",
    "    squared = num ** 2\n",
    "    print(num, \"squared is\", squared)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## while\n",
    "Another useful loop which is a bit less controllable. It executes over and over until its condition becomes false. For example, we can make a loop that executes 5 times and then stops."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 0\n",
    "while n < 5:\n",
    "    print(\"Executing while loop\")\n",
    "    n = n + 1\n",
    "\n",
    "print(\"Finished while loop\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## break\n",
    "Not a loop but extremely useful within loops! As implied `break` literally breaks the loop and forces the program to go out of it. We can redo our `while` loop example using `break`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 0\n",
    "while True:  # execute indefinitely\n",
    "    print(\"Executing while loop\")\n",
    "    \n",
    "    if n == 5:  # stop loop if n is 5\n",
    "        break\n",
    "    \n",
    "    n = n + 1\n",
    "\n",
    "print(\"Finished while loop\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Functions <a name=\"func\"></a>\n",
    "Also referred to as methods, functions are effectively small programs that take in arguments(ie. inputs) and return values(outputs).\n",
    "\n",
    "Functions are an incredibly useful concept since they allow us to package functionality in a convenient and easy to read manner and reproduce the same result without having to write it again and again. A quick example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def printNum(num):\n",
    "    print(\"My favourite number is\", num)\n",
    "    \n",
    "printNum(7)\n",
    "printNum(14)\n",
    "printNum(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Rule of thumb - if you are planning on using very similar code more than once, it may be wortwhile writing it as a reusable function. \n",
    "\n",
    "Some examples:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def roundNum(num):\n",
    "    remainder = num % 1\n",
    "    if remainder < 0.5:\n",
    "        return num - remainder\n",
    "    else:\n",
    "        return num + (1 - remainder)\n",
    "\n",
    "# Will it work?\n",
    "x = roundNum(3.4)\n",
    "print (x)\n",
    "\n",
    "y = roundNum(7.7)\n",
    "print(y)\n",
    "\n",
    "z = roundNum(9.2)\n",
    "print(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The number of arguments is by no means limited to 1. Actually it is infinite! A function can have any number of arguments using `*args` but bear in mind that this also can make it less controllable. With this knowledge we can make a function that simply adds up all of its inputs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def sum(*args):\n",
    "    result = 0\n",
    "    for num in args:\n",
    "        result = result + num\n",
    "    return result\n",
    "        \n",
    "print(sum(5, 6, 7, 8, 9))\n",
    "print(sum(1, 2, 5, 10, 20, 34))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exercise <a name=\"exercise\"></a>\n",
    "\n",
    "## 1. Fibonacci\n",
    "Create a function `fibonacci()` which takes an integer `num` as an input and returns a list of the first `num` fibonacci numbers.\n",
ignat's avatar
ignat committed
    "\n",
    "Eg.\n",
    "\n",
    "Input: `8`\n",
    "\n",
    "Output: `[1, 1, 2, 3, 5, 8, 13, 21]`\n",
    "\n",
    "*Hint: You might want to recall [fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
ignat's avatar
ignat committed
   "source": [
    "def fibonacci(num):\n",
    "    # [ WRITE YOUR CODE HERE ]\n",
    "    "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Check your answer by running the code cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
ignat's avatar
ignat committed
    "################ Checking code ########################\n",
    "# Please don't edit this code\n",
    "newList = fibonacci(10)\n",
    "if newList == [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]:\n",
    "    print(\"Success!\")\n",
    "else:\n",
    "    print(\"Error! Your function returned\")\n",
ignat's avatar
ignat committed
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Guessing game\n",
    "Ask the user to input a number within [0, 100] and then have the program guess it. After each guess, the user must input whether it was too high, too low or the correct number. In the end, the program must always guess the users number and it must print out the number of guesses it needed.\n",
ignat's avatar
ignat committed
    "\n",
    "_Note: You can use `random.randint(0,100)` to generate the random number but don't forget to also import the package via `import random as random`_\n",
    "\n",
    "_Note2: You can use `input()` to ask the user for a number_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "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.6.6"
ignat's avatar
ignat committed
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}