{ "cells": [ { "cell_type": "markdown", "metadata": { "toc": true }, "source": [ "

Table of Contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> All content here is under a Creative Commons Attribution [CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/) and all source code is released under a [BSD-2 clause license](https://en.wikipedia.org/wiki/BSD_licenses).\n", ">\n", ">Please reuse, remix, revise, and [reshare this content](https://github.com/kgdunn/python-basic-notebooks) in any way, keeping this notice." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Module 1: Overview\n", "\n", "This tutorial covers several topics that are important to the beginning Python user, especially if you are coming from using another programming language.\n", "\n", "1. Printing\n", "2. Creating variables\n", "3. Types of variables\n", "3. Calculations with variables\n", "4. Built-in constants and mathematical functions\n", "6. Exercises\n", "\n", "## Preparing for this module\n", "\n", "* Have a basic Python installation that works. You can follow the instructions below, which should generate the output shown." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Printing\n", "\n", "* The ``print(...)`` function sends output to the screen. It is useful for debugging. \n", "* What is the equivalent way to do it in MATLAB, or in Java, or another language that you know already? \n", "* The ``print(...)`` function can use 'strings' or \"strings\", in other words with single or double quotes.\n", "\n", "Print the following text to the screen:\n", "\n", "> Hi, my name is \\_\\_\\_\\_\\_\n", "\n", "Now try this:\n", "\n", "> The Python language was created by Guido van Rossum in the 1980's when he worked at the Centrum Wiskunde & Informatica in Amsterdam. Yes, he's from the Netherlands, but has moved to the US and worked for Google, but now at Dropbox.\n", "\n", "You can verify the above by typing just the following two commands separately in Python:\n", "* ``credits``\n", "* ``copyright``" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi, my name is Kevin.\n" ] } ], "source": [ "print('Hi, my name is Kevin.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "long_string = \"\"\"If you really want to write paragraphs,\n", "and paragraphs of text, you do it with the triple quotes. Try it\"\"\"\n", "\n", "print(long_string)\n", "```\n", "\n", "* Verify how the above variable ``long_string`` will be printed. Does Python put a line break where you expect it?\n", "* Can you use single quotes instead of double quotes ?\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also create longer strings in Python using the bracket construction. Try this:\n", "\n", "```python\n", "print('Here is my first line.',\n", " 'Then the second.',\n", " 'And finally a third.',\n", " 'But did you expect that?')\n", "```\n", "The reason for this is stylistic. Python, unlike other languages, has some recommended rules, \n", "which we will introduce throughout these modules. One of these rules is that you don't exceed 79 characters per line.\n", "It helps to keep your code width narrow: you can then put two or three code files side-by-side on a widescreen monitor.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python also has escape characters. Discover it:\n", "* Try to print just the backslash character on its own: `print('\\')`\n", "* Try this instead: `print('\\\\')`\n", "\n", "The \"\\\\\" on its own is an *escape character*. Google that term. \n", "What are the escape characters for:\n", "* a tab?\n", "* a new line?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Try to print this: ``print('The files are in C:\\Data\\dirnew\\excel')``.\n", "2. Try to print this: ``print('The files are in C:\\temp\\newdir\\excel')``.\n", "\n", "> Why does it create such an unexpected mess?\n", ">\n", "> There are two different ways to quickly fix the code to show what is intended. \n", "> Try using escape characters first; we will show a more efficient way later." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Creating variables\n", "\n", "\n", "We already saw above how a variable was created: ``long_string = \"\"\" .... \"\"\"``.\n", "\n", "You've done this plenty of times in other programming languages; almost always with an \"=\". We prefer to refer to \"=\" as the \"assignment\" operator; not \"equals\".\n", "\n", "What goes on the left hand side of the assignment must be a '*valid variable name*'.\n", "\n", "Which of the following are valid variables, or valid ways to create variables in Python?\n", "\n", "```python\n", "my_integer = 3.1428571 \n", "_my_float = 3.1428571 # variables like this have a special use in Python\n", "__my_float__ = 3.1428571 # variables like this have a special use in Python\n", "€value = 42.95 \n", "cost_in_€ = 42.95\n", "cost_in_dollars = 42.95 \n", "42.95 = cost_in_dollars \n", "dollar.price = 42.95 \n", "favourite#tag = '#like4like'\n", "favourite_hashtag = '#일상'\n", "x = y = z = 1\n", "a, b, c = 1, 2, 3 # tuple assignment\n", "a, b, c = (1, 2, 3)\n", "i, f, s = 42, 12.94, 'spam'\n", "from = 'my lover'\n", "raise = 'your glass'\n", "pass = 'you shall not'\n", "fail = 'you will not'\n", "True = 'not False'\n", "pay day = 'Thursday'\n", "NA = 'not applicable' # for R users\n", "a = 42; # for MATLAB users: semi-colons are never required \n", "A = 13 # like most languages, Python is also case-sensitive \n", "```\n", "\n", "What's the most interesting idea/concept you learned from this?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the software editor you are using, is there a space where you can see the variable's current value? \\[This is called the *Watch* window in most graphical editors\\]\n", "\n", "![The 'Variable explorer'](./images/variable-explorer.png)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Variable types\n", "\n", "\n", "Each variable you create has a ``type``, which is automatically detected based on what is on the right hand side of the \"=\" sign. This is similar to MATLAB, but very different from C++ where you require this type of code:\n", "\n", "```c\n", "int a, b; // first declare your variables\n", "float result;\n", "a = 5; // then you get to use them\n", "b = 2;\n", "result = a / b; // you will get an unexpected value if you had defined \"result\" as \"int\"\n", "```\n", "\n", "In Python you have _dynamic typing_, where you simply write:\n", "```python\n", "a, b = 5, 2\n", "result = a / b\n", "```\n", "and Python figures out the most appropriate type from the context.\n", "\n", "Run those 2 lines of Python code. Then add this below. What is the output you see?\n", "```python\n", "type(a)\n", "type(result)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each variable always has a **type**. Usually you know what the type is, because you created the variable yourself at some point.\n", "\n", "But on occasion you use someone else's code and you get back an answer that you don't know the type of. Then it is useful to check it with the ``type(...)`` function.\n", "\n", "Try these lines in Python:\n", "```python\n", "type(99)\n", "type(99.)\n", "type(9E9)\n", "type('It\\'s raining cats and dogs today!') # How can you rewrite this line better?\n", "type(r'Brexit will cost you £8E8. Thank you.')\n", "type(['this', 'is', 'a', 'vector', 'of', 7, 'values'])\n", "type([])\n", "type(4 > 5)\n", "type(True)\n", "type(False)\n", "type(None)\n", "type({'this': 'is what is called a', 'dictionary': 'variable!'})\n", "type(('this', 'is', 'called', 'a', 'tuple'))\n", "type(())\n", "\n", "type(None)\n", "type(print) # anything that can be assigned to a variable name can be 'type checked'\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can convert most variables to a string, as follows: ``str(...)``\n", "\n", "Try these conversions to make sure you get what you expect:\n", "```python\n", "str(45)\n", "type(str(45))\n", "str(92.5)\n", "str(None)\n", "str(print)\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Calculations with variables\n", "\n", "The next step is to perform some calculations with the variables. \n", "\n", "The standard expressions exist in Python:\n", "\n", "| Operation | Symbol |\n", "|----------------|--------|\n", "| Addition | + |\n", "| Subtraction | - |\n", "| Multiplication | * |\n", "| Division | / |\n", "| Power of | ** |\n", "| Modulo | % | \n", "\n", "Please note: \"power of\" is not with the ^ operator, and can mislead you. Try this:\n", "* ``print(2 ^ 4)``\n", "* ``print(2**4)``\n", "\n", "If you are not familiar with the modulo operator, you can use it as follows: if you have a variable ``x`` and you want to check if it is exactly divisible by, for example, a number 5, then you can check if the modulus, the remainder, is zero.\n", "\n", "* ``x % 5`` \n", "* ``7 % 5`` evaluates to 2, since there's a remainder of 2 when 7 is divided by 5\n", "* ``10 % 5`` evaluates to 0, since there's no remainder after 10 is divided by 5" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Given the above, use Python as a calculator to find the values of these expressions:\n", "\n", "If ``a = 5`` and ``b = 9``\n", "\n", "* ``a / b``\n", "* What type is the result of the above expression?\n", "* ``a * b`` \n", "* What type is the result of the above expression?\n", "\n", "\n", "The distance $d$ travelled by an object falling for time $t$, given in seconds, is $$d=\\frac {1}{2}gt^{2}$$ where $g$ is the gravitational constant = $9.8\\, \\text{m.s}^{-2}$. Calculate the distance that you will travel in free-fall gravity in 10 seconds:\n", "\n", "```python\n", "t = ____ # seconds\n", "d = ____ # meters\n", "print('The distance fallen is ' + str(d) + ' meters.')\n", "```" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Try it now the other way around: the time taken for an object to fall is: $$ t= \\sqrt {\\frac {2d}{g}}$$\n", "\n", "We will introduce the ``sqrt`` function in the next section, but you can also calculate square root using a power of 0.5, as in $\\sqrt{x} = x^{0.5}$.\n", "\n", "Using that knowledge, how long will it take for an object to fall from the top of the building you are currently in:\n", "\n", "```python\n", "# Creates a string value in variable 'd'. Verify that it is a string type.\n", "d = input('The height of the building, in meters, which I am currently in is: ') \n", "d = float(d) # convert the string variable to a floating point value\n", "t = ____ # seconds\n", "\n", "# You might also want to investigate the \"round\" function at this point\n", "# to improve the output for variable t.\n", "\n", "print('The time for an object to fall from a building',\n", " 'of ' + str(d) + ' meters tall is ' + str(t) + \\\n", " ' seconds.')\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You wish to automate your workflow to write a standardized statistical report. It should appear as follows on the screen:\n", "\n", "> There were 4 outliers detected in the data set using Grubbs' test at the **99**% confidence level. These outliers will not be used in the subsequent calculations. The regression trend of **45.9** mg/day was detected for this product, with a p-value of **0.00341**. This indicates that there is an important **rising** trend over time.\n", "\n", "The 5 pieces in bold should be replaced with variables, so the above paragraph can be automatically written in the future with different variable values.\n", "\n", "Write the Python code, creating the 5 variables. Print your paragraph of text to the screen. The last variable can either be 'rising' or 'falling'. (In the next class we will see how you can use an if-else statement to write ``'rising'`` or ``'falling'`` depending on the sign of the regression slope." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python, like other languages, has the order of operations rules (same as the PEMDAS rules you might have learned in school):\n", "\n", "1. **P**arentheses (round brackets)\n", "2. **E**xponentiation or powers, left to right\n", "3. **M**ultiplication and Division, left to right\n", "4. Addition and **S**ubtraction, left to right\n", "\n", "So what is the result of these statements?\n", "```python\n", "a = 1 + 3 ** 2 * 4 / 2\n", "b = 1 + 3 ** (2 * 4) / 2\n", "c = (1 + 3) ** 2 * 4 / 2\n", "```\n", "\n", "While it is good to know these rules, the general advice is to always use brackets to clearly show your actual intention. \n", "> Never leave the reader of your code guessing: someone will have to maintain your code after you; including yourself, a few years later 😉 " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Write code for the following: \n", "\n", "Divide the sum of a and _b_ by the product of c and *d*, and store the result in x." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The above operators return results which are either ``int`` or ``float``. \n", "\n", "There are another set of operators which return ***bool***ean values: ``True`` or ``False``. We will use these frequently when we make decisions in our code. For example:\n", "> if \\_\\_<condition> \\_\\_ then \\_\\_<action\\>\\_\\_\n", "\n", "We cover **if-statements** in the [next module](https://yint.org/pybasic02).\n", "\n", "But for now, try out these ```` statements:\n", "\n", "```python\n", "3 < 5\n", "5 < 3\n", "4 <= 4\n", "4 <= 9.2\n", "5 == 5\n", "5. == 5 # float on the left, and int on the right. Does it matter?\n", "5. != 5 # does that make sense?\n", "True != False\n", "False < True\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Related to these operators are some others, which you can use to combine up: ``and`` and ``not`` and ``or``\n", "\n", "Try these out. What do you get in each case?\n", "\n", "```python\n", "True and not False\n", "True and not(False)\n", "True and True\n", "not(False) or False\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the quadratic equation $$ax^2 + bx + c=0$$ the short-cut solution is given by $$ x= -\\frac{b}{2a}$$\n", "but only if $b^2 - 4ac=0$ and $a \\neq 0$.\n", "\n", "Verify if you can use this short-cut solution for these combinations:\n", "\n", "* ``a=3, b=-1, c=2 # use tuple-assignment to create these 3 variables in 1 line of code``\n", "* ``a=0, b=-1, c=2`` \n", "* ``a=3, b=6, c=3`` \n", "\n", "Write the single line of Python code that will return ``True`` if you can use the shortcut, or ``False`` if you cannot." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Built-in constants and mathematical functions\n", "\n", "You will certainly need to calculate logs, exponentials, square roots, or require the value of $e$ or $\\pi$ at some point.\n", "\n", "In this last section we get a bit ahead, and load a Python library to provide this for us. Libraries - we will see later - are a collection of functions and variables that pre-package useful tools. Libraries can be large collections of code, and are for special purposes, so they are not loaded automatically when you launch Python.\n", "\n", "\n", "In MATLAB you can think of *Toolboxes* as being equivalent; in R you have *Packages*; in C++ and Java you also use the word *Library* for the equivalent concept.\n", "\n", "In Python, there are several libraries that come standard, and one is the ``math`` library. Use the ``import`` command to load the library. The ``math`` library can be used as follows:\n", "\n", "```python\n", "import math\n", "radius = 3 # cm\n", "area_of_circle = math.pi * radius**2\n", "print('The area of the circle is ' + str(area_of_circle))\n", "```\n", "\n", "Now that you know how to use the ``math`` library, it is worth searching what else is in it:\n", "\n", "> https://www.google.com/search?q=python+math+library\n", "\n", "All built-in Python libraries are documented in the same way. Searching this way usually brings up the link near the top. Make sure you look at the documentation for Python version 3.x.\n", "\n", "Now that you have the documentation ready, use functions from that library to calculate:\n", "\n", "* the *ceiling* of a number, for example ``a = 3.7``\n", "* the *floor* of a number, for example ``b = 3.7``\n", "* the *absolute* value of ``c = -2.9``\n", "* the log to the base $e$ of ``d = 100``\n", "* the log to the base 10 of ``e = 100``\n", "* the Golden ratio ${\\dfrac {1+{\\sqrt {5}}}{2}}$ \n", "* check that the factorial n=9, in other words $n!$ is equal to 362880\n", "* and see that Stirling's approximation, $n! \\approx \\sqrt{2\\pi n} \\cdot n^n e^{-n}$ for a factorial matches closely [you will use 4 different methods from the ``math`` library to calculate this!]\n", "\n", "```python\n", "\n", "print('The true value of 9! is ' + ___ + ', while the Stirling approximation is ' + ___)\n", "```\n", "\n", "* verify that the cosine of ``g`` = $2\\pi$ radians is indeed 1.0\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Last exercises" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. The population of a country could be approximated by the formula $$ p(t) = \\dfrac{197 273 000}{1 + e^{− 0.03134(t − 1913)}}$$\n", "where the time $t$ is in years.\n", "\n", " * What is the population in 1913?\n", " * What is the population in 2013?\n", " * Does the population grow and grow without bounds, or does it reach steady state (it stabilizes at some constant value eventually)\n", " \n", "1. Explain to your partner whom you are working with, what some of the benefits are of writing your code in Python files.\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# IGNORE this. Execute this cell to load the notebook's style sheet.\n", "from IPython.core.display import HTML\n", "css_file = './images/style.css'\n", "HTML(open(css_file, \"r\").read())" ] } ], "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.7.3" }, "toc": { "base_numbering": "1", "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "349px" }, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }