{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to the Python language" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "We introduce here the Python language. Only the bare minimum\n", "necessary for getting started with Numpy and Scipy is addressed here.\n", "To learn more about the language, consider going through the\n", "excellent tutorial http://www.scipy-lectures.org/intro/index.html. Dedicated books\n", "are also available, such as http://www.diveintopython.net/.\n", "\n", "Python is a **programming language**, as are C, Fortran, BASIC, PHP,\n", "etc. Some specific features of Python are as follows:\n", "\n", "* an *interpreted* (as opposed to *compiled*) language. Contrary to e.g.\n", "C or Fortran, one does not compile Python code before executing it. In\n", "addition, Python can be used **interactively**: many Python\n", "interpreters are available, from which commands and scripts can be\n", "executed.\n", "\n", "* a free software released under an **open-source** license: Python can\n", "be used and distributed free of charge, even for building commercial\n", "software.\n", "\n", "* **multi-platform**: Python is available for all major operating\n", "systems, Windows, Linux/Unix, MacOS X, most likely your mobile phone\n", "OS, etc.\n", "\n", "* a very readable language with clear non-verbose syntax\n", "\n", "* a language for which a large variety of high-quality packages are\n", "available for various applications, from web frameworks to scientific\n", "computing.\n", "\n", "* a language very easy to interface with other languages, in particular C\n", "and C++.\n", "\n", "* Some other features of the language are illustrated just below. For\n", "example, Python is an object-oriented language, with dynamic typing\n", "(the same variable can contain objects of different types during the\n", "course of a program).\n", "\n", "\n", "See https://www.python.org/about/ for more information about\n", "distinguishing features of Python." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Hello world\n", "\n", "you type in the cells, execute commands with shift + Enter\n", "\n", "```print(\"Hello world\")```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print(\"Hello world\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic types\n", "\n", "## Integers" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "1+1" ] }, { "cell_type": "markdown", "metadata": { "collapsed": false }, "source": [ "We can assign values to variables with `=`\n", "\n", " a = 4\n", " type(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = 4" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that one does not declare the type of a variable before assigning its value. In C, conversely, one should write:\n", "\n", "```int a = 4;```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Floats\n", "There exists a floating point type that is created when the variable has decimal values:\n", "\n", " c = 2.1\n", " type(c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "c = 2.1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Boolean\n", "Similarly, boolean types are created from a comparison:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "3 > 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " test = (3 > 4)\n", " type(test)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "test = (3 > 4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(test)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Tip_:A Python shell can therefore replace your pocket calculator, with the basic arithmetic operations ``+``, ``-``, ``*``, ``/``, ``%`` (modulo) natively implemented" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Type conversion (casting)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = 1\n", "type(a)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "b = float(a)\n", "type(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise <^^>: Compute the floating point expression of 3 / 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Containers\n", "\n", "_Tip_: Python provides many efficient types of containers, in which collections of objects can be stored.\n", "\n", "## Lists\n", "\n", "A list is an ordered collection of objects, that may have different types. For example:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " colors = ['red', 'blue', 'green', 'black', 'white']\n", " type(colors)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors = ['red', 'blue', 'green', 'black', 'white']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "type(colors)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indexing: accessing individual objects contained in the list::" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

WARNING: **Indexing starts at 0** (as in C), not at 1 (as in Fortran or Matlab)!

\n", "\n", "Counting from the end with negative indices:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[-2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise: get the before last element in colors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Slicing: obtaining sublists of regularly-spaced elements\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[1:5:2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Slicing syntax**: ``colors[start:stop:stride]``\n", "\n", " _Tip_: All slicing parameters are optional::" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[3:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise: what is the output of ```colors[::2]```. Why?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[::2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise: reverse a list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "colors[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Strings\n", "\n", "Different string syntaxes (simple, double or triple quotes)::\n", "\n", " s = 'Hello, how are you?'\n", " s = \"Hi, what's up\"\n", " s = '''Hello, # tripling the quotes allows the\n", " how are you''' # the string to span more than one line\n", " s = \"\"\"Hi,\n", " what's up?\"\"\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "s = 'asdfdfdf'\n", "type(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s = \"asdfdfd\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s = \"\"\"asdfadsf\n", "asdfdf\n", "asdfdf\n", "\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Dictionaries" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "A dictionary is basically an efficient table that **maps keys to values**. It is an **unordered** container" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "tel = {'emmanuelle': 5752, 'sebastian': 5578}" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'emanuelle': 5752, 'sebastian': 5578}" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "ename": "KeyError", "evalue": "'francis'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtel\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'francis'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mKeyError\u001b[0m: 'francis'" ] } ], "source": [ "tel['francis']" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "tel['francis'] = 5919" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'emanuelle': 5752, 'francis': 5919, 'sebastian': 5578}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5578" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel['sebastian']" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_keys(['sebastian', 'emanuelle', 'francis'])" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel.keys()" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "dict_values([5578, 5752, 5919])" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel.values()" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'francis' in tel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It can be used to conveniently store and retrieve values\n", "associated with a name (a string for a date, a name, etc.). See\n", "https://docs.python.org/tutorial/datastructures.html#dictionaries\n", "for more information.\n", "\n", "_Tip_: A dictionary can have keys (resp. values) with different types:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'a': 1, 3: 'asdf', 'b': 2}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d = {'a':1, 'b':2, 3: 'asdf'}\n", "d" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": true }, "outputs": [], "source": [ "del d['a']" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{3: 'asdf', 'b': 2}" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise: assign the telephone of sebastian to francis, and that of francis to sebastian.\n" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [], "source": [ "tel = {'emanuelle': 5752, 'sebastian' : 5578, 'francis' : 1234}" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": true }, "outputs": [], "source": [ "tmp = tel['francis']\n", "tel['francis'] = tel['sebastian']\n", "tel['sebastian'] = tmp" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "{'emanuelle': 5752, 'francis': 5578, 'sebastian': 1234}" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tel" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Control Flow\n", "\n", "Controls the order in which the code is executed.\n", "\n", "## if/elif/else\n", "\n", " if 2**2 == 4:\n", " print('Obvious!')" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "YES\n" ] } ], "source": [ "if 2 ** 2 == 5:\n", " print('Obvious')\n", "print('YES')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "## Blocks are delimited by indentation!\n", "\n", "_Tip_: Type the following lines in your Python interpreter, and be careful\n", "to **respect the indentation depth**. The Ipython shell automatically\n", "increases the indentation depth after a colon ``:`` sign; to\n", "decrease the indentation depth, go four spaces to the left with the\n", "Backspace key. Press the Enter key twice to leave the logical block.\n", "\n", " >>> a = 10\n", "\n", " >>> if a == 1:\n", " ... print(1)\n", " ... elif a == 2:\n", " ... print(2)\n", " ... else:\n", " ... print('A lot')\n", " A lot\n", "\n" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = 10\n", "if a == 1:\n", " print(1)\n", "elif a == 2:\n", " print(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# for/range\n", "\n", "Iterating with an index::\n", "\n", " >>> for i in range(4):\n", " ... print(i)\n", " 0\n", " 1\n", " 2\n", " 3\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(4):\n", " print(i + 1)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = []\n" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "2\n", "4\n", "6\n", "8\n", "10\n", "12\n", "14\n", "16\n", "18\n", "20\n", "22\n", "24\n", "26\n", "28\n", "30\n", "32\n", "34\n", "36\n", "38\n", "40\n", "42\n", "44\n", "46\n", "48\n", "50\n", "52\n", "54\n", "56\n", "58\n", "60\n", "62\n", "64\n", "66\n", "68\n", "70\n", "72\n", "74\n", "76\n", "78\n", "80\n", "82\n", "84\n", "86\n", "88\n", "90\n", "92\n", "94\n", "96\n", "98\n", "100\n" ] } ], "source": [ "for i in range(0, 101, 2):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise: print all even numbers between 0 and 100" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But most often, it is more readable to iterate over values::\n", "\n", " >>> for word in ('cool', 'powerful', 'readable'):\n", " ... print('Python is %s' % word)\n", " Python is cool\n", " Python is powerful\n", " Python is readable" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "green\n", "blue\n", "yellow\n" ] } ], "source": [ "for word in ['green', 'blue', 'yellow']:\n", " print(word)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### List Comprehensions\n", "\n", "\n", " >>> [i**2 for i in range(4)]\n", " [0, 1, 4, 9]\n" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[0,\n", " 2,\n", " 4,\n", " 6,\n", " 8,\n", " 10,\n", " 12,\n", " 14,\n", " 16,\n", " 18,\n", " 20,\n", " 22,\n", " 24,\n", " 26,\n", " 28,\n", " 30,\n", " 32,\n", " 34,\n", " 36,\n", " 38,\n", " 40,\n", " 42,\n", " 44,\n", " 46,\n", " 48,\n", " 50,\n", " 52,\n", " 54,\n", " 56,\n", " 58,\n", " 60,\n", " 62,\n", " 64,\n", " 66,\n", " 68,\n", " 70,\n", " 72,\n", " 74,\n", " 76,\n", " 78,\n", " 80,\n", " 82,\n", " 84,\n", " 86,\n", " 88,\n", " 90,\n", " 92,\n", " 94,\n", " 96,\n", " 98,\n", " 100]" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[2 * i for i in range(51)]" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "a = 10\n", "b = 1\n", "while b < a:\n", " b = b + 1\n", " print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### <^^> Exercise\n", "\n", "Compute the decimals of Pi using the Wallis formula:\n", "\n", "$$\n", "\\pi = 2 \\prod_{i=1}^{100} \\frac{4i^2}{4i^2 - 1}\n", "$$\n" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "collapsed": false }, "outputs": [], "source": [ "pi = 2\n", "eps = 1e-6\n", "dif = 2 * eps\n", "i = 1\n", "while(dif > eps):\n", " old_pi = pi\n", " pi *= 4 * i ** 2 / (4 * i ** 2 - 1)\n", " dif = pi - old_pi\n", " i += 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 51, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3.140707822589477" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pi" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "### while/break/continue\n", "\n", "Typical C-style while loop (Mandelbrot problem)::\n", "\n", " >>> z = 1 + 1j\n", " >>> while abs(z) < 100:\n", " ... z = z**2 + 1\n", " >>> z\n", " (-134+352j)\n", "\n" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "collapsed": false }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m [i while i < 10; i += 1]\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "[i while i < 10; i += 1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Defining functions\n", "\n", "### Function definition\n", " def test():\n", " print('in test function')\n", "\n", " >>> test()\n", " in test function\n", "\n", "Warning: Function blocks must be indented as other control-flow blocks.\n", "\n" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def test():\n", " print('in test function')" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "in test function\n" ] } ], "source": [ "test()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Return statement\n", "\n", "Functions can *optionally* return values.\n", "\n", "\n", " >>> def disk_area(radius):\n", " ...: return 3.14 * radius * radius\n", " ...:\n", "\n", " >>> disk_area(1.5)\n", " >>> 7.0649999999999995\n", "\n", "Note: By default, functions return ``None``.\n", "\n", "The syntax to define a function:\n", "\n", " * the ``def`` keyword;\n", "\n", " * is followed by the function's **name**, then\n", "\n", " * the arguments of the function are given between parentheses followed\n", " by a colon.\n", "\n", " * the function body;\n", "\n", " * and ``return object`` for optionally returning values.\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Parameters\n", "\n", "Mandatory parameters (positional arguments)\n", "\n", "\n", " >>> def double_it(x):\n", " ....: return x * 2\n", " ....:\n", "\n", " >>> double_it(3)\n", " >>> 6\n", "\n", " >>> double_it()\n", " ---------------------------------------------------------------------------\n", " Traceback (most recent call last):\n", " File \"\", line 1, in \n", " TypeError: double_it() takes exactly 1 argument (0 given)\n", "\n", "Optional parameters (keyword or named arguments)\n", "\n", "\n", " >>> def double_it(x=2):\n", " ....: return x * 2\n", " ....:\n", "\n", " >>> double_it()\n", " >>> 4\n", "\n", " >>> double_it(3)\n", " >>> 6\n", "\n", "Keyword arguments allow you to specify *default values*.\n" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def square(x):\n", " return x ** 2" ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "16" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "square(4)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: compute the 20-th Fibonacci number." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Object-oriented programming (OOP)\n", "\n", "Python supports object-oriented programming (OOP). The goals of OOP are:\n", "\n", " * to organize the code, and\n", "\n", " * to re-use code in similar contexts.\n", "\n", "\n", "\n", "Here is a small example: we create a Student *class*, which is an object\n", "gathering several custom functions (*methods*) and variables (*attributes*),\n", "we will be able to use::\n", "\n", " >>> class Student(object):\n", " ... def __init__(self, name):\n", " ... self.name = name\n", " ... def set_age(self, age):\n", " ... self.age = age\n", " ... def set_major(self, major):\n", " ... self.major = major\n", " ...\n", " >>> anna = Student('anna')\n", " >>> anna.set_age(21)\n", " >>> anna.set_major('physics')\n", "\n", "In the previous example, the Student class has ``__init__``, ``set_age`` and\n", "``set_major`` methods. Its attributes are ``name``, ``age`` and ``major``. We\n", "can call these methods and attributes with the following notation:\n", "``classinstance.method`` or ``classinstance.attribute``. The ``__init__``\n", "constructor is a special method we call with: ``MyClass(init parameters if\n", "any)``.\n", "\n", "Now, suppose we want to create a new class MasterStudent with the same\n", "methods and attributes as the previous one, but with an additional\n", "``internship`` attribute. We won't copy the previous class, but\n", "**inherit** from it::\n", "\n", " >>> class MasterStudent(Student):\n", " ... internship = 'mandatory, from March to June'\n", " ...\n", " >>> james = MasterStudent('james')\n", " >>> james.internship\n", " 'mandatory, from March to June'\n", " >>> james.set_age(23)\n", " >>> james.age\n", " 23" ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Numbers:\n", " def add(self, x, y):\n", " return x + y\n", " def substract(self, x, y):\n", " return x - y" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = Numbers()" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.add(2, 3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise: define a class for an integer number with methods ```add``` and ```substract``` " ] }, { "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }