{ "cells": [ { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "A quick note before the introduction: Jupyter/IPython Notebooks are composed of segments called cells. There are several cell types: \n", "* **Code** cells contain source code. \n", "* **Markdown** cells contain text.\n", "* **Raw NBContent** cells contain content that should be unmodified in output.\n", "* **Heading** cells used to contain simple headings. They are not used much anymore.\n", "\n", "We will primarily use **Code** and **Markdown** types. You can change the cell type in the drop down menu above. I have set this cell to be 'Markdown', but by default cells are of 'Code' type.\n", "\n", "To execute a cell you can use 'Shift+Enter' or execute button at the top. When you execute a markdown cell, it changes in appearance and becomes as text. When you execute a code cell, output of that cell is appended at the bottom. \n", "\n", "For the HW0 assignments I will ask you to execute several cells in this document. After you are done, you should save the file using save button at the top. You can then submit the file to me through **Blackboard**, and I will be able to see the changes you've made (including output of the cells). " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " ***ASSIGNMENT 1:*** " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "Modify **this** cell to be **Markdown** and run this cell (useful shortcuts for running a cell are 'Ctrl+Enter' and 'Shift+Enter' )\n", " \n", " - More shortcuts at: https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction\n", "Notebook documents (or “notebooks”, all lower case) are documents produced by the Jupyter Notebook App which contain both computer code (e.g. python) and rich text elements (paragraph, equations, figures, links, etc...). Notebook documents are both human-readable documents containing the analysis description and the results (figures, tables, etc..) as well as executable documents which can be run to perform data analysis. (https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Syntax\n", "The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Identifers\n", "A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore (\\_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and \\% within identifiers. Python is a case sensitive programming language. Thus, XYZ and xyz are two different identifiers in Python." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Reserved Keywords\n", "The following list shows the Python keywords. These are reserved words and you cannot use them as constant or variable or any other identifier names. List of keywords: \n", "\n", "**and, exec, not, assert, finally,\tor, break, for, pass, class, from, print, continue, global, raise, def, if, return, del, import, try, elif, in, while, else, is, with, except, lambda, yield**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Lines and Indentation\n", "Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. All statements within the block must be indented the same amount. In Python all the continuous lines indented with same number of spaces would form a block. \n", "\n", "Note: Do not try to understand the logic at this point of time. Just make sure you understood various blocks even if they are without braces." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Multi-Line Statements\n", "Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\\\\) to denote that the line should continue. Statements contained within the [], {}, or () brackets do not need to use the line continuation character.\n", "\n", "### Quotation in Python\n", "Python accepts single ('), double (\") and triple (''' or \"\"\") quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. \n", "\n", "### Comments in Python\n", "A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Assignments\n", "Variables are reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables.\n", "\n", "### Assigning Values to Variables\n", "Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.\n", "\n", "The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100\n", "1000.0\n", "John\n" ] } ], "source": [ "counter = 100 # An integer assignment\n", "miles = 1000.0 # A floating point\n", "name = \"John\" # A string\n", "\n", "print counter\n", "print miles\n", "print name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***ASSIGNMENT 2:*** Run the cell below ('Ctrl+Enter' or 'Shift+Enter')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "myCounter = 10 # An integer assignment\n", "print myCounter # output myCounter variable" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Loops\n", "In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. A *loop statement* allows us to execute a statement or group of statements multiple times.\n", "\n", "#### Loop Architecture\n", "Python provides the following types of loops to handle looping requirements.\n", "\n", "##### while loop\n", "Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "counter= 0\n", "counter= 1\n", "counter= 2\n", "counter= 3\n", "counter= 4\n", "counter= 5\n", "counter= 6\n", "counter= 7\n", "counter= 8\n", "counter= 9\n" ] } ], "source": [ "counter = 0\n", "while counter<10: # Try changing 10 to 20 and re-running this cell \n", " print \"counter=\",counter\n", " counter = counter + 1 # Try changing 1 to 3 and re-running this cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### for loop\n", "Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "counter= 10\n", "counter= 11\n", "counter= 12\n", "counter= 13\n" ] } ], "source": [ "for counter0 in [10, 11, 12, 13]: # Try changing this list to [3,4,5] and re-running this cell\n", " print \"counter=\",counter0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note: You can use one or more loop inside any another while, for loop.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***ASSIGNMENT 3:*** Run the cell below" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "counter1 = 0\n", "while counter1<50:\n", " print \"Outer loop counter = \", counter1\n", " for counter2 in [3, 5, 7]:\n", " print \"Inner loop counter = \", counter2\n", " print \"Sum of the two counters during current iteration is\",counter1+counter2\n", " counter2 = counter2 + 1\n", " counter1 = counter1 + 10" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Loop Control Statements\n", "Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.Pyt hon supports the following control statements. \n", "\n", "##### break statement\n", "Terminates the loop statement and transfers execution to the statement immediately following the loop.\n", "\n", "##### continue statement\n", "Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.\n", "\n", "##### pass statement\n", "The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions\n", "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.\n", "\n", "#### Defining a Function\n", "You can define functions to provide the required functionality. Here are rules to define a function in Python.\n", "* Function blocks begin with the keyword **def** followed by the function name and parentheses ( ( ) ).\n", "* Input parameters (or arguments) should be placed within these parentheses. \n", "* The code block within every function starts with a colon (**:**) and is indented.\n", "* The statement **return** exits a function, passing back an expression to the caller. A return statement with no arguments is the same as **return None**." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def myAddFunction1( param1, param2 ):\n", " print \" Running myAddFunction1 ...\"\n", " print \"param1 =\",param1,\" param2=\",param2\n", " myOut = param1 + param2\n", " return myOut" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Running a Function\n", "You can run functions by typing its name and passing necessary parameters in parentheses" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Running myAddFunction1 ...\n", "param1 = 2 param2= 3\n" ] }, { "data": { "text/plain": [ "5" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myAddFunction1(2,3) # Try modifying the numbers and re-executing this cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***ASSIGNMENT 4:*** Modify the function below to calculate the product of param1 and param2 and run the two cells below" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def myProductFunction1( param1, param2 ):\n", " print \" Running myAssignmentFunction1 ...\"\n", " print \"param1 =\",param1,\" param2=\",param2\n", " out = param1 + param2\n", " return out" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "myProductFunction1(2,3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Default arguments\n", "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default if not passed" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Function definition is here\n", "def myAddFunction2( param1, param2 = 7 ):\n", " print \" Running myAddFunction2...\"\n", " myOut = param1 + param2\n", " return myOut" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Running myAddFunction2...\n", "10\n", " Running myAddFunction2...\n", "8\n" ] } ], "source": [ "print myAddFunction2(3)\n", "print myAddFunction2(3,5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Variable-length arguments\n", "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments." ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def myAddFunction3( param1, *moreParams ):\n", " print \" Running myAddFunction3...\"\n", " myOut = param1 + moreParams[0] + moreParams[1]\n", " return myOut" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " Running myAddFunction3...\n" ] }, { "data": { "text/plain": [ "14" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "myAddFunction3(3,4,7)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Anonymous Functions\n", "These functions are called anonymous because they are not declared in the standard manner by using the **def** keyword. You can use the **lambda** keyword to create small anonymous functions.\n", "\n", "* Lambda forms can take any number of arguments **but return just one value** in the form of an expression. They cannot contain commands or multiple expressions.\n", "* An anonymous function cannot be a direct call to print.\n", "* Lambda functions cannot access variables other than those in their parameter list and those in the global namespace.\n", "* The syntax of lambda functions contains only a single statement: lambda [arg1 [,arg2,.....argn]]:expression" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Function definition is here\n", "mySum3Fun = lambda arg1, arg2, arg3: arg1 + arg2 + arg3;" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Value of total : 60\n", "Value of total : 70\n" ] } ], "source": [ "# Now you can call sum as a function\n", "print \"Value of total : \", mySum3Fun( 10, 20, 30 )\n", "print \"Value of total : \", mySum3Fun( 20, 20, 30 )" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Scope of Variables\n", "All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The **scope** of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python − **global variables** and **local variables**:\n", "\n", "* Variables that are defined inside a function body have a local scope\n", "* Variables that are defined outside have a global scope.\n", "\n", "This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Classes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Class**: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.\n", "\n", "**Method**: A special kind of function that is defined in a class definition.\n", "\n", "**Object**: A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Additional Links:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Jupyter Notebook Basics: http://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Notebook%20Basics.ipynb\n", "\n", "Running Code in Jupyter Notebook: http://nbviewer.jupyter.org/github/jupyter/notebook/blob/master/docs/source/examples/Notebook/Running%20Code.ipynb)\n", "\n", "Pyton Tutorial: http://www.tutorialspoint.com/python/index.htm" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.13" } }, "nbformat": 4, "nbformat_minor": 0 }