{ "metadata": { "name": "", "signature": "sha256:29e3376dda05a6c55add6cd786acc285f136d0e29ad6a7407fa46b07c78f51ad" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#I-[Python](https://www.python.org/)\n", "\n", "Lecturer:*Jos\u00e9 Pedro Silva*[1](http://www-num.math.uni-wuppertal.de/en/amna/people/jose-pedro-silva.html) - [silva_at_math.uni-wuppertal.de](mailto:silva_at_math.uni-wuppertal.de)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This notebook is based on the one provided by [rjohansson](http://nbviewer.ipython.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-1-Introduction-to-Python-Programming.ipynb)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import antigravity" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "import this" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Index" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- [Character Encoding](#character_encoding)\n", "- [Modules](#modules)\n", "- [Variables and Types](#variables_and_types)\n", "- [Fundamental Types](#fundamental_types)\n", "- [Operators and Comparisons](#operators_and_comparisons)\n", "- [Compound Types](#compound_types)\n", "- [Control Flow](#control_flow)\n", "- [Loops](#loops)\n", "- [Functions](#functions)\n", "- [Classes](#classes)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python program files\n", "\n", "* Python code is usually stored in text files with the file ending \"`.py`\":\n", "\n", " myprogram.py\n", "\n", "* Every line in a Python program file is assumed to be a Python statement. \n", "\n", " * The only exception is comment lines, which start with the character `#` (optionally preceded by an arbitrary number of white-space characters, i.e., tabs or spaces). Comment lines are usually ignored by the Python interpreter.\n", "\n", "\n", "* To run our Python program from the command line we use:\n", "\n", " $ python myprogram.py\n", "\n", "* On UNIX systems it is common to define the path to the interpreter on the first line of the program (note that this is a comment line as far as the Python interpreter is concerned):\n", "\n", " #!/usr/bin/env python\n", "\n", " If we do, and if we additionally set the file script to be executable, we can run the program like this:\n", "\n", " $ myprogram.py\n", "\n", "#### Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "script_dir = '../scripts/'" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "ls $script_dir\"hello-world\"*.py" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "../scripts/hello-world-in-portuguese.py ../scripts/hello-world.py\r\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "cat $script_dir\"hello-world.py\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "#!/usr/bin/env python\r\n", "\r\n", "print(\"Instituto Superior de Economia e Gestao!\")\r\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "!python $script_dir\"hello-world.py\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Instituto Superior de Economia e Gestao!\r\n" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Character encoding\n", "\n", "The standard character encoding is ASCII, but we can use any other encoding, for example UTF-8. To specify that UTF-8 is used we include the special line\n", "\n", " # -*- coding: UTF-8 -*-\n", "\n", "at the top of the file." ] }, { "cell_type": "code", "collapsed": false, "input": [ "!ls $script_dir" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "hello-world-in-german.py~ hello-world-in-portuguese.py hello-world.py hello-world.py~\r\n" ] } ], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [ "cat $script_dir\"hello-world-in-portuguese.py\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "#!/usr/bin/env python\r\n", "# -*- coding: UTF-8 -*-\r\n", "\r\n", "print(\"Instituto Superior de Economia e Gest\u00e3o!\")\r\n" ] } ], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "!python $script_dir\"hello-world-in-portuguese.py\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Instituto Superior de Economia e Gest\u00e3o!\r\n" ] } ], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other than these two *optional* lines in the beginning of a Python code file, no additional code is required for initializing a program." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modules\n", "\n", "Most of the functionality in Python is provided by *modules*. \n", "\n", "To use a module in a Python program it first has to be imported. A module can be imported using the `import` statement. For example, to import the module `math`, which contains many standard mathematical functions, we can do:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import math" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 26 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This includes the whole module and makes it available for use later in the program. For example, we can do:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import math\n", "\n", "x = math.cos(2 * math.pi)\n", "\n", "print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.0\n" ] } ], "prompt_number": 27 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, we can chose to import all symbols (functions and variables) in a module to the current namespace (so that we don't need to use the prefix \"`math.`\" every time we use something from the `math` module:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from math import *\n", "\n", "x = cos(2 * pi)\n", "\n", "print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.0\n" ] } ], "prompt_number": 28 }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a third alternative, we can chose to import only a few selected symbols from a module by explicitly listing which ones we want to import instead of using the wildcard character `*`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from math import cos, pi\n", "\n", "x = cos(2 * pi)\n", "\n", "print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1.0\n" ] } ], "prompt_number": 29 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although not a very good practice, we can rename the symbols for ease of comprehension" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from numpy.linalg import inv\n", "from scipy.sparse.linalg import inv as sparseinv" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 30 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Looking at what a module contains, and its documentation\n", "\n", "Once a module is imported, we can list the symbols it provides using the `dir` function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import math\n", "\n", "print(dir(math))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['__doc__', '__file__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']\n" ] } ], "prompt_number": 31 }, { "cell_type": "markdown", "metadata": {}, "source": [ "And using the function `help` we can get a description of each function (almost .. not all functions have docstrings, as they are technically called, but the vast majority of functions are documented this way). " ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(math.log)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on built-in function log in module math:\n", "\n", "log(...)\n", " log(x[, base])\n", " \n", " Return the logarithm of x to the given base.\n", " If the base not specified, returns the natural logarithm (base e) of x.\n", "\n" ] } ], "prompt_number": 32 }, { "cell_type": "code", "collapsed": false, "input": [ "log(10)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 33, "text": [ "2.302585092994046" ] } ], "prompt_number": 33 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also specify the base" ] }, { "cell_type": "code", "collapsed": false, "input": [ "log(10, 2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 34, "text": [ "3.3219280948873626" ] } ], "prompt_number": 34 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use the `help` function directly on modules: Try\n", "\n", " help(math) " ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(math)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on module math:\n", "\n", "NAME\n", " math\n", "\n", "FILE\n", " /home/jpsilva/anaconda/lib/python2.7/lib-dynload/math.so\n", "\n", "MODULE DOCS\n", " http://docs.python.org/library/math\n", "\n", "DESCRIPTION\n", " This module is always available. It provides access to the\n", " mathematical functions defined by the C standard.\n", "\n", "FUNCTIONS\n", " acos(...)\n", " acos(x)\n", " \n", " Return the arc cosine (measured in radians) of x.\n", " \n", " acosh(...)\n", " acosh(x)\n", " \n", " Return the hyperbolic arc cosine (measured in radians) of x.\n", " \n", " asin(...)\n", " asin(x)\n", " \n", " Return the arc sine (measured in radians) of x.\n", " \n", " asinh(...)\n", " asinh(x)\n", " \n", " Return the hyperbolic arc sine (measured in radians) of x.\n", " \n", " atan(...)\n", " atan(x)\n", " \n", " Return the arc tangent (measured in radians) of x.\n", " \n", " atan2(...)\n", " atan2(y, x)\n", " \n", " Return the arc tangent (measured in radians) of y/x.\n", " Unlike atan(y/x), the signs of both x and y are considered.\n", " \n", " atanh(...)\n", " atanh(x)\n", " \n", " Return the hyperbolic arc tangent (measured in radians) of x.\n", " \n", " ceil(...)\n", " ceil(x)\n", " \n", " Return the ceiling of x as a float.\n", " This is the smallest integral value >= x.\n", " \n", " copysign(...)\n", " copysign(x, y)\n", " \n", " Return x with the sign of y.\n", " \n", " cos(...)\n", " cos(x)\n", " \n", " Return the cosine of x (measured in radians).\n", " \n", " cosh(...)\n", " cosh(x)\n", " \n", " Return the hyperbolic cosine of x.\n", " \n", " degrees(...)\n", " degrees(x)\n", " \n", " Convert angle x from radians to degrees.\n", " \n", " erf(...)\n", " erf(x)\n", " \n", " Error function at x.\n", " \n", " erfc(...)\n", " erfc(x)\n", " \n", " Complementary error function at x.\n", " \n", " exp(...)\n", " exp(x)\n", " \n", " Return e raised to the power of x.\n", " \n", " expm1(...)\n", " expm1(x)\n", " \n", " Return exp(x)-1.\n", " This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.\n", " \n", " fabs(...)\n", " fabs(x)\n", " \n", " Return the absolute value of the float x.\n", " \n", " factorial(...)\n", " factorial(x) -> Integral\n", " \n", " Find x!. Raise a ValueError if x is negative or non-integral.\n", " \n", " floor(...)\n", " floor(x)\n", " \n", " Return the floor of x as a float.\n", " This is the largest integral value <= x.\n", " \n", " fmod(...)\n", " fmod(x, y)\n", " \n", " Return fmod(x, y), according to platform C. x % y may differ.\n", " \n", " frexp(...)\n", " frexp(x)\n", " \n", " Return the mantissa and exponent of x, as pair (m, e).\n", " m is a float and e is an int, such that x = m * 2.**e.\n", " If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.\n", " \n", " fsum(...)\n", " fsum(iterable)\n", " \n", " Return an accurate floating point sum of values in the iterable.\n", " Assumes IEEE-754 floating point arithmetic.\n", " \n", " gamma(...)\n", " gamma(x)\n", " \n", " Gamma function at x.\n", " \n", " hypot(...)\n", " hypot(x, y)\n", " \n", " Return the Euclidean distance, sqrt(x*x + y*y).\n", " \n", " isinf(...)\n", " isinf(x) -> bool\n", " \n", " Check if float x is infinite (positive or negative).\n", " \n", " isnan(...)\n", " isnan(x) -> bool\n", " \n", " Check if float x is not a number (NaN).\n", " \n", " ldexp(...)\n", " ldexp(x, i)\n", " \n", " Return x * (2**i).\n", " \n", " lgamma(...)\n", " lgamma(x)\n", " \n", " Natural logarithm of absolute value of Gamma function at x.\n", " \n", " log(...)\n", " log(x[, base])\n", " \n", " Return the logarithm of x to the given base.\n", " If the base not specified, returns the natural logarithm (base e) of x.\n", " \n", " log10(...)\n", " log10(x)\n", " \n", " Return the base 10 logarithm of x.\n", " \n", " log1p(...)\n", " log1p(x)\n", " \n", " Return the natural logarithm of 1+x (base e).\n", " The result is computed in a way which is accurate for x near zero.\n", " \n", " modf(...)\n", " modf(x)\n", " \n", " Return the fractional and integer parts of x. Both results carry the sign\n", " of x and are floats.\n", " \n", " pow(...)\n", " pow(x, y)\n", " \n", " Return x**y (x to the power of y).\n", " \n", " radians(...)\n", " radians(x)\n", " \n", " Convert angle x from degrees to radians.\n", " \n", " sin(...)\n", " sin(x)\n", " \n", " Return the sine of x (measured in radians).\n", " \n", " sinh(...)\n", " sinh(x)\n", " \n", " Return the hyperbolic sine of x.\n", " \n", " sqrt(...)\n", " sqrt(x)\n", " \n", " Return the square root of x.\n", " \n", " tan(...)\n", " tan(x)\n", " \n", " Return the tangent of x (measured in radians).\n", " \n", " tanh(...)\n", " tanh(x)\n", " \n", " Return the hyperbolic tangent of x.\n", " \n", " trunc(...)\n", " trunc(x:Real) -> Integral\n", " \n", " Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.\n", "\n", "DATA\n", " e = 2.718281828459045\n", " pi = 3.141592653589793\n", "\n", "\n" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables and types\n", "\n", "### Symbol names \n", "\n", "Variable names in Python can contain alphanumerical characters `a-z`, `A-Z`, `0-9` and some special characters such as `_`. Normal variable names must start with a letter. \n", "\n", "By convension, variable names start with a lower-case letter, and Class names start with a capital letter. \n", "\n", "In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:\n", "\n", " and, as, assert, break, class, continue, def, del, elif, else, except, \n", " exec, finally, for, from, global, if, import, in, is, lambda, not, or,\n", " pass, print, raise, return, try, while, with, yield\n", "\n", "Note: Be aware of the keyword `lambda`, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.\n", "\n", "### Assignment\n", "\n", "The assignment operator in Python is `=`. Python is a dynamically typed language, so we do not need to specify the type of a variable when we create one.\n", "\n", "Assigning a value to a new variable creates the variable:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import sys\n", "import keyword\n", "\n", "print sys.version\n", "print ''\n", "print(keyword.kwlist)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Aug 21 2014, 18:22:21) \n", "[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n", "\n", "['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', 'while', 'with', 'yield']\n" ] } ], "prompt_number": 36 }, { "cell_type": "code", "collapsed": false, "input": [ "# variable assignments\n", "x = 1.0\n", "my_variable = 12.2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 37 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although not explicitly specified, a variable do have a type associated with it. The type is derived from the value it was assigned." ] }, { "cell_type": "code", "collapsed": false, "input": [ "type(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 38, "text": [ "float" ] } ], "prompt_number": 38 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we assign a new value to a variable, its type can change." ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 39 }, { "cell_type": "code", "collapsed": false, "input": [ "type(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 40, "text": [ "int" ] } ], "prompt_number": 40 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we try to use a variable that has not yet been defined we get an `NameError`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(y)" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'y' is not defined", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mNameError\u001b[0m: name 'y' is not defined" ] } ], "prompt_number": 41 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Fundamental types" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# integers\n", "x = 1\n", "type(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 42, "text": [ "int" ] } ], "prompt_number": 42 }, { "cell_type": "code", "collapsed": false, "input": [ "# float\n", "x = 1.0\n", "type(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 43, "text": [ "float" ] } ], "prompt_number": 43 }, { "cell_type": "code", "collapsed": false, "input": [ "# boolean\n", "b1 = True\n", "b2 = False\n", "\n", "type(b1)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 44, "text": [ "bool" ] } ], "prompt_number": 44 }, { "cell_type": "code", "collapsed": false, "input": [ "# complex numbers: note the use of `j` to specify the imaginary part\n", "x = 1.0 - 1.0j\n", "type(x)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 45, "text": [ "complex" ] } ], "prompt_number": 45 }, { "cell_type": "code", "collapsed": false, "input": [ "print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1-1j)\n" ] } ], "prompt_number": 46 }, { "cell_type": "code", "collapsed": false, "input": [ "print(x.real, x.imag)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1.0, -1.0)\n" ] } ], "prompt_number": 47 }, { "cell_type": "code", "collapsed": false, "input": [ "import types\n", "\n", "# print all types defined in the `types` module\n", "print(dir(types))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']\n" ] } ], "prompt_number": 48 }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1.0\n", "\n", "# check if the variable x is a float\n", "type(x) is float" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 49, "text": [ "True" ] } ], "prompt_number": 49 }, { "cell_type": "code", "collapsed": false, "input": [ "# check if the variable x is an int\n", "type(x) is int" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 50, "text": [ "False" ] } ], "prompt_number": 50 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also use the `isinstance` method for testing types of variables:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "isinstance(x, float)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 51, "text": [ "True" ] } ], "prompt_number": 51 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Type casting" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x = 1.5\n", "\n", "print(x, type(x))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1.5, )\n" ] } ], "prompt_number": 52 }, { "cell_type": "code", "collapsed": false, "input": [ "x = int(x)\n", "\n", "print(x, type(x))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1, )\n" ] } ], "prompt_number": 53 }, { "cell_type": "code", "collapsed": false, "input": [ "z = complex(x)\n", "\n", "print(z, type(z))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "((1+0j), )\n" ] } ], "prompt_number": 54 }, { "cell_type": "code", "collapsed": false, "input": [ "x = float(z)" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "can't convert complex to float", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mx\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mfloat\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mz\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: can't convert complex to float" ] } ], "prompt_number": 55 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Complex variables cannot be cast to floats or integers. We need to use `z.real` or `z.imag` to extract the part of the complex number we want:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "y = bool(z.real)\n", "\n", "print(z.real, \" -> \", y, type(y))\n", "\n", "y = bool(z.imag)\n", "\n", "print(z.imag, \" -> \", y, type(y))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1.0, ' -> ', True, )\n", "(0.0, ' -> ', False, )\n" ] } ], "prompt_number": 56 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Operators and comparisons\n", "\n", "Most operators and comparisons in Python work as one would expect:\n", "\n", "* Arithmetic operators `+`, `-`, `*`, `/`, `//` (integer division), '**' power\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "1 + 2, 1 - 2, 1 * 2, 1 / 2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 57, "text": [ "(3, -1, 2, 0)" ] } ], "prompt_number": 57 }, { "cell_type": "code", "collapsed": false, "input": [ "1.0 + 2.0, 1.0 - 2.0, 1.0 * 2.0, 1.0 / 2.0" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 58, "text": [ "(3.0, -1.0, 2.0, 0.5)" ] } ], "prompt_number": 58 }, { "cell_type": "code", "collapsed": false, "input": [ "3.0 // 2.0" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 59, "text": [ "1.0" ] } ], "prompt_number": 59 }, { "cell_type": "code", "collapsed": false, "input": [ "2 ** 2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 60, "text": [ "4" ] } ], "prompt_number": 60 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The boolean operators are spelled out as words `and`, `not`, `or`. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "True and False" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 61, "text": [ "False" ] } ], "prompt_number": 61 }, { "cell_type": "code", "collapsed": false, "input": [ "not False" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 62, "text": [ "True" ] } ], "prompt_number": 62 }, { "cell_type": "code", "collapsed": false, "input": [ "True or False" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 63, "text": [ "True" ] } ], "prompt_number": 63 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Comparison operators `>`, `<`, `>=` (greater or equal), `<=` (less or equal), `==` equality, `is` identical." ] }, { "cell_type": "code", "collapsed": false, "input": [ "2 > 1, 2 < 1" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 64, "text": [ "(True, False)" ] } ], "prompt_number": 64 }, { "cell_type": "code", "collapsed": false, "input": [ "2 > 2, 2 < 2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 65, "text": [ "(False, False)" ] } ], "prompt_number": 65 }, { "cell_type": "code", "collapsed": false, "input": [ "2 >= 2, 2 <= 2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 66, "text": [ "(True, True)" ] } ], "prompt_number": 66 }, { "cell_type": "code", "collapsed": false, "input": [ "# equality\n", "[1,2] == [1,2]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 67, "text": [ "True" ] } ], "prompt_number": 67 }, { "cell_type": "code", "collapsed": false, "input": [ "# objects identical?\n", "l1 = l2 = [1,2]\n", "\n", "l1 is l2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 68, "text": [ "True" ] } ], "prompt_number": 68 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Compound types: Strings, List and dictionaries\n", "\n", "### Strings\n", "\n", "Strings are the variable type that is used for storing text messages. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "s = \"Hello world\"\n", "type(s)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 69, "text": [ "str" ] } ], "prompt_number": 69 }, { "cell_type": "code", "collapsed": false, "input": [ "# length of the string: the number of characters\n", "len(s)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 70, "text": [ "11" ] } ], "prompt_number": 70 }, { "cell_type": "code", "collapsed": false, "input": [ "# replace a substring in a string with somethign else\n", "s2 = s.replace(\"world\", \"test\")\n", "print(s2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello test\n" ] } ], "prompt_number": 71 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can index a character in a string using `[]`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s[0]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 72, "text": [ "'H'" ] } ], "prompt_number": 72 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can extract a part of a string using the syntax `[start:stop]`, which extracts characters between index `start` and `stop`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s[0:5]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 73, "text": [ "'Hello'" ] } ], "prompt_number": 73 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we omit either (or both) of `start` or `stop` from `[start:stop]`, the default is the beginning and the end of the string, respectively:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s[:5]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 74, "text": [ "'Hello'" ] } ], "prompt_number": 74 }, { "cell_type": "code", "collapsed": false, "input": [ "s[6:]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 75, "text": [ "'world'" ] } ], "prompt_number": 75 }, { "cell_type": "code", "collapsed": false, "input": [ "s[:]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 76, "text": [ "'Hello world'" ] } ], "prompt_number": 76 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also define the step size using the syntax `[start:end:step]` (the default value for `step` is 1, as we saw above):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "s[::1]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 77, "text": [ "'Hello world'" ] } ], "prompt_number": 77 }, { "cell_type": "code", "collapsed": false, "input": [ "s[::2]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 78, "text": [ "'Hlowrd'" ] } ], "prompt_number": 78 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### String formatting examples" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"str1\" + \"str2\" + \"str3\") # strings added with + are concatenated without space" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "str1str2str3\n" ] } ], "prompt_number": 79 }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"value = %f\" % 1.0)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "value = 1.000000\n" ] } ], "prompt_number": 80 }, { "cell_type": "code", "collapsed": false, "input": [ "s2 = \"value1 = %.2f value2 = %d\" % (3.1415, 1.5)\n", "\n", "print(s2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "value1 = 3.14 value2 = 1\n" ] } ], "prompt_number": 81 }, { "cell_type": "code", "collapsed": false, "input": [ "s3 = 'value1 = {0}, value2 = {1}'.format(3.1415, 1.5)\n", "\n", "print(s3)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "value1 = 3.1415, value2 = 1.5\n" ] } ], "prompt_number": 82 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### List\n", "\n", "Lists are very similar to strings, except that each element can be of any type.\n", "\n", "The syntax for creating lists in Python is `[...]`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l = [1,2,3,4]\n", "\n", "print(type(l))\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "[1, 2, 3, 4]\n" ] } ], "prompt_number": 83 }, { "cell_type": "code", "collapsed": false, "input": [ "print(l)\n", "\n", "print(l[1:3])\n", "\n", "print(l[::2])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 2, 3, 4]\n", "[2, 3]\n", "[1, 3]\n" ] } ], "prompt_number": 84 }, { "cell_type": "code", "collapsed": false, "input": [ "l[0]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 85, "text": [ "1" ] } ], "prompt_number": 85 }, { "cell_type": "code", "collapsed": false, "input": [ "l = [1, 'a', 1.0, 1-1j]\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[1, 'a', 1.0, (1-1j)]\n" ] } ], "prompt_number": 86 }, { "cell_type": "code", "collapsed": false, "input": [ "start = 10\n", "stop = 30\n", "step = 2\n", "\n", "range(start, stop, step)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 87, "text": [ "[10, 12, 14, 16, 18, 20, 22, 24, 26, 28]" ] } ], "prompt_number": 87 }, { "cell_type": "code", "collapsed": false, "input": [ "list(range(-10, 10))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 88, "text": [ "[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] } ], "prompt_number": 88 }, { "cell_type": "code", "collapsed": false, "input": [ "s" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 89, "text": [ "'Hello world'" ] } ], "prompt_number": 89 }, { "cell_type": "code", "collapsed": false, "input": [ "# convert a string to a list:\n", "\n", "s2 = list(s)\n", "\n", "s2" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 90, "text": [ "['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']" ] } ], "prompt_number": 90 }, { "cell_type": "code", "collapsed": false, "input": [ "# sorting lists\n", "s2.sort()\n", "\n", "print(s2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[' ', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']\n" ] } ], "prompt_number": 91 }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Adding, inserting, modifying, and removing elements from lists" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# create a new empty list\n", "l = []\n", "\n", "# add an elements using `append`\n", "l.append(\"A\")\n", "l.append(\"d\")\n", "l.append(\"d\")\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['A', 'd', 'd']\n" ] } ], "prompt_number": 94 }, { "cell_type": "code", "collapsed": false, "input": [ "l[1] = \"p\"\n", "l[2] = \"p\"\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['A', 'p', 'p']\n" ] } ], "prompt_number": 95 }, { "cell_type": "code", "collapsed": false, "input": [ "l[1:3] = [\"d\", \"d\"]\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['A', 'd', 'd']\n" ] } ], "prompt_number": 96 }, { "cell_type": "code", "collapsed": false, "input": [ "l.insert(0, \"i\")\n", "l.insert(1, \"n\")\n", "l.insert(2, \"s\")\n", "l.insert(3, \"e\")\n", "l.insert(4, \"r\")\n", "l.insert(5, \"t\")\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['i', 'n', 's', 'e', 'r', 't', 'A', 'd', 'd']\n" ] } ], "prompt_number": 97 }, { "cell_type": "code", "collapsed": false, "input": [ "l.remove(\"A\")\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['i', 'n', 's', 'e', 'r', 't', 'd', 'd']\n" ] } ], "prompt_number": 98 }, { "cell_type": "code", "collapsed": false, "input": [ "del l[7]\n", "del l[6]\n", "\n", "print(l)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['i', 'n', 's', 'e', 'r', 't']\n" ] } ], "prompt_number": 99 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuples\n", "\n", "Tuples are like lists, except that they cannot be modified once created, that is they are *immutable*. \n", "\n", "In Python, tuples are created using the syntax `(..., ..., ...)`, or even `..., ...`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "point = (10, 20)\n", "\n", "print(point, type(point))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "((10, 20), )\n" ] } ], "prompt_number": 100 }, { "cell_type": "code", "collapsed": false, "input": [ "point = 10, 20\n", "\n", "print(point, type(point))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "((10, 20), )\n" ] } ], "prompt_number": 101 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can unpack a tuple by assigning it to a comma-separated list of variables:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "x, y = point\n", "\n", "print(\"x =\", x)\n", "print(\"y =\", y)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('x =', 10)\n", "('y =', 20)\n" ] } ], "prompt_number": 102 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we try to assign a new value to an element in a tuple we get an error:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "point[0] = 20" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'tuple' object does not support item assignment", "output_type": "pyerr", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mpoint\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m20\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ], "prompt_number": 103 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Dictionaries\n", "\n", "Dictionaries are also like lists, except that each element is a key-value pair. The syntax for dictionaries is `{key1 : value1, ...}`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "params = {\"parameter1\" : 1.0,\n", " \"parameter2\" : 2.0,\n", " \"parameter3\" : 3.0,}\n", "\n", "print(type(params))\n", "print(params)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "{'parameter1': 1.0, 'parameter3': 3.0, 'parameter2': 2.0}\n" ] } ], "prompt_number": 104 }, { "cell_type": "code", "collapsed": false, "input": [ "print(\"parameter1 = \" + str(params[\"parameter1\"]))\n", "print(\"parameter2 = \" + str(params[\"parameter2\"]))\n", "print(\"parameter3 = \" + str(params[\"parameter3\"]))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "parameter1 = 1.0\n", "parameter2 = 2.0\n", "parameter3 = 3.0\n" ] } ], "prompt_number": 105 }, { "cell_type": "code", "collapsed": false, "input": [ "params[\"parameter1\"] = \"A\"\n", "params[\"parameter2\"] = \"B\"\n", "\n", "# add a new entry\n", "params[\"parameter4\"] = \"D\"\n", "\n", "print(\"parameter1 = \" + str(params[\"parameter1\"]))\n", "print(\"parameter2 = \" + str(params[\"parameter2\"]))\n", "print(\"parameter3 = \" + str(params[\"parameter3\"]))\n", "print(\"parameter4 = \" + str(params[\"parameter4\"]))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "parameter1 = A\n", "parameter2 = B\n", "parameter3 = 3.0\n", "parameter4 = D\n" ] } ], "prompt_number": 106 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control Flow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Conditional statements: if, elif, else\n", "\n", "The Python syntax for conditional execution of code use the keywords `if`, `elif` (else if), `else`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "statement1 = False\n", "statement2 = False\n", "\n", "if statement1:\n", " print(\"statement1 is True\")\n", " \n", "elif statement2:\n", " print(\"statement2 is True\")\n", " \n", "else:\n", " print(\"statement1 and statement2 are False\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "statement1 and statement2 are False\n" ] } ], "prompt_number": 107 }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python, the extent of a code block is defined by the indentation level (usually a tab or say four white spaces). This means that we have to be careful to indent our code correctly, or else we will get syntax errors. \n", "\n", "**Examples:**" ] }, { "cell_type": "code", "collapsed": false, "input": [ "statement1 = statement2 = True\n", "\n", "if statement1:\n", " if statement2:\n", " print(\"both statement1 and statement2 are True\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "both statement1 and statement2 are True\n" ] } ], "prompt_number": 108 }, { "cell_type": "code", "collapsed": false, "input": [ "# Bad indentation!\n", "if statement1:\n", " if statement2:\n", " print(\"both statement1 and statement2 are True\") # this line is not properly indented" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "both statement1 and statement2 are True\n" ] } ], "prompt_number": 109 }, { "cell_type": "code", "collapsed": false, "input": [ "statement1 = False \n", "\n", "if statement1:\n", " print(\"printed if statement1 is True\")\n", " \n", " print(\"still inside the if block\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 110 }, { "cell_type": "code", "collapsed": false, "input": [ "if statement1:\n", " print(\"printed if statement1 is True\")\n", " \n", "print(\"now outside the if block\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "now outside the if block\n" ] } ], "prompt_number": 111 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops\n", "\n", "In Python, loops can be programmed in a number of different ways. The most common is the `for` loop, which is used together with iterable objects, such as lists. The basic syntax is:\n", "\n", "\n", "**`for` loops**:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for x in [1,2,3]:\n", " print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1\n", "2\n", "3\n" ] } ], "prompt_number": 112 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `for` loop iterates over the elements of the supplied list, and executes the containing block once for each element. Any kind of list can be used in the `for` loop. For example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for x in range(4): # by default range start at 0\n", " print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0\n", "1\n", "2\n", "3\n" ] } ], "prompt_number": 113 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note: `range(4)` does not include 4 !" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for x in range(-3,3):\n", " print(x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "-3\n", "-2\n", "-1\n", "0\n", "1\n", "2\n" ] } ], "prompt_number": 114 }, { "cell_type": "code", "collapsed": false, "input": [ "for word in [\"scientific\", \"computing\", \"with\", \"python\"]:\n", " print(word)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "scientific\n", "computing\n", "with\n", "python\n" ] } ], "prompt_number": 115 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To iterate over key-value pairs of a dictionary:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for key, value in params.items():\n", " print(key + \" = \" + str(value))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "parameter4 = D\n", "parameter1 = A\n", "parameter3 = 3.0\n", "parameter2 = B\n" ] } ], "prompt_number": 116 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes it is useful to have access to the indices of the values when iterating over a list. We can use the `enumerate` function for this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "for idx, x in enumerate(range(-3,3)):\n", " print(idx, x)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(0, -3)\n", "(1, -2)\n", "(2, -1)\n", "(3, 0)\n", "(4, 1)\n", "(5, 2)\n" ] } ], "prompt_number": 117 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**List comprehensions: Creating lists using `for` loops**:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "l1 = [x**2 for x in range(0,5)]\n", "\n", "print(l1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[0, 1, 4, 9, 16]\n" ] } ], "prompt_number": 118 }, { "cell_type": "markdown", "metadata": {}, "source": [ "**`while` loops**:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "i = 0\n", "\n", "while i < 5:\n", " print(i)\n", " \n", " i = i + 1\n", " \n", "print(\"done\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "done\n" ] } ], "prompt_number": 119 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions\n", "\n", "A function in Python is defined using the keyword `def`, followed by a function name, a signature within parenthises `()`, and a colon `:`. The following code, with one additional level of indentation, is the function body." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def func0(): \n", " print(\"test\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 120 }, { "cell_type": "code", "collapsed": false, "input": [ "func0()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "test\n" ] } ], "prompt_number": 121 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Optionally, but highly recommended, we can define a so called \"docstring\", which is a description of the functions purpose and behavior. The docstring should be located after the function definition and before the code in the function body." ] }, { "cell_type": "code", "collapsed": false, "input": [ "def func1(s):\n", " \"\"\"\n", " Print a string 's' and tell how many characters it has \n", " \"\"\"\n", " \n", " print(s + \" has \" + str(len(s)) + \" characters\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 122 }, { "cell_type": "code", "collapsed": false, "input": [ "help(func1)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on function func1 in module __main__:\n", "\n", "func1(s)\n", " Print a string 's' and tell how many characters it has\n", "\n" ] } ], "prompt_number": 123 }, { "cell_type": "code", "collapsed": false, "input": [ "func1(\"test\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "test has 4 characters\n" ] } ], "prompt_number": 124 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions that returns a value use the `return` keyword:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def square(x):\n", " \"\"\"\n", " Return the square of x.\n", " \"\"\"\n", " return x ** 2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 125 }, { "cell_type": "code", "collapsed": false, "input": [ "square(4)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 126, "text": [ "16" ] } ], "prompt_number": 126 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can return multiple values from a function using tuples (see above):" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def powers(x):\n", " \"\"\"\n", " Return a few powers of x.\n", " \"\"\"\n", " return x ** 2, x ** 3, x ** 4" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 127 }, { "cell_type": "code", "collapsed": false, "input": [ "powers(3)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 128, "text": [ "(9, 27, 81)" ] } ], "prompt_number": 128 }, { "cell_type": "code", "collapsed": false, "input": [ "x2, x3, x4 = powers(3)\n", "\n", "print(x3)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "27\n" ] } ], "prompt_number": 129 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Default argument and keyword arguments" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def myfunc(x, p=2, debug=False):\n", " if debug:\n", " print(\"evaluating myfunc for x = \" + str(x) + \" using exponent p = \" + str(p))\n", " return x**p" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 130 }, { "cell_type": "code", "collapsed": false, "input": [ "myfunc(5)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 131, "text": [ "25" ] } ], "prompt_number": 131 }, { "cell_type": "code", "collapsed": false, "input": [ "myfunc(5, debug=True)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "evaluating myfunc for x = 5 using exponent p = 2\n" ] }, { "metadata": {}, "output_type": "pyout", "prompt_number": 132, "text": [ "25" ] } ], "prompt_number": 132 }, { "cell_type": "code", "collapsed": false, "input": [ "myfunc(p=3, debug=True, x=7)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "evaluating myfunc for x = 7 using exponent p = 3\n" ] }, { "metadata": {}, "output_type": "pyout", "prompt_number": 133, "text": [ "343" ] } ], "prompt_number": 133 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Unnamed functions (lambda function)\n", "\n", "In Python we can also create unnamed functions, using the `lambda` keyword:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "f1 = lambda x: x**2\n", " \n", "# is equivalent to \n", "\n", "def f2(x):\n", " return x**2" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 134 }, { "cell_type": "code", "collapsed": false, "input": [ "f1(2), f2(2)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 135, "text": [ "(4, 4)" ] } ], "prompt_number": 135 }, { "cell_type": "markdown", "metadata": {}, "source": [ "This technique is useful for exmample when we want to pass a simple function as an argument to another function, like this:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# map is a built-in python function\n", "map(lambda x: x**2, range(-3,4))" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 136, "text": [ "[9, 4, 1, 0, 1, 4, 9]" ] } ], "prompt_number": 136 }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classes\n", "\n", "Classes are the key features of object-oriented programming. A class is a structure for representing an object and the operations that can be performed on the object. \n", "\n", "In Python a class can contain *attributes* (variables) and *methods* (functions).\n", "\n", "In python a class is defined almost like a function, but using the `class` keyword, and the class definition usually contains a number of class method definitions (a function in a class).\n", "\n", "* Each class method should have an argument `self` as it first argument. This object is a self-reference.\n", "\n", "* Some class method names have special meaning, for example:\n", "\n", " * `__init__`: The name of the method that is invoked when the object is first created.\n", " * `__str__` : A method that is invoked when a simple string representation of the class is needed, as for example when printed." ] }, { "cell_type": "code", "collapsed": false, "input": [ "class Point:\n", " \"\"\"\n", " Simple class for representing a point in a Cartesian coordinate system.\n", " \"\"\"\n", " \n", " def __init__(self, x, y):\n", " \"\"\"\n", " Create a new Point at x, y.\n", " \"\"\"\n", " self.x = x\n", " self.y = y\n", " \n", " def translate(self, dx, dy):\n", " \"\"\"\n", " Translate the point by dx and dy in the x and y direction.\n", " \"\"\"\n", " self.x += dx\n", " self.y += dy\n", " \n", " def __str__(self):\n", " return(\"Point at [%f, %f]\" % (self.x, self.y))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 137 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To create a new instance of a class:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "p1 = Point(0, 0) # this will invoke the __init__ method in the Point class\n", "\n", "print(p1) # this will invoke the __str__ method" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Point at [0.000000, 0.000000]\n" ] } ], "prompt_number": 138 }, { "cell_type": "code", "collapsed": false, "input": [ "p2 = Point(1, 1)\n", "\n", "p1.translate(0.25, 1.5)\n", "\n", "print(p1)\n", "print(p2)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Point at [0.250000, 1.500000]\n", "Point at [1.000000, 1.000000]\n" ] } ], "prompt_number": 139 }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Modules\n", "\n", "One of the most important concepts in good programming is to reuse code and avoid repetitions.\n", "\n", "Consider the following example: the file `mymodule.py` contains simple example implementations of a variable, function and a class:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%file mymodule.py\n", "\"\"\"\n", "Example of a python module. Contains a variable called my_variable,\n", "a function called my_function, and a class called MyClass.\n", "\"\"\"\n", "\n", "my_variable = 0\n", "\n", "def my_function():\n", " \"\"\"\n", " Example function\n", " \"\"\"\n", " return my_variable\n", " \n", "class MyClass:\n", " \"\"\"\n", " Example class.\n", " \"\"\"\n", "\n", " def __init__(self):\n", " self.variable = my_variable\n", " \n", " def set_variable(self, new_value):\n", " \"\"\"\n", " Set self.variable to a new value\n", " \"\"\"\n", " self.variable = new_value\n", " \n", " def get_variable(self):\n", " return self.variable" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Writing mymodule.py\n" ] } ], "prompt_number": 140 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can import the module `mymodule` into our Python program using `import`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import mymodule" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 141 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use `help(module)` to get a summary of what the module provides:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "help(mymodule)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on module mymodule:\n", "\n", "NAME\n", " mymodule\n", "\n", "FILE\n", " /home/jpsilva/Lisbon1214/notebooks/mymodule.py\n", "\n", "DESCRIPTION\n", " Example of a python module. Contains a variable called my_variable,\n", " a function called my_function, and a class called MyClass.\n", "\n", "CLASSES\n", " MyClass\n", " \n", " class MyClass\n", " | Example class.\n", " | \n", " | Methods defined here:\n", " | \n", " | __init__(self)\n", " | \n", " | get_variable(self)\n", " | \n", " | set_variable(self, new_value)\n", " | Set self.variable to a new value\n", "\n", "FUNCTIONS\n", " my_function()\n", " Example function\n", "\n", "DATA\n", " my_variable = 0\n", "\n", "\n" ] } ], "prompt_number": 142 }, { "cell_type": "code", "collapsed": false, "input": [ "mymodule.my_variable" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 143, "text": [ "0" ] } ], "prompt_number": 143 }, { "cell_type": "code", "collapsed": false, "input": [ "mymodule.my_function() " ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 144, "text": [ "0" ] } ], "prompt_number": 144 }, { "cell_type": "code", "collapsed": false, "input": [ "my_class = mymodule.MyClass() \n", "my_class.set_variable(10)\n", "my_class.get_variable()" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 145, "text": [ "10" ] } ], "prompt_number": 145 }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we make changes to the code in `mymodule.py`, we need to reload it using `reload`:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "reload(mymodule)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 146, "text": [ "" ] } ], "prompt_number": 146 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Versions" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%reload_ext version_information\n", "\n", "%version_information math" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "
SoftwareVersion
Python2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Aug 21 2014, 18:22:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]
IPython2.3.0
OSposix [linux2]
math'module' object has no attribute '__version__'
Fri Dec 05 09:59:20 2014 CET
" ], "json": [ "{ \"Software versions\" : [{ \"module\" : \"Python\", \"version\" : \"2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Aug 21 2014, 18:22:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\" }, { \"module\" : \"IPython\", \"version\" : \"2.3.0\" }, { \"module\" : \"OS\", \"version\" : \"posix [linux2]\" }, { \"module\" : \"math\", \"version\" : \"'module' object has no attribute '__version__'\" } ] }" ], "latex": [ "\\begin{tabular}{|l|l|}\\hline\n", "{\\bf Software} & {\\bf Version} \\\\ \\hline\\hline\n", "Python & 2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Aug 21 2014, 18:22:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] \\\\ \\hline\n", "IPython & 2.3.0 \\\\ \\hline\n", "OS & posix [linux2] \\\\ \\hline\n", "math & 'module' object has no attribute '__version__' \\\\ \\hline\n", "\\hline \\multicolumn{2}{|l|}{Fri Dec 05 09:59:20 2014 CET} \\\\ \\hline\n", "\\end{tabular}\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 147, "text": [ "Software versions\n", "Python 2.7.8 |Anaconda 2.1.0 (64-bit)| (default, Aug 21 2014, 18:22:21) [GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n", "IPython 2.3.0\n", "OS posix [linux2]\n", "math 'module' object has no attribute '__version__'\n", "\n", "Fri Dec 05 09:59:20 2014 CET" ] } ], "prompt_number": 147 }, { "cell_type": "code", "collapsed": false, "input": [ "%who" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "HTML\t Point\t acos\t acosh\t asin\t asinh\t atan\t atan2\t atanh\t \n", "b1\t b2\t ceil\t copysign\t cos\t cosh\t css_styling\t degrees\t e\t \n", "erf\t erfc\t exp\t expm1\t f1\t f2\t fabs\t factorial\t floor\t \n", "fmod\t frexp\t fsum\t func0\t func1\t gamma\t hypot\t i\t idx\t \n", "inv\t isinf\t isnan\t key\t keyword\t l\t l1\t l2\t ldexp\t \n", "lgamma\t log\t log10\t log1p\t math\t modf\t my_class\t my_variable\t myfunc\t \n", "mymodule\t p1\t p2\t params\t pi\t point\t pow\t powers\t radians\t \n", "s\t s2\t s3\t script_dir\t sin\t sinh\t sparseinv\t sqrt\t square\t \n", "start\t statement1\t statement2\t step\t stop\t sys\t tan\t tanh\t trunc\t \n", "types\t value\t word\t x\t x2\t x3\t x4\t y\t z\t \n", "\n" ] } ], "prompt_number": 148 }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can find more information about IPython capabilities in [IPython example notebooks](https://github.com/ipython/ipython/tree/1.x/examples/notebooks)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " *The full notebook can be downloaded* \n", "[*here*](https://raw.github.com/PoeticCapybara/Python-Introduction-Zittau/master/Lecture-1-Introduction-to-Python.ipynb), \n", "*or viewed statically on* \n", "[*nbviewer*](http://nbviewer.ipython.org/urls/raw.github.com/PoeticCapybara/Python-Introduction-Zittau/master/Lecture-1-Introduction-to-Python.ipynb)" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.core.display import HTML\n", "def css_styling():\n", " styles = open(\"./styles/custom.css\", \"r\").read()\n", " return HTML(styles)\n", "css_styling()" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "\n", "\n", "\n", "\n" ], "metadata": {}, "output_type": "pyout", "prompt_number": 149, "text": [ "" ] } ], "prompt_number": 149 }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Back to top](#Index)" ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }