{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "7F2u32atJ6ol" }, "source": [ "# Introduction to Python\n", "\n", "In this part of the tutorial, we will go through some aspects of the Python programming language, highlighting some useful specific aspects, with some practical tips for dayly use. Some knowledge of logic of programation is required. Of course this is overview is not supposed to be exaustive, and the reader could consult external sourcers for further information, such as:\n", "\n", " * [Learn python: interactive edition](https://panda.ime.usp.br/pensepy/static/pensepy/)\n", " * [The python tutorial](https://docs.python.org/3/tutorial/)\n", " * [https://www.learnpython.org/](https://www.learnpython.org/)\n", "\n", "You can also get herlp from the community, for instance in foruns like:\n", " * [Stackoverflow](https://stackoverflow.com/questions/tagged/python)\n", " * [reddit](https://www.reddit.com/r/Python/)\n", "\n", "Among other sources" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "DChkIzMBJ6or" }, "source": [ "## Basic numeric types\n", "\n", "In Python, your don't need to explicitly define the type of the variable. This is different from some programming languages like C, where the programmer should explicitly define the types of the variables. The running environment will guess the type from the variable content." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "h_O-uk7fJ6ov" }, "source": [ "You can use basic data numeric types are similar to those found in other languages, for instance:\n", "\n", "**Integers (``int``)**" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "colab": {}, "colab_type": "code", "collapsed": false, "id": "lDFKMjFTJ6o0", "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "i = 42\n", "j = 2199\n", "k = -9911" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 1422, "status": "ok", "timestamp": 1581354855419, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "p-WL0emJJ6pC", "jupyter": { "outputs_hidden": false }, "outputId": "729b64b0-d7cc-4a9d-8578-0301fdeaea66" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42 2199 -9911\n" ] } ], "source": [ "print(i, j, k)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2241\n" ] } ], "source": [ "print(i+j)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "7J7K7Z6mJ6pL" }, "source": [ "**Floating point values (``float``)**" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "colab": {}, "colab_type": "code", "collapsed": false, "id": "EnDckFl_J6pN", "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "a = 4.4\n", "b = 1/3\n", "c = 3.1e33" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 1565, "status": "ok", "timestamp": 1581354862222, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "Q6ISdfdwJ6pV", "jupyter": { "outputs_hidden": false }, "outputId": "b130178c-ff53-4bab-d1db-b79e18ca7ed7" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.4 0.3333333333333333 3.1e+33\n" ] } ], "source": [ "print(a, b, c)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "qjdmlHlLJ6pg" }, "source": [ "### Variable types and casting \n", "\n", "As we have previously said, there is no need to specify the type of the variable. Python will dynamically infer the type. However, you can force type conversion in different ways: " ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "colab": {}, "colab_type": "code", "id": "mY0yfEBvJ6pi" }, "outputs": [], "source": [ "x = 1.0\n", "y = float(1)\n", "z = float(i)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 1408, "status": "ok", "timestamp": 1581354869231, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "TFvwrL7qJ6po", "outputId": "533022a1-75e9-45b9-f5f7-fccb3a5ac515" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0 1.0 42.0\n" ] } ], "source": [ "print(x,y,z)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "N4hQqnZkJ6pw" }, "source": [ "**Complex values (``complex``)**" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "colab": {}, "colab_type": "code", "collapsed": false, "id": "nfou5KUNJ6pz", "jupyter": { "outputs_hidden": false } }, "outputs": [], "source": [ "d = complex(4., -1.)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 1066, "status": "ok", "timestamp": 1581354876663, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "UNkjON8yJ6p6", "jupyter": { "outputs_hidden": false }, "outputId": "fb92b50f-e2a9-4900-b1a8-ae25b43a792f" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(4-1j)\n" ] } ], "source": [ "print(d)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1.6666666666666667-0.3333333333333333j)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(1+d)/3" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LqZDpVjiJ6qA" }, "source": [ "\n", "\n", "Manipulating these variables behaves the way you would expect, so an operation (``+``, ``-``, ``*``, ``**``, etc.) on two values of the same type produces another value of the same type (with one, exception, ``/``, see below), while an operation on two values with different types produces a value of the more 'advanced' type:" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Lw2dks48J6qC" }, "source": [ "Adding two integers gives an integer:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 764, "status": "ok", "timestamp": 1581354880966, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "hoHYVhO4J6qE", "jupyter": { "outputs_hidden": false }, "outputId": "c70bed72-f500-4af8-b93a-eef7acb00569" }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 3" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "QKLSLd19J6qL" }, "source": [ "Multiplying two floats gives a float:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 730, "status": "ok", "timestamp": 1581354883529, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "YF1-IpSdJ6qO", "jupyter": { "outputs_hidden": false }, "outputId": "a40275fc-967e-41a4-fbd8-cacf983bb0e2" }, "outputs": [ { "data": { "text/plain": [ "6.0" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3. * 2." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "aDnKPUA9J6qV" }, "source": [ "Subtracting two complex numbers gives a complex number:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 787, "status": "ok", "timestamp": 1581354887016, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "Y_HPUOzcJ6qW", "jupyter": { "outputs_hidden": false }, "outputId": "be9b56fe-0770-4063-a6fa-1031298663ad" }, "outputs": [ { "data": { "text/plain": [ "(1-2j)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "complex(2., 4.) - complex(1., 6.)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "gjhy-JWuJ6qd" }, "source": [ "Multiplying an integer with a float gives a float:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 882, "status": "ok", "timestamp": 1581354892031, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "CWEsYaE5J6qg", "jupyter": { "outputs_hidden": false }, "outputId": "0b560d8b-d209-45cd-d47e-604a60f0116b" }, "outputs": [ { "data": { "text/plain": [ "27.599999999999998" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 * 9.2" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "a-ik2iGLJ6ql" }, "source": [ "Multiplying a float with a complex number gives a complex number:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 861, "status": "ok", "timestamp": 1581354895400, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "NjTuTk5kJ6qn", "jupyter": { "outputs_hidden": false }, "outputId": "984bcf63-1990-40f1-f45d-a02285fc23e4" }, "outputs": [ { "data": { "text/plain": [ "(-2+6j)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2. * complex(-1., 3.)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "pfAMKuiZJ6qv" }, "source": [ "Multiplying an integer and a complex number gives a complex number:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 722, "status": "ok", "timestamp": 1581354898789, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "8eyZxQLHJ6qw", "jupyter": { "outputs_hidden": false }, "outputId": "bf45dacb-642c-4979-d88d-386fb086fb34" }, "outputs": [ { "data": { "text/plain": [ "(-26.4+8j)" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 * complex(-3.3, 1)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0S7POICsJ6q1" }, "source": [ "However, the division of two integers gives a float:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 716, "status": "ok", "timestamp": 1581354902924, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "DKNXSX-NJ6q3", "jupyter": { "outputs_hidden": false }, "outputId": "005d0699-b214-4daf-dfb2-91b25b2162eb" }, "outputs": [ { "data": { "text/plain": [ "1.5" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 / 2" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "6xG_B7R4J6q7" }, "source": [ "Note that in Python 2.x, this used to return ``1`` because it would round the solution to an integer. If you ever need to work with Python 2 code, the safest approach is to add the following line at the top of the script:\n", "\n", " from __future__ import division\n", " \n", "and the division will then behave like a Python 3 division. Note that in Python 3 you can also specifically request integer division:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "collapsed": false, "executionInfo": { "elapsed": 716, "status": "ok", "timestamp": 1581354910574, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "7gm2NhboJ6q9", "jupyter": { "outputs_hidden": false }, "outputId": "5ba5d1be-1f91-490b-fad6-55363aa4fdb5" }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 // 2" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 % 2" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-UsfW2tlHu9A" }, "source": [ "## Blocks and identation\n", "\n", "Python uses identation for delemiting the scope of a block of code. Thus, constructing an 'if' for instance, we need to indent the code properly\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "colab_type": "code", "executionInfo": { "elapsed": 7133, "status": "ok", "timestamp": 1581355473206, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "6IbtImvhIFQA", "outputId": "c40b209d-9ad3-4c76-dd64-e9f2899a7e84" }, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "Enter a number: 3\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "3 is Odd\n" ] } ], "source": [ "num = int(input(\"Enter a number: \"))\n", "if (num % 2) == 0:\n", " print(\"you typed {0}\".format(num) )\n", " print(\"{0} is Even\".format(num))\n", " if (num == 0):\n", " print(\"The number is also 0\")\n", "else:\n", " print(\"{0} is Odd\".format(num))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "s-0K0GuMI2Ll" }, "source": [ "This should be also used in loops" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(10))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 191 }, "colab_type": "code", "executionInfo": { "elapsed": 833, "status": "ok", "timestamp": 1581355719970, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "vkwRAcbJJPz4", "outputId": "097b1069-08ad-404b-8fa2-0720a2e41c48" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "for i in range(10):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 104 }, "colab_type": "code", "executionInfo": { "elapsed": 8400, "status": "ok", "timestamp": 1581355852134, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "nvP_M6fSJY5k", "outputId": "a3a94b6d-f36c-4ed2-cb2d-708d15253ce0" }, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "Enter a number: 5\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "5 is Odd\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "Enter a number: 2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "2 is Even\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "Enter a number: 1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "1 is Odd\n" ] }, { "name": "stdin", "output_type": "stream", "text": [ "Enter a number: 0\n" ] } ], "source": [ "num = int(input(\"Enter a number: \"))\n", "while not num == 0:\n", " if (num % 2) == 0:\n", " print(\"{0} is Even\".format(num))\n", " else:\n", " print(\"{0} is Odd\".format(num))\n", " num = int(input(\"Enter a number: \"))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "AXv0ONureq4u" }, "source": [ "## Lists\n", "\n", "A list is an ordered collection of values. The values that make up a list are called its **elements**. There are several ways to create a new list. the simplest is to enclose the elements in square brackets ([ and ]):\n", "\n" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "colab": {}, "colab_type": "code", "id": "2zyy8V1D7CRW" }, "outputs": [], "source": [ "l1 = [1,2,3]\n", "l2 = ['C','H','H','H','H']" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "colab_type": "code", "executionInfo": { "elapsed": 753, "status": "ok", "timestamp": 1581354963612, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "erjAAKhEGadh", "outputId": "f45bae6f-3cef-4e71-9c97-003d2b7216ec" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n", "['C', 'H', 'H', 'H', 'H']\n" ] } ], "source": [ "print(l1)\n", "print(l2)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(l1)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min(l1)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(l1)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2.0\n" ] } ], "source": [ "mean = sum(l1)/len(l1)\n", "print(mean)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "L9HrWs7q62yG" }, "source": [ "Another one is to create an empty list, and then add content dynamically\n", "\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "colab": {}, "colab_type": "code", "id": "mJX0S0LzxLlp" }, "outputs": [], "source": [ "l3 = []\n", "\n", "l3.append(4)\n", "l3.append(5)\n", "l3.append(6)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 5, 6]\n" ] } ], "source": [ "print(l3)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 5, 6, 10]\n" ] } ], "source": [ "l3.append(10)\n", "print(l3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "5Um8rTVwxj6Z" }, "source": [ "The content of the lists are very flexible, for instance you can append a list as an element of another lest" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 760, "status": "ok", "timestamp": 1581354985929, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "HbpzuutixcmV", "outputId": "174ed80d-a2b0-4d5e-e432-a1fe19f47f42" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 5, 6, 10, [1, 2, 3]]\n" ] } ], "source": [ "l3.append(l1)\n", "print(l3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "7YizK5npx51D" }, "source": [ "You can also copy the elements of one list to another one using the extend function:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 828, "status": "ok", "timestamp": 1581354989335, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "4afd-NpbxgEu", "outputId": "3679182b-4196-4395-a21b-d5bfafdd92b5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 5, 6, 10, [1, 2, 3], 1, 2, 3]\n" ] } ], "source": [ "l3.extend(l1)\n", "print(l3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "21tGPd_q68Cr" }, "source": [ "Or join two lists with the '+' command" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 818, "status": "ok", "timestamp": 1581354992585, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "iPe5OCmx7Az9", "outputId": "e7cfe57d-4522-46e6-f67b-bbcf7a89ca11" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 'C', 'H', 'H', 'H', 'H']\n" ] } ], "source": [ "l4 = l1+l2\n", "print(l4)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "cPwwRpJI4HMo" }, "source": [ "We can counsult the size of the list" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "colab_type": "code", "executionInfo": { "elapsed": 761, "status": "ok", "timestamp": 1581354995833, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "PZEIBh8Z4K1E", "outputId": "6dfe9aad-b3d2-401d-cee1-9ea9f72a7d6d" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "5\n", "8\n" ] } ], "source": [ "print(len(l1))\n", "print(len(l2))\n", "print(len(l3))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "1WuPujoM6nuC" }, "source": [ "We can also consult if some element belongs to the list" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 806, "status": "ok", "timestamp": 1581355000474, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "cqwMGgoG6swX", "outputId": "e26ff890-074b-4bc2-b4d8-eee4b72e2061" }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "4 in l1" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 1015, "status": "ok", "timestamp": 1581355004849, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "UGBNwIhr6yh_", "outputId": "e5f82dba-bb46-40fb-a164-7bbca37d7adb" }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 in l1" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "227yWAb18kvw" }, "source": [ "We can use indexing for acessing an specific element or a slice of the list" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 724, "status": "ok", "timestamp": 1581355007165, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "t0uxE23I8xld", "outputId": "d746d901-7428-40b5-ea93-c35858fd64b4" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "[10, [1, 2, 3], 1]\n" ] } ], "source": [ "print(l1[0])\n", "print(l3[3:6])" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "print(l1[-2])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zSMM58p97ezQ" }, "source": [ "You can replace elements of the lis" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 706, "status": "ok", "timestamp": 1581355013376, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "56Inx6Xa7kEH", "outputId": "935774c4-5139-45a8-9d3c-d67ea265f9e5" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 0, 3]\n" ] } ], "source": [ "l1[1] = 0\n", "print(l1)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LdUzEi_nF2j_" }, "source": [ "And also delete some element" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 1007, "status": "ok", "timestamp": 1581355018390, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "aCj2u_B8F5kG", "outputId": "032dcecd-8e21-4d45-8858-2c96b90be1c2" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 3]\n" ] } ], "source": [ "del(l1[0])\n", "print(l1)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ClLmxP-PKAES" }, "source": [ "### Dictionaries\n", "\n", "Dictionary is a built-in python structure that can be used to map keys to values. \n", "\n", "It is a very useful structure, that can be used in many situations. For instance, let's create a dictionary that maps elements to atomic numbers:" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "colab": {}, "colab_type": "code", "id": "e_aQ9L7ZNFfI" }, "outputs": [], "source": [ "element_to_number = {}\n", "element_to_number['H'] = 1\n", "element_to_number['C'] = 6\n", "element_to_number['N'] = 7\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "PhlW9h0iRbPr" }, "source": [ "The first assignment creates a dictionary named element_to_number; the other assignments add new key:value pairs to the dictionary. \n", "\n", "We can print the current value of the dictionary in the usual way:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 1028, "status": "ok", "timestamp": 1581355046038, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "jzXoSUQ-SC0j", "outputId": "1eebc69f-f5b1-4442-f374-eda470d96afc" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'H': 1, 'C': 6, 'N': 7}\n" ] } ], "source": [ "print(element_to_number)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "3FOFho0OSDUw" }, "source": [ "Another way to create a dictionary is to provide a list of key:value pairs using the same syntax as the previous output:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "colab": {}, "colab_type": "code", "id": "PKHpMY6zQjbD" }, "outputs": [], "source": [ "element_to_number = {\n", " 'H': 1,\n", " 'C': 6,\n", " 'N': 7\n", "}" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2aN4Ctx_RjfP" }, "source": [ "Once it is created, we can use it to retrieve the value, given a key:" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 892, "status": "ok", "timestamp": 1581355052801, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "QM9h9d3XSuzW", "outputId": "9eeb039d-4cb1-4f80-b8d3-8ba4ddb06c1e" }, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "element_to_number['H']" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "zDlEyKL6HdQn" }, "source": [ "We can use this dictionary, for example, associated with an [inline for loop](https://www.programiz.com/python-programming/list-comprehension) to convert a list of elements to numbers" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 726, "status": "ok", "timestamp": 1581356891519, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "VUdC1C_yNdqh", "outputId": "83bc562f-83b2-43cc-ceae-a1cae6a14941" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[6, 1, 1, 1, 1]\n" ] } ], "source": [ "elements = ['C', 'H', 'H', 'H', 'H']\n", "\n", "numbers = [element_to_number[e] for e in elements]\n", "\n", "print(numbers)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "numbers = []\n", "for e in elements:\n", " numbers.append(element_to_number[e])" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Lc5h1MD_Ok-e" }, "source": [ "## Libraries and packages\n", "\n", "Python has many libraryies that can be used for many purpuses. Learning how to find and use them can save you a lot of time (re)implementing things. \n", "\n", "\n", "![](https://imgs.xkcd.com/comics/python.png)\n", "\n", "\n", "For instance, we can use the Counter metho in the collections packages to count the number of elements in a list:\n" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 714, "status": "ok", "timestamp": 1581357124059, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "Zx2jbB9wOne1", "outputId": "43f3edda-238d-48b2-d0e2-8085c53df4ea" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Counter({'H': 4, 'C': 1})\n" ] } ], "source": [ "from collections import Counter\n", "print(Counter(elements))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mqnmaq1sQbXQ" }, "source": [ "[Pypi](https://pypi.org/) is a repository that compiles several packages. Two simple ways to install new packages is [pip](https://pt.wikipedia.org/wiki/Pip_(gerenciador_de_pacotes)) and, if you are using anaconda python, [conda](https://docs.conda.io/en/latest/). We will learn how to use other packages latter on this series of lectures." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "IWiSgAJbesZj" }, "source": [ "## Scripting\n", "\n", "A very common task in working with data science and computer supported research is to build configurable scripts that one can configurates by passing arguments through the command line (like in a shell script). In python, we can use use the optparse module to help you with that. For instance, the script below, we can pass two arguments in different ways. Copy and paste the script below into a file, and name it 'year.py'\n", "\n", "```python\n", "#!/usr/bin/env python\n", "# Years till 100\n", "import sys\n", "import optparse\n", "\n", "parser = optparse.OptionParser()\n", "parser.add_option('-n', '--name', dest='name', help='Your Name')\n", "parser.add_option('-a', '--age', dest='age', help='Your Age', type=int)\n", "\n", "(options, args) = parser.parse_args()\n", "\n", "if options.name is None:\n", " options.name = raw_input('Enter Name:')\n", "\n", "if options.age is None:\n", " options.age = int(raw_input('Enter Age:'))\n", "\n", "sayHello = 'Hello ' + options.name + ','\n", "\n", "if options.age == 100:\n", " sayAge = 'You are already 100 years old!'\n", "elif options.age < 100:\n", " sayAge = 'You will be 100 in ' + str(100 - options.age) + ' years!'\n", "else:\n", " sayAge = 'You turned 100 ' + str(options.age - 100) + ' years ago!'\n", "\n", "print (sayHello, sayAge)\n", "````\n", "\n", " This script imports the optparse package in order to make use of the class OptionParser. The OptionParse class will allow you to add options to your script and it will generate a help option based on the options you provide. In this example, we are adding two options: -n (or --name) and -a (or --age). The first parameter to add_option is the short option and the 2nd is the long option, it is quite common in the Unix & Linux environment to add a short and long version of an option. Tthe next optional parameters to the add_option function are dest=, which is the variable name created, help=, which is the help text generated and type=, which gives the type for the variable. By default the type is string, but for age, we want to make it int.\n", "\n", "Finally, after adding the options, we call the parse_args function, which will return an options object and an args list object. We can access the variables defined in \"dest=\" when adding options on the options object returned. So it will have two options, options.name and options.age. If one of the variables wasn't passed in, we can check by using the \"if variableName is None\" condition. Then we will load from user input as before.\n", "\n", "Now, there are several ways to run this script: \n", "\n", "| command | usage |\n", "| --------------------- |:--------------------------| \n", "| ./years.py \t | Prompts for user and age |\n", "| ./years.py -n Joe |\tSets user, prompts for age |\n", "| ./years.py --name Joe |\tSets user, prompts for age |\n", "| ./years.py -a 25\t | Sets age, prompts for user |\n", "| ./years.py --age 25\t | Sets age, prompts for user |\n", "| ./years.py -a 25 --name Joe |\tSets age, sets user |\n", "| ./years.py -n Joe --age 25\t| Sets age, sets user |\n", "\n", "Another thing you can do now is run the help option, by specifying either -h or --help: \n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Q3BSuMs2maBV" }, "source": [ "## Configuration files\n", "\n", "Another way to input options for a script is to write a configuration file. There are many options like using [.ini, .json, and .yaml](https://martin-thoma.com/configuration-files-in-python/) files. The example bellow shows a .yaml file. Copy and paste it to a file named 'config.yml'\n", "\n", "```\n", "user:\n", " age: 25\n", " name: Joe\n", "\n", "configuration:\n", " color: blue\n", "```\n", "\n", "That can be read by an script using the script below:\n", "\n", "```python\n", "#!/usr/bin/env python\n", "import yaml\n", "\n", "with open(\"config.yml\", 'r') as ymlfile:\n", " cfg = yaml.load(ymlfile, Loader=yaml.FullLoader)\n", "\n", "for section in cfg:\n", " print(section)\n", "\n", "print(cfg['user']['age'])\n", "print(cfg['configuration']['color'])\n", "```" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jZpclTAGrxAP" }, "source": [ "## Transversing a file structure\n", "\n", "Another common task is to transverse the file structure of some directory. For instance, if you have scheleduled several jobs in a cluster for doing some calculation, you may wish to go through the folder where results were saved to check if all jobs provided an output. \n", "\n", "In python, we can use the `os` library to help in transversing the structure. For instance, if we a file strucutre like this\n", "\n", "![](https://www.bogotobogo.com/python/images/TraversingDirectory/simple-tree.png)\n", "\n", "The code snipet below will transverse the tree structure of the `TEST` folder\n", "\n", "```python\n", "import os\n", "path = \"./TEST\"\n", "\n", "for root,d_names,f_names in os.walk(path):\n", "\tprint root, d_names, f_names\n", "```\n", "\n", "producing\n", "\n", "```\n", "./TEST ['D1', 'D2'] ['root.txt']\n", "./TEST/D1 [] ['d1_b.txt', 'd1_a.txt']\n", "./TEST/D2 [] ['d2_a.txt']\n", "``` \n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ewObkzgH8LcX" }, "source": [ "## Functions\n", "\n", "In Python, function is a group of related statements that perform a specific task.\n", "\n", "Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable.\n", "\n", "Furthermore, it avoids repetition and makes code reusable.\n", "\n", "The syntax of a function is\n", "\n", "```python\n", "def function_name(parameters):\n", "\t\"\"\"docstring\"\"\"\n", "\tstatement(s)\n", "```\n", "\n", "Above shown is a function definition which consists of following components.\n", "\n", " - Keyword `def` marks the start of function header.\n", " - A function name to uniquely identify it. Function naming follows the same rules of writing [identifiers in Python](https://www.programiz.com/python-programming/keywords-identifier#rules).\n", " - Parameters (arguments) through which we pass values to a function. They are optional.\n", " - A colon (:) to mark the end of function header.\n", " - Optional documentation string (docstring) to describe what the function does.\n", " - One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).\n", " - An optional `return statement to return a value from the function.\n", "\n", "All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "colab_type": "code", "executionInfo": { "elapsed": 976, "status": "ok", "timestamp": 1581470291997, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "cAa2ZR9R9UMa", "outputId": "c7ff2f78-8274-442e-c113-2e1809b9c726" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Values previous the call [10, 20, 30]\n", "Values inside the function: [10, 20, 30, [1, 2, 3, 4]]\n", "Values outside the function: [10, 20, 30, [1, 2, 3, 4]]\n" ] } ], "source": [ "def append_list( mylist ):\n", " \"This changes a passed list into this function\"\n", " mylist.append([1,2,3,4]);\n", " print(\"Values inside the function: \", mylist)\n", " return\n", "\n", "# Now you can call changeme function\n", "mylist = [10,20,30];\n", "print(\"Values previous the call\", mylist)\n", "append_list( mylist );\n", "print (\"Values outside the function: \", mylist)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "FTYJk3-DEGQu" }, "source": [ "### Default arguments\n", "\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 age if it is not passed −\n" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 86 }, "colab_type": "code", "executionInfo": { "elapsed": 781, "status": "ok", "timestamp": 1581471920847, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "Uoy0B8Q8EflN", "outputId": "81b7f0f6-303a-4f85-d79b-edad03affa59" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Name: miki\n", "Age 50\n", "Name: miki\n", "Age 35\n" ] } ], "source": [ "def printinfo( name, age = 35 ):\n", " \"This prints a passed info into this function\"\n", " print (\"Name: \", name)\n", " print (\"Age \", age)\n", " return;\n", "\n", "# Now you can call printinfo function\n", "printinfo( age=50, name=\"miki\" )\n", "printinfo( name=\"miki\" )" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Tme-HEhuGGWQ" }, "source": [ "## Timing code snipts \n", "\n", "Sometimes, we want to have an idea about the runtime of a piece of code. In jupyter notebooks, we can estimate the running time using the [magic commands](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-timeit) `%timeit` (for a single line) and `%%timeit` (for an entire cell)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 4440, "status": "ok", "timestamp": 1581473152509, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "VlKneLtoGamx", "outputId": "7cb45159-7236-4810-89b9-9d435836a36b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "123\n", "814 ns ± 12 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n" ] } ], "source": [ "print('123')\n", "%timeit sum(range(100))" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 2123, "status": "ok", "timestamp": 1581472869704, "user": { "displayName": "Ronaldo Prati", "photoUrl": "https://lh3.googleusercontent.com/a-/AAuE7mCsO1Q96nR8aZv_9Hd81R4y4pOXjbeVhZLUjLAPNw=s64", "userId": "11520667040770147820" }, "user_tz": 180 }, "id": "OPmT-5CgICz5", "outputId": "8f01208f-f38d-4c46-d38b-f06ad9f68a48" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "265 ms ± 3.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" ] } ], "source": [ "%%timeit\n", "total = 0\n", "for i in range(1000):\n", " for j in range(1000):\n", " total += i * (-1) ** j\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "1. PythonBasics.ipynb", "provenance": [] }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 4 }