{ "cells": [ { "cell_type": "markdown", "metadata": { "tags": [ "s1", "content", "l1" ] }, "source": [ "# Python Advanced\n", "\n", "A continuation of the previous lesson \"Introduction to Python\", here we introduce more advanced concepts.\n", "\n", "## Operators\n", "\n", "Operators are the constructs which can manipulate the value of operands.\n", "\n", "### Arithmetic Operators\n", "\n", "The standard operators are +, -, *, **, /, % for addition, subtraction, multiplication, exponentials, division and modulus respectively.\n", "\n", "### Example:\n", "\n", "```\n", "var_a = 10\n", "var_b = 5\n", "var_sum = var_a + var_b\n", "```\n", "\n", "### Relational/Comparison Operators\n", "\n", "The comparison operators are similar to any other language with the commonly known symbols >, <, =, ==, >=, <= denoting, greater than, less than, assignment, equal to, greater than or equal to and less than or equal to respectively. \n", "\n", "### Example:\n", "\n", "To compare equality of the two variables, var_a and var_b and assign the result (True or False) to variable, var_c:\n", "\n", "```\n", "var_c = var_a == var_b\n", "```\n", "\n", "### Exercise\n", "\n", "Try out the above example by assigning ```var_a```, a value of 5 and ```var_b```, a value of 10. Store the comparaed result in var_c and print it out." ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": true, "tags": [ "s1", "ce", "l1" ] }, "outputs": [], "source": [ "var_a = 5\n", "var_b = 10\n", "\n", "# Assign result of comparison of above variables to var_c" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": true, "tags": [ "s1", "l1", "hint" ] }, "outputs": [], "source": [ "# Hint\n", "\n", "# var_a and var_b are not equal" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "tags": [ "s1", "l1", "ans" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "var_c = var_a == var_b\n", "print (var_c)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "tags": [ "s1", "hid", "l1" ] }, "outputs": [], "source": [ "ref_tmp_var = False\n", "\n", "try:\n", " if var_c == False:\n", " ref_assert_var = True\n", " ref_tmp_var = True\n", " else:\n", " ref_assert_var = False\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "except Exception:\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "\n", "\n", "assert ref_tmp_var" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l2", "content", "s2" ] }, "source": [ "### Membership Operator (in)\n", "\n", "Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. If x is a subset of y, then the result is True:\n", "\n", "```\n", ">>> if var_a in [1, 2, 3, 4, 5, 6]:\n", "...   print(\"True\")\n", "True\n", "```\n", "\n", "### Identity Operators (is)\n", "\n", "Identity operators compare the memory locations of two python objects and returns True if they point to the same location.\n", "\n", "Two objects can contain the same value but can be different objects. Here is an example which illustrates the 'is' operator:\n", "\n", "```\n", "a = 'This '\n", "b = a + 'is a python tutorial'\n", "c = 'This is a python tutorial'\n", "\n", ">> b == c\n", "True\n", ">> b is c\n", "False\n", "```\n", "\n", "Ref: https://docs.python.org/3/library/operator.html\n", "\n", "### Loops\n", "\n", "The two commonly used loops are the While loop and the For loop.\n", "\n", "#### While Loop\n", "\n", "Note that Python works with indentation and no braces are necessary. The next line of code following the loops or conditions or function blocks should have an indentation of two spaces or four spaces.\n", "\n", "Syntax: \n", "\n", "```\n", "While :\n", "  statements\n", "Example:\n", "i = 1\n", "while i < 5:\n", "  i += 1\n", "```\n", "\n", "#### For Loop\n", "\n", "Syntax:\n", "\n", "range(1, 10) -- generates a list of numbers from 1 to 10\n", "\n", "for i in range(1, 10):\n", "\n", "   statements\n", "\n", "Ref: https://docs.python.org/3/tutorial/controlflow.html\n", "\n", "### Exercise\n", "\n", "Compute the square of each number in X and assign it to a list y\n", "print y." ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": true, "tags": [ "l2", "ce", "s2" ] }, "outputs": [], "source": [ "x = range(1, 10)\n", "y = []" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": true, "tags": [ "l2", "s2", "hint" ] }, "outputs": [], "source": [ "# To compute power of a variable, use **" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "tags": [ "l2", "s2", "ans" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81]\n" ] } ], "source": [ "for i in x:\n", " y.append(i**2)\n", "\n", "print(y)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "tags": [ "l2", "hid", "s2" ] }, "outputs": [], "source": [ "ref_tmp_var = False\n", "\n", "try:\n", " import numpy as np\n", "\n", " if np.all(y == [1, 4, 9, 16, 25, 36, 49, 64, 81]):\n", " ref_assert_var = True\n", " ref_tmp_var = True\n", " else:\n", " ref_assert_var = False\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "except Exception:\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "\n", "assert ref_tmp_var" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l3", "s3", "content" ] }, "source": [ "## Decision Making\n", "\n", "Decision Making is to execute a set of statements based on the validation of a condition. The decision making in Python involves an 'if' condition that is written as:\n", "\n", "Syntax:\n", "\n", "\n", "if condition:\n", "\n", "  statements\n", "\n", "Ref: https://docs.python.org/3/tutorial/controlflow.html\n", "\n", "#### Exercise\n", "\n", "Push even numbers in [0, 10] to the list variable even_numbers\n", "\n", "print even_numbers" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": true, "tags": [ "l3", "s3", "ce" ] }, "outputs": [], "source": [ "even_numbers = []\n", "x = range(0, 10)" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l3", "s3", "hint" ] }, "source": [ "Hint: Use the for loop" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "tags": [ "l3", "s3", "ans" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8]\n" ] } ], "source": [ "for i in x:\n", " if (i%2) == 0:\n", " even_numbers.append(i)\n", "print(even_numbers)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "tags": [ "l3", "s3", "hid" ] }, "outputs": [], "source": [ "ref_tmp_var = False\n", "\n", "try:\n", " import numpy as np\n", "\n", " even_numbers_ = []\n", "\n", " for i in x:\n", " if (i%2) == 0:\n", " even_numbers_.append(i)\n", "\n", " if np.all(even_numbers == even_numbers_): \n", " ref_assert_var = True\n", " ref_tmp_var = True\n", " else:\n", " ref_assert_var = False\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "except Exception:\n", " print('Please follow the instructions given and use the same variables provided in the instructions.') \n", "\n", "assert ref_tmp_var" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l4", "s4", "content" ] }, "source": [ "## More Data Types\n", "\n", "### Tuples\n", "\n", "A tuple is a sequence of immutable sequential objects. Tuples use parentheses for access unlike lists and cannot be changed. It is an ordered sequence and used for objects such as coordinates that contain latitude, longitude.\n", "\n", "Example: \n", "\n", "```\n", "loc = (30.456, 50.436)\n", "```\n", "\n", "Ref: https://docs.python.org/3/c-api/tuple.html\n", "\n", "### Sets\n", "\n", "Sets are collection types and very useful for Mathematicians, Statisticians and Data Scientists. A set contains an unordered collection of unique objects of the same type. It is equivalent to the mathematical definition of sets.\n", "\n", "```\n", "even_number_set = set([0, 2, 4, 6])\n", "```\n", "\n", "Ref: https://docs.python.org/3/c-api/set.html\n", "\n", "### Dictionary\n", "\n", "Dictionaries are hash maps containing key-value pairs. While the keys need to be unique, the referenced values need not be. The values are accessed via the keys.\n", "\n", "Example: A dictionary of city to state:\n", "```\n", "location_dict = {'Boston': 'MA', 'Chicago': 'IL', 'New York': 'NY'}\n", "```\n", "\n", "Ref: https://docs.python.org/3/c-api/dict.html\n", "\n", "### Exercise\n", "\n", "Build a location map that contains latitude and longitude of the following cities.\n", "\n", "Boston: 42.318365, -71.086692
Chicago: 41.797568, -87.620958
New York: 40.685526, -73.887406

\n", "Assign it to the variable location_map \n", "\n", "Print out the variable location_map" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true, "tags": [ "l4", "s4", "ce" ] }, "outputs": [], "source": [ "location_map = {}" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "s4", "l4", "hint" ] }, "source": [ "Hint: Use dictionary and tuples." ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "tags": [ "s4", "l4", "ans" ] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Boston': (42.318365, -71.086692), 'Chicago': (41.797568, -87.620958), 'New York': (40.685526, -73.887406)}\n" ] } ], "source": [ "location_map = {'Boston': (42.318365, -71.086692),\n", " 'Chicago': (41.797568, -87.620958), \n", " 'New York': (40.685526, -73.887406)}\n", "print(location_map)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "tags": [ "s4", "hid", "l4" ] }, "outputs": [], "source": [ "ref_tmp_var = False\n", "\n", "try:\n", " location_map_ = {'Boston': (42.318365, -71.086692),\n", " 'Chicago': (41.797568, -87.620958), \n", " 'New York': (40.685526, -73.887406)}\n", "\n", " if location_map == location_map_:\n", " ref_assert_var = True\n", " ref_tmp_var = True\n", " else:\n", " ref_assert_var = False\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "except Exception:\n", " print('Please follow the instructions given and use the same variables provided in the instructions.') \n", "\n", "assert ref_tmp_var" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l5", "content", "s5" ] }, "source": [ "## Functions and Modules\n", "\n", "### Functions\n", "\n", "A function is a block of code that executes in a sequence and can be invoked in a repeated fashion. We have already used some functions such as .append(), .pop(), print(). These are called 'builtin' functions. We can also define our own set of functions. Here is an example of a function that takes in two numbers and returns their sum:\n", "\n", "```\n", "def add_values(x, y):\n", "  z = x + y\n", "  return z\n", "```\n", "\n", "Here x, y, z are called local variables as they only retain their values inside the function. This function is invoked as:\n", "\n", "```\n", ">>print(add_values(5, 10))\n", "15\n", "```\n", "\n", "### Modules in Python\n", "\n", "Python has a standard library where functions such as print(), range(), len() can be invoked at any point in our code. However, some functions that belong to a category of operations often exist in modules. For example, if we intend to use a logartithm, a square root operation, then such operations exist in a module called the 'math' module. Similarly, there are tons of modules in python that we can leverage to write our code. These modules need to be imported to use them.\n", "\n", "To import a module you must explicity specify 'import ' in the beginning of your code.\n", "\n", "For example, to compute a square root of a number:\n", "\n", "```\n", "import math\n", "\n", "print(math.sqrt(25))\n", "5\n", "```\n", "\n", "These modules sometimes are heavy in terms of memory of functions that are loaded. Also modules are often built up of submodules that could be imported to save memory. Consider a module built of a heirarchy of submodules in this manner:\n", "\n", "For example consider module A that has submodule B, C, D as submodules. Suppose the submodule D has a function func(), which is all we need for our code. Then, we can import just the submodule in a heirarchial fashion as:\n", "\n", "```\n", "from A.C import D\n", "\n", "D.func()\n", "```\n", "\n", "### Exercise\n", "\n", "Write a function, compute_sqrt(x), which takes a non-negative number as an input and returns a dictionary with key as number and square root of the number as its value.\n", "* Invoke the function compute_sqrt(25), assign it to variable sqrt_25 and print it out." ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": true, "tags": [ "l5", "ce", "s5" ] }, "outputs": [], "source": [ "import math\n", "\n", "# def compute_sqrt(x):\n", "# " ] }, { "cell_type": "markdown", "metadata": { "tags": [ "l5", "s5", "hint" ] }, "source": [ "Hint: Use { key: value } to specify a dictionary" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "tags": [ "l5", "s5", "ans" ] }, "outputs": [], "source": [ "def compute_sqrt(x):\n", " return {x: math.sqrt(x)}\n", "\n", "sqrt_25 = compute_sqrt(25)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "tags": [ "hid", "l5", "s5" ] }, "outputs": [], "source": [ "ref_tmp_var = False\n", "\n", "try:\n", " if sqrt_25[25] == 5:\n", " ref_assert_var = True\n", " ref_tmp_var = True\n", " else:\n", " ref_assert_var = False\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "except Exception:\n", " print('Please follow the instructions given and use the same variables provided in the instructions.')\n", "\n", "assert ref_tmp_var" ] } ], "metadata": { "executed_sections": [], "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.1" }, "rf_version": 1 }, "nbformat": 4, "nbformat_minor": 2 }