{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "(variables)=\n", "# Variables\n", "\n", "A variable is an object that contains an assigned value:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "a = 10 # a is a variable containing a number\n", "b = \"hello\" # b is a variable containing a string (text)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Certain words have a special meaning in Python and cannot be used as variable names. These are: `and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, with, while,` and `yield`.\n", "\n", "Good variable names are usually descriptive, can be one letter symbols, abbreviation of words, containing lower/upper case, underscores, digits. They cannot start with digits. Variables are case sensitive so variable `a` is not the same as `A`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(variable_types)=\n", "## Types of variables\n", "Common types of Python variables are:\n", "- _str_ - string, e.g. `\"Hello world!\"`\n", "- _int_ - integer numbers, e.g. `5`\n", "- _float_ - floating point numbers, e.g. `5.0`, `5.2`\n", "- _bool_ - boolean value, i.e. `True` or `False`\n", "\n", "Integer and floating point numbers are different types of variables and a computer stores them differently. Computers use a discrete representation of numbers, which means that there is a gap between two adjacent numbers. For integers this gap is 1 and for floats it is much much smaller. For example, in integer arithmetic 0 and 0.999999 are the same numbers. We will therefore almost always use floating point numbers." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1\n" ] } ], "source": [ "a = int(0.99999999)\n", "b = int(1.00000001)\n", "print(a, b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To check what type a variable is, we can use the in-built `type()` function that takes the variable as an argument:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n" ] } ], "source": [ "a = \"some text\" # string\n", "b = 5 # integer\n", "c = 5. # float\n", "d = True # boolean\n", "\n", "print(type(a))\n", "print(type(b)) \n", "print(type(c))\n", "print(type(d))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(variable_operations)=\n", "## Operations on variables\n", "### Numbers\n", "An integer-type variable will automatically change to float if it is required for mathematical accuracy:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11 \n", "12.1 \n", "2.5 \n" ] } ], "source": [ "b = 10 # An integer\n", "b = 1 + b # b should be still an int\n", "print(b, type(b))\n", "\n", "b = 1.1 + b # b should change into float\n", "print(b, type(b))\n", "\n", "b = 10 # An integer\n", "b = b/4 # A float\n", "print(b, type(b))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can make calculations on numbers stored in variables and program mathematical formulae. For example, a position for a ball in vertical motion is given by:\n", " \\\\(y(t) = v_0t- \\frac{1}{2}gt^2 \\\\)\n", "where the ball starts at $y=0$ at time $t=0$ and:\n", "\n", "* $y$ is the height (position) as a function of time $t$\n", "* $v_0$ is the initial velocity (at $t=0$)\n", "* $g$ is the acceleration due to gravity\n", "\n", "Given $v_0$, $g$ and $t$, we can compute the value $y$:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The position of the ball at time t = 0.30 s is y = 3.31 m.\n" ] } ], "source": [ "v0 = 12.5 # m/s\n", "g = 9.81 # m/s2\n", "t = 0.3 # s\n", "y = v0*t - 0.5*g*t**2\n", "print(\"The position of the ball at time t = %.2f s is y = %.2f m.\" % (t, y))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Strings\n", "We can add strings together:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "some text \n", "some text and more text \n" ] } ], "source": [ "a = \"some text\" # A string\n", "print(a, type(a))\n", "a = a + \" and more text\" # Add a string at the end of 'a'\n", "print(a, type(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can slice strings to get specific parts of them by using the following syntax:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "so\n", "some text and more te\n", "sm et\n" ] } ], "source": [ "# Print characters 0, 1 excluding 2\n", "# (Python counts from zero!!!)\n", "print(a[0:2])\n", "\n", "# Print all characters but last two\n", "print(a[0:-2])\n", "\n", "# Print every second character\n", "# from first 10 characters\n", "print(a[0:10:2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Searching strings:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "To what use serves learning, if understanding be away.\n", "8\n", "True\n", "True\n", "To what use serves studying, if understanding be away.\n", "To what use serves learning, if understanding be away.\n" ] } ], "source": [ "s = \"To what use serves learning, if understanding be away.\"\n", "\n", "print(s)\n", "print(s.find(\"use\")) # returns the index of the first character if found\n", "print(\"if\" in s) # returns True if string 'if' is contained in 's', False otherwise\n", "print(\"is\" not in s) # returns True if string 'is' is not contained in 's', False otherwise\n", "\n", "s2 = s.replace(\"learning\", \"studying\") # replaces learning with studying in 's'\n", "print(s2)\n", "\n", "s3 = s.replace(\"learnning\", \"studying\") # does nothing if we make a typo\n", "print(s3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Splitting and joining:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Dare', 'to', 'be', 'wise;', 'begin!']\n", "['Dare to be wise', ' begin!']\n", "Dare to be wise: begin!\n" ] } ], "source": [ "s = \"Dare to be wise; begin!\"\n", "words = s.split() # Splits the string based on spaces\n", "print(words)\n", "\n", "phrases = s.split(\";\") # Add a string by which splitting will happen\n", "print(phrases)\n", "\n", "print(\":\".join(phrases)) # Join phrases with a collon" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other useful functions:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "False\n", "i like watermelons! i like trains! i like books!\n", "I LIKE WATERMELONS! I LIKE TRAINS! I LIKE BOOKS!\n", "False\n", "True\n", " I like watermelons! I like trains! I like books! \n", "I like watermelons! I like trains! I like books!\n", "56\n" ] } ], "source": [ "s = \"I like watermelons! I like trains! I like books!\"\n", "\n", "print(s.count(\"!\")) # Count how many times string '!' occurs in 's'\n", "print(s[5].isnumeric()) # Check if the sixth character is a number\n", "print(s.lower()) # Make all characters lower case\n", "print(s.upper()) # Make all characters upper case\n", "print(s.isalpha()) # Check if all characters are letters\n", "print(s[2:5].isalpha()) # Check if the characters 3 to 5 are letters\n", "\n", "s = \" \" + s + \" \"\n", "print(s)\n", "print(s.strip()) # Strips strings from tabs, spaces, new line characters from\n", " # beginning and end of the string\n", " \n", "print(len(s)) # Print how many characters the string has" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Booleans\n", "\n", "Booleans are objects in Python that are `True` or `False`. The simplest booleans are:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print(True)\n", "print(False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Objects can be compared to one another, where `print` statements will return `True` or `False`. Standard mathematical formulae in Boolean expressions are:\n", "- $a = b$ is `a == b`\n", "- $a \\neq b$ is `a != b`\n", "- $a > b$ is `a > b`\n", "- $a \\geq b$ is `a >= b`\n", "- $a < b$ is `a < b`\n", "- $a \\leq b$ is `a <= b` \n", "\n", "An example use below:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "False\n", "True\n", "False\n", "True\n" ] } ], "source": [ "a = 5\n", "print(a > 10)\n", "print(a == 10)\n", "print(a <= 5)\n", "print(a != 5)\n", "print(a != \"cat\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Compound conditions with logical operators can also be used:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "True\n", "False\n" ] } ], "source": [ "a = 5\n", "b = 20\n", "\n", "print((a < 6) and (b > 18)) # For 'and' both expressions need to be True to return True\n", "print((a < 5) and (b > 18)) # Returns false because the first expression is False\n", "print((a < 5) or (b > 18)) # For 'or' only one expression is needed to be True\n", "\n", "# 'and' and 'or' can be combined, but brackets matter!!\n", "\n", "print((a > 10 and b < 10) or b > 13)\n", "print(a > 10 and (b < 10 or b > 13))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(variable_exercises)=\n", "## Exercises\n", "----------------\n", "\n", "* **Print** the value of the expression \\\\((a + b - c^4) \\div d \\\\) where\n", "\\\\(a=1; b=4; c = 3; d =17\\\\). Check the type of the expression." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", "\n", "```python\n", "a = 1\n", "b = 4\n", "c, d = 3, 17\n", "\n", "result = (a + b - c**4)/d\n", "\n", "print(result)\n", "print(type(result))\n", "```\n", " \n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "-----------\n", "* **Integer division**: Very popular operators in Computer Science include integer (or *floor*) division `//` and modulus operator `%`. Think what operation combined with type casting can result in integer division. Check the working of your operator using the equality \\\\( div(a, b) * b + a \\% b = a\\\\) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", "\n", "```python\n", "print(50//6 * 6 + 50%6 == 50)\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_______\n", "* **String slicing**: Let `a = \"Bananas\"` and `b = \"Apples\"`: \n", " - concatenate the strings\n", " - take even characters from the resulting string\n", " - take the last three characters\n", "\n", "Print the intermediate results." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer\n", ":class: dropdown\n", "\n", "```python\n", "a = \"Bananas\"\n", "b = \"Apples\"\n", "\n", "c = a + b\n", "print(c)\n", "c = c[::2]\n", "print(c)\n", "c = c[-3:]\n", "print(c)\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "----------\n", "* **Lorem Ipsum**: Count the number of 'l' characters in the following text (used as dummy text in web development), then count the number of words:\n", "\n", "*Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices tempus faucibus. Mauris id porta turpis, a sodales leo. Nam fringilla dolor at tellus auctor, ut sollicitudin augue gravida. Proin vitae sem ligula. Suspendisse vel erat elit. Sed fringilla massa ut iaculis vestibulum. Fusce placerat est id felis semper facilisis.*\n", "\n", "**HINT**: There is whitespace between any two words!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "````{admonition} Answer \n", ":class: dropdown\n", "\n", "```python\n", "a = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ultrices tempus faucibus. Mauris id porta turpis, a sodales leo. Nam fringilla dolor at tellus auctor, ut sollicitudin augue gravida. Proin vitae sem ligula. Suspendisse vel erat elit. Sed fringilla massa ut iaculis vestibulum. Fusce placerat est id felis semper facilisis.\"\n", "\n", "print(a.count('l'))\n", "print(a.count(' ') + 1) # number of words\n", "```\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* **Boolean short circuit**: Consider the following code:\n", "\n", "```python\n", "def f(a):\n", " a += 1\n", " return True\n", "\n", "a = 0\n", "if(1 > 2 or f(a)):\n", " print(a)\n", " \n", "```\n", " \n", "f defines an increment function, what will the programme print?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{admonition} Answer\n", ":class: dropdown\n", "\n", "0\n", "\n", "```" ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 4 }