{"cells":[{"cell_type":"markdown","metadata":{"id":"U-CNG-VWsgTu"},"source":["# Introduction to Python\n","\n","Content of this tutorial is delivered during the Introduction to Natural Language Processing course at Heriot-Watt University.\n","\n","> Adapted from the cs228 Python tutorial by Volodymyr Kuleshov and Isaac Caswell (https://github.com/kuleshov/cs228-material/blob/master/tutorials/python/cs228-python-tutorial.ipynb).\n","\n"]},{"cell_type":"markdown","metadata":{"id":"C0p0eWmpsgTw"},"source":["## Introduction"]},{"cell_type":"markdown","metadata":{"id":"XQAVjrexsgTx"},"source":["Python is a great general-purpose programming language on its own, but with the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific computing. It's also considered as the [top programming language in 2023](https://spectrum.ieee.org/the-top-programming-languages-2023).\n","\n","We expect that many of you will have some experience with Python; for the rest of you, this section will serve as a quick crash course both on the Python programming language and on the use of Python for scientific computing.\n","\n","Some of you may have previous knowledge in Matlab, in which case we also recommend the numpy for Matlab users page (https://docs.scipy.org/doc/numpy/user/numpy-for-matlab-users.html).\n"]},{"cell_type":"markdown","metadata":{"id":"Zq6hR_d3sgTx"},"source":["In this tutorial, we will cover:\n","\n","* Basic Python: Basic data types (Containers, Lists, Dictionaries, Sets, Tuples), Functions, Classes\n","\n","**The good programmer tip**: Every library that we are going to use has a dedicated documentation. Please refer to it when you have some doubts. They are your dearest friends :)"]},{"cell_type":"markdown","metadata":{"id":"Co001VGjsgTx"},"source":["## Basics of Python"]},{"cell_type":"markdown","metadata":{"id":"jjy74GFzsgTy"},"source":["Python is a high-level, dynamically typed multiparadigm programming language. Python code is often said to be almost like pseudocode, since it allows you to express very powerful ideas in very few lines of code while being very readable. As an example, here is an implementation of the classic quicksort algorithm in Python:"]},{"cell_type":"code","execution_count":1,"metadata":{"collapsed":true,"id":"SKjjNxsasgTy","executionInfo":{"status":"ok","timestamp":1732116724789,"user_tz":-60,"elapsed":286,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# Function definition starts with the `def` keyword followed by the function name\n","def quicksort(arr):\n","    if len(arr) <= 1:\n","        return arr\n","    pivot = arr[len(arr) // 2]\n","    left = [x for x in arr if x < pivot]\n","    middle = [x for x in arr if x == pivot]\n","    right = [x for x in arr if x > pivot]\n","    return quicksort(left) + middle + quicksort(right)"]},{"cell_type":"code","source":["quicksort([3,6,8,10,1,2,1])"],"metadata":{"id":"clWTDxRS8Krb","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116725452,"user_tz":-60,"elapsed":373,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"fcf67f93-5a4c-4caa-a5cc-614f46423ac6"},"execution_count":2,"outputs":[{"output_type":"execute_result","data":{"text/plain":["[1, 1, 2, 3, 6, 8, 10]"]},"metadata":{},"execution_count":2}]},{"cell_type":"markdown","metadata":{"id":"dVXPP3r0sgT0"},"source":["### Basic data types"]},{"cell_type":"markdown","metadata":{"id":"S4RmF6QAsgT0"},"source":["#### Numbers"]},{"cell_type":"markdown","metadata":{"id":"aPdh5UTWsgT0"},"source":["Integers and floats work as you would expect from other languages:"]},{"cell_type":"code","execution_count":3,"metadata":{"collapsed":true,"id":"JX-UmPl0sgT1","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116725452,"user_tz":-60,"elapsed":26,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"05e630f1-52eb-4752-b6b2-9b12be737bc5"},"outputs":[{"output_type":"stream","name":"stdout","text":["Value: 3 - Type: <class 'int'>\n"]}],"source":["x = 3\n","print(\"Value: {} - Type: {}\".format(x, type(x)))"]},{"cell_type":"code","execution_count":4,"metadata":{"collapsed":true,"id":"UpHMHMrysgT1","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":25,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"a669669a-8ea6-41be-95ea-85e7eefa21db"},"outputs":[{"output_type":"stream","name":"stdout","text":["x + 1 = 4\n","x - 1 = 2\n","x * 2 = 6\n","x ** 2 = 9\n"]}],"source":["print(\"x + 1 = {}\".format(x + 1))   # Addition;\n","print(\"x - 1 = {}\".format(x - 1))   # Subtraction;\n","print(\"x * 2 = {}\".format(x * 2))   # Multiplication;\n","print(\"x ** 2 = {}\".format(x ** 2))  # Exponentiation;"]},{"cell_type":"markdown","metadata":{"id":"WMlbpdQ7sgT1"},"source":["#### New in Python 3.5.\n","\n","The / (division) and // (floor division) operators yield the quotient of their arguments. The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the ‘floor’ function applied to the result. Division by zero raises the ZeroDivisionError exception. For details Python 3 [official documentation]( https://docs.python.org/3.7/reference/expressions.html)."]},{"cell_type":"code","execution_count":5,"metadata":{"collapsed":true,"id":"6EH3lDycsgT1","colab":{"base_uri":"https://localhost:8080/"},"outputId":"25621bf4-3fa5-4ea2-b29b-3ad5a98343e9","executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":24,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["x/2 = 1.5\n"]}],"source":["print(f\"x/2 = {x/2}\") # floating point division"]},{"cell_type":"code","execution_count":6,"metadata":{"collapsed":true,"id":"zjYgUd-ZsgT2","colab":{"base_uri":"https://localhost:8080/"},"outputId":"ae7ad592-505c-4811-c42f-4229117c282d","executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":23,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["x // 2 = 1\n"]}],"source":["print(f\"x // 2 = {x//2}\") # exact division"]},{"cell_type":"code","execution_count":7,"metadata":{"collapsed":true,"id":"nfvlITFMsgT2","colab":{"base_uri":"https://localhost:8080/"},"outputId":"8add8d7b-927d-4ef3-bb35-af8f374fab81","executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":21,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["4\n","8\n"]}],"source":["x += 1\n","print(x)  # Prints \"4\"\n","x *= 2\n","print(x)  # Prints \"8\""]},{"cell_type":"code","execution_count":8,"metadata":{"collapsed":true,"id":"U30EdqXIsgT2","colab":{"base_uri":"https://localhost:8080/"},"outputId":"d55ca1d8-f0da-4b91-e090-4e25e806888b","executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":19,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Variable y is of type: <class 'float'>\n","y = 2.5, y + 1 = 3.5, y * 2 = 5.0, y ** 2 = 6.25\n"]}],"source":["y = 2.5\n","print(f\"Variable y is of type: {type(y)}\") # Prints \"<type 'float'>\"\n","print(f\"y = {y}, y + 1 = {y+1}, y * 2 = {y*2}, y ** 2 = {y ** 2}\") # Prints \"2.5 3.5 5.0 6.25\""]},{"cell_type":"markdown","metadata":{"id":"jAaAs9FJsgT2"},"source":["Write code to compute the following expression: $3 \\cdot \\frac{(8-5)^2 \\cdot 3}{5}$"]},{"cell_type":"code","execution_count":9,"metadata":{"collapsed":true,"id":"XyaoWGw4sgT2","executionInfo":{"status":"ok","timestamp":1732116725453,"user_tz":-60,"elapsed":17,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# write code here\n","\n","\n"]},{"cell_type":"code","execution_count":10,"metadata":{"collapsed":true,"id":"w7aTfytZsgT2","colab":{"base_uri":"https://localhost:8080/","height":110},"outputId":"f2ace86e-1578-4218-d12e-83300cedb88b","executionInfo":{"status":"error","timestamp":1732116725453,"user_tz":-60,"elapsed":17,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"error","ename":"SyntaxError","evalue":"invalid syntax (<ipython-input-10-0af4bb0eac37>, line 1)","traceback":["\u001b[0;36m  File \u001b[0;32m\"<ipython-input-10-0af4bb0eac37>\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m    x++\u001b[0m\n\u001b[0m       ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n"]}],"source":["x++"]},{"cell_type":"markdown","metadata":{"id":"aFMiNW11sgT3"},"source":["Note that unlike many languages, Python does not have unary increment (x++) or decrement (x--) operators.\n","\n","Python also has built-in types for long integers and complex numbers; you can find all of the details in the [documentation](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-long-complex)."]},{"cell_type":"markdown","metadata":{"id":"MRocEtMqsgT3"},"source":["#### Booleans"]},{"cell_type":"markdown","metadata":{"id":"Eehymz0QsgT3"},"source":["Python implements all of the usual operators for Boolean logic, but uses English words rather than symbols (`&&`, `||`, etc.):"]},{"cell_type":"code","execution_count":11,"metadata":{"collapsed":true,"id":"qITLfxzusgT3","colab":{"base_uri":"https://localhost:8080/"},"outputId":"c4617177-d75c-40ab-b713-13ab6b07becd","executionInfo":{"status":"ok","timestamp":1732116789418,"user_tz":-60,"elapsed":419,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Variable y is of type: <class 'bool'>\n"]}],"source":["t, f = True, False\n","print(f\"Variable y is of type: {type(t)}\") # Prints \"<type 'bool'>\""]},{"cell_type":"markdown","metadata":{"id":"6-QJJS4CsgT3"},"source":["Now we let's look at the operations:"]},{"cell_type":"code","execution_count":12,"metadata":{"collapsed":true,"id":"fUT-pno6sgT3","colab":{"base_uri":"https://localhost:8080/"},"outputId":"1be55663-6edd-4e74-dbc1-70e70ffd7c86","executionInfo":{"status":"ok","timestamp":1732116789893,"user_tz":-60,"elapsed":41,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["t AND f = False\n","t OR f = True\n","NOT t = False\n","t XOR f = True\n"]}],"source":["print(f\"t AND f = {t and f}\") # Logical AND;\n","print(f\"t OR f = {t or f}\")  # Logical OR;\n","print(f\"NOT t = {not t}\")   # Logical NOT;\n","print(f\"t XOR f = {t != f}\")  # Logical XOR;"]},{"cell_type":"markdown","metadata":{"id":"2L86Jd_CsgT3"},"source":["What is the result of the expression $(True \\enspace AND \\enspace False) \\enspace OR \\enspace (True \\enspace OR \\enspace False)$?"]},{"cell_type":"code","execution_count":13,"metadata":{"collapsed":true,"id":"seDB9QmasgT3","executionInfo":{"status":"ok","timestamp":1732116789893,"user_tz":-60,"elapsed":39,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# write code here\n","\n","\n"]},{"cell_type":"markdown","metadata":{"id":"sBhBgHwgsgT3"},"source":["#### Strings"]},{"cell_type":"code","execution_count":14,"metadata":{"collapsed":true,"id":"XbTcV_mgsgT3","colab":{"base_uri":"https://localhost:8080/"},"outputId":"c439f164-5229-4d60-b95c-5277cb15c4d2","executionInfo":{"status":"ok","timestamp":1732116789893,"user_tz":-60,"elapsed":39,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["hello 5\n"]}],"source":["hello = 'hello'   # String literals can use single quotes\n","world = \"world\"   # or double quotes; it does not matter.\n","print(hello, len(hello))"]},{"cell_type":"code","execution_count":15,"metadata":{"collapsed":true,"id":"T_192wwssgT3","colab":{"base_uri":"https://localhost:8080/"},"outputId":"47e0ba76-69fb-4e0d-da78-b8d06e72c9ff","executionInfo":{"status":"ok","timestamp":1732116789893,"user_tz":-60,"elapsed":36,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["hello + world = hello world\n"]}],"source":["hw = hello + ' ' + world  # String concatenation\n","print(f\"hello + world = {hw}\")  # prints \"hello world\""]},{"cell_type":"code","execution_count":16,"metadata":{"id":"v1eH5qMFsgT3","colab":{"base_uri":"https://localhost:8080/"},"outputId":"11ebff7e-68cb-4a8b-85f1-acafa2acd6fe","executionInfo":{"status":"ok","timestamp":1732116789893,"user_tz":-60,"elapsed":34,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["hello world 12\n","hello world 14\n","hello world 16\n"]}],"source":["hw12 = '%s %s %d' % (hello, world, 12)  # sprintf style string formatting\n","print(hw12)  # prints \"hello world 12\"\n","\n","hw_format = \"{} {} {}\".format(hello, world, 14) # format method\n","print(hw_format)\n","\n","hw_format = f\"{hello} {world} 16\" # fstring method\n","print(hw_format)"]},{"cell_type":"markdown","metadata":{"id":"-QhKRmVxsgT3"},"source":["String objects have a bunch of useful methods; for example:"]},{"cell_type":"code","execution_count":17,"metadata":{"collapsed":true,"id":"YzDah2NvsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"bf03ed57-bd60-4759-db29-a303b39d8d17","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":33,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Hello\n","HELLO\n","  hello\n"," hello \n","he(ell)(ell)o\n","world\n"]}],"source":["s = \"hello\"\n","print(s.capitalize())  # Capitalize a string; prints \"Hello\"\n","print(s.upper())       # Convert a string to uppercase; prints \"HELLO\"\n","print(s.rjust(7))      # Right-justify a string, padding with spaces; prints \"  hello\"\n","print(s.center(7))     # Center a string, padding with spaces; prints \" hello \"\n","print(s.replace('l', '(ell)'))  # Replace all instances of one substring with another;\n","                               # prints \"he(ell)(ell)o\"\n","print ('  world '.strip())  # Strip leading and trailing whitespace; prints \"world\""]},{"cell_type":"markdown","metadata":{"id":"6friQlnpsgT4"},"source":["Create two strings $s1$=_'you are very tired'_ and $s2$=_'fight for the best'_. Concatenate the first $8$ characters of $s1$ with the last $8$ characters of $s2$ into a new string $s3$ and print it."]},{"cell_type":"code","execution_count":18,"metadata":{"collapsed":true,"id":"mfSzAGYMsgT4","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":31,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# write code here\n","\n","\n"]},{"cell_type":"markdown","metadata":{"id":"yo1l3NNLsgT4"},"source":["You can find a list of all string methods in the [documentation](https://docs.python.org/2/library/stdtypes.html#string-methods)."]},{"cell_type":"markdown","metadata":{"id":"RxqFNEG0sgT4"},"source":["### Containers"]},{"cell_type":"markdown","metadata":{"id":"y2nIkYAMsgT4"},"source":["Python includes several built-in container types: lists, dictionaries, sets, and tuples."]},{"cell_type":"markdown","metadata":{"id":"stI3onhrsgT4"},"source":["#### Lists"]},{"cell_type":"markdown","metadata":{"id":"LMbb5FiJsgT4"},"source":["A list is the Python equivalent of an array, but is resizeable and can contain elements of different types:"]},{"cell_type":"code","execution_count":19,"metadata":{"collapsed":true,"id":"a9kPdFJvsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"48789188-152f-4757-c8e8-07b55baac3d0","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":31,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["List: [3, 1, 2] - 2nd element: 2\n","Last element: 2\n"]}],"source":["xs = [3, 1, 2]   # Create a list\n","print(f\"List: {xs} - 2nd element: {xs[2]}\")\n","print(f\"Last element: {xs[-1]}\")     # Negative indices count from the end of the list; prints \"2\""]},{"cell_type":"code","execution_count":20,"metadata":{"collapsed":true,"id":"HhUhdHzQsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"353e29bb-4f38-4093-89f2-86c08dd07fba","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":28,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[3, 1, 'foo']\n"]}],"source":["xs[2] = 'foo'    # Lists can contain elements of different types (not recommended but it may be useful...)\n","print(xs)"]},{"cell_type":"code","execution_count":21,"metadata":{"collapsed":true,"id":"kJZetvffsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"6e97c225-9b56-4fa2-fd17-9f1c6a34d289","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":26,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[3, 1, 'foo', 'bar']\n"]}],"source":["xs.append('bar') # Add a new element to the end of the list\n","print(xs)"]},{"cell_type":"code","execution_count":22,"metadata":{"collapsed":true,"id":"06Pn4TpOsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"51464890-7316-46d7-a5b5-f765b7f00267","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":24,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Popped element: bar - new list: [3, 1, 'foo']\n"]}],"source":["x = xs.pop()     # Remove and return the last element of the list\n","print(f\"Popped element: {x} - new list: {xs}\")"]},{"cell_type":"markdown","metadata":{"id":"2-6GEBfcsgT4"},"source":["As usual, you can find all the gory details about lists in the [documentation](https://docs.python.org/3/tutorial/datastructures.html#more-on-lists)."]},{"cell_type":"markdown","metadata":{"id":"0r1Q02m8sgT4"},"source":["#### Slicing"]},{"cell_type":"markdown","metadata":{"id":"2Xl7tEslsgT4"},"source":["In addition to accessing list elements one at a time, Python provides concise syntax to access sublists; this is known as slicing:"]},{"cell_type":"code","execution_count":23,"metadata":{"collapsed":true,"id":"gkE7pRqFsgT4","colab":{"base_uri":"https://localhost:8080/"},"outputId":"3cc8ed1b-3133-46b6-deee-821cdf31fe67","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":22,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 1, 2, 3, 4]\n","nums[2:4] = [2, 3]\n","nums[2:] = [2, 3, 4]\n","nums[:2] = [0, 1]\n","nums[:] = [0, 1, 2, 3, 4]\n","nums[:-1] = [0, 1, 2, 3]\n","[0, 1, 8, 9, 4]\n"]}],"source":["# range is a built-in function that returns an \"immutable\" sequence of numbers\n","nums = list(range(5))    # we need to convert it to an actual list to be able to modify it\n","print(nums)         # Prints \"[0, 1, 2, 3, 4]\"\n","print(f\"nums[2:4] = {nums[2:4]}\")    # Get a slice from index 2 to 4 (exclusive); prints \"[2, 3]\"\n","print(f\"nums[2:] = {nums[2:]}\")     # Get a slice from index 2 to the end; prints \"[2, 3, 4]\"\n","print(f\"nums[:2] = {nums[:2]}\")     # Get a slice from the start to index 2 (exclusive); prints \"[0, 1]\"\n","print(f\"nums[:] = {nums[:]}\")      # Get a slice of the whole list; prints [\"0, 1, 2, 3, 4]\"\n","print(f\"nums[:-1] = {nums[:-1]}\")    # Slice indices can be negative; prints [\"0, 1, 2, 3]\"\n","nums[2:4] = [8, 9] # Assign a new sublist to a slice\n","print(nums)         # Prints \"[0, 1, 8, 8, 4]\""]},{"cell_type":"markdown","metadata":{"id":"FBpZ2qUZsgT5"},"source":["#### Loops"]},{"cell_type":"markdown","metadata":{"id":"6ZO_RsF6sgT5"},"source":["You can loop over the elements of a list like this:"]},{"cell_type":"code","execution_count":24,"metadata":{"collapsed":true,"id":"GlnjoqLpsgT5","colab":{"base_uri":"https://localhost:8080/"},"outputId":"94baeca6-8ef6-4063-f3de-a04d10713ec1","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":21,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["cat\n","dog\n","monkey\n"]}],"source":["animals = ['cat', 'dog', 'monkey']\n","for animal in animals:\n","    print(animal)"]},{"cell_type":"markdown","metadata":{"id":"2W9gcFGYsgT5"},"source":["If you want access to the index of each element within the body of a loop, use the built-in `enumerate` function:"]},{"cell_type":"code","execution_count":25,"metadata":{"collapsed":true,"id":"8YOCz1_3sgT5","colab":{"base_uri":"https://localhost:8080/"},"outputId":"1ead4ad3-4520-4750-d7fa-ead06b01b73a","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":20,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["#1: cat\n","#2: dog\n","#3: monkey\n"]}],"source":["animals = ['cat', 'dog', 'monkey']\n","for idx, animal in enumerate(animals):\n","    print(f'#{idx+1}: {animal}')"]},{"cell_type":"markdown","metadata":{"id":"wh84gSTZsgT5"},"source":["#### List comprehensions:"]},{"cell_type":"markdown","metadata":{"id":"rwrxOr75sgT5"},"source":["When programming, frequently we want to transform one type of data into another. As a simple example, consider the following code that computes square numbers:"]},{"cell_type":"code","execution_count":26,"metadata":{"collapsed":true,"id":"pN9AQdx7sgT5","colab":{"base_uri":"https://localhost:8080/"},"outputId":"d16a1d1f-58b1-4199-998b-aa16a040ed3e","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":18,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 1, 4, 9, 16]\n"]}],"source":["nums = [0, 1, 2, 3, 4]\n","squares = []\n","for x in nums:\n","    squares.append(x ** 2)\n","print(squares)"]},{"cell_type":"markdown","metadata":{"id":"PTO2JMXasgT5"},"source":["You can make this code simpler using a list comprehension:"]},{"cell_type":"code","execution_count":27,"metadata":{"collapsed":true,"id":"J8ivuTADsgT5","colab":{"base_uri":"https://localhost:8080/"},"outputId":"12493e76-dfb6-42fc-c9b5-75c9442b37d2","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":17,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 1, 4, 9, 16]\n"]}],"source":["nums = [0, 1, 2, 3, 4]\n","squares = [x ** 2 for x in nums] #\n","print(squares)"]},{"cell_type":"markdown","metadata":{"id":"jWgZ1Fa3sgT5"},"source":["List comprehensions can also contain conditions:"]},{"cell_type":"code","execution_count":28,"metadata":{"collapsed":true,"id":"Y2vP9DrasgT5","colab":{"base_uri":"https://localhost:8080/"},"outputId":"3a7a0ee0-e465-4f8a-a5ed-7a4cdc86bd8c","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":17,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["[0, 4, 16]\n"]}],"source":["nums = [0, 1, 2, 3, 4]\n","even_squares = [x ** 2 for x in nums if x % 2 == 0]\n","print(even_squares)"]},{"cell_type":"markdown","metadata":{"id":"huKpG1OmsgT5"},"source":["Create a list with your favorite actors/actresses. Print the first two of them. Remove the third actor/actress from the list. Loop over the elements of the list and print one element at a time."]},{"cell_type":"code","execution_count":29,"metadata":{"collapsed":true,"id":"VraTNqCOsgT5","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":16,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# write your code here\n","\n","\n"]},{"cell_type":"markdown","metadata":{"id":"LCuQT351sgT5"},"source":["Create a list containing integers from $0$ to $10$. Use list comprehension to create a new list containing only the prime numbers of the initial list. Print the new list."]},{"cell_type":"code","execution_count":30,"metadata":{"collapsed":true,"id":"iFT_u-YBsgT5","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":16,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# write your code here\n","\n","\n"]},{"cell_type":"markdown","metadata":{"id":"0m07WnOvsgT6"},"source":["**The good programmer tip**:\n","Python list comprehension allow you to express really complicated logic. Writing one-liners is pretty great but it affects readability. Don't abuse! For more information about list comprehension check the [official documentation](https://docs.python.org/3.7/howto/functional.html?highlight=list%20comprehension#generator-expressions-and-list-comprehensions)."]},{"cell_type":"markdown","metadata":{"id":"s7fnqlkPsgT6"},"source":["#### Dictionaries"]},{"cell_type":"markdown","metadata":{"id":"ava7Y9d4sgT6"},"source":["A dictionary stores (key, value) pairs, similar to a `Map` in Java or an object in Javascript. You can use it like this:"]},{"cell_type":"code","execution_count":31,"metadata":{"collapsed":true,"id":"8yFakw8WsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"7f7a639a-45e7-4704-c7cc-05f7997f47a4","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":15,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["d['cat'] = cute\n","Is 'cat' in d? True\n"]}],"source":["d = {'cat': 'cute', 'dog': 'furry'}  # Create a new dictionary with some data\n","print(\"d['cat'] = {}\".format(d['cat']))       # Get an entry from a dictionary; prints \"cute\"\n","print(\"Is 'cat' in d? {}\".format('cat' in d))     # Check if a dictionary has a given key; prints \"True\""]},{"cell_type":"code","execution_count":32,"metadata":{"collapsed":true,"id":"LMjEwXZQsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"c3b2506b-9806-47b5-f594-bd149fbcb56f","executionInfo":{"status":"ok","timestamp":1732116789894,"user_tz":-60,"elapsed":15,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["wet\n"]}],"source":["d['fish'] = 'wet'    # Set an entry in a dictionary\n","print(d['fish'])      # Prints \"wet\""]},{"cell_type":"code","execution_count":33,"metadata":{"collapsed":true,"id":"x40KLO6rsgT6","colab":{"base_uri":"https://localhost:8080/","height":147},"outputId":"2799fceb-9f75-479f-f65e-7cb9575e280f","executionInfo":{"status":"error","timestamp":1732116789894,"user_tz":-60,"elapsed":13,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"error","ename":"KeyError","evalue":"'monkey'","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)","\u001b[0;32m<ipython-input-33-78fc9745d9cf>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0md\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'monkey'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# KeyError: 'monkey' not a key of d\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mKeyError\u001b[0m: 'monkey'"]}],"source":["print(d['monkey'])  # KeyError: 'monkey' not a key of d"]},{"cell_type":"code","execution_count":34,"metadata":{"collapsed":true,"id":"TU-911sEsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"74499e56-c7f6-410c-8c21-530c21213f13","executionInfo":{"status":"ok","timestamp":1732116800251,"user_tz":-60,"elapsed":287,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["N/A\n","wet\n"]}],"source":["print(d.get('monkey', 'N/A'))  # Get an element with a default; prints \"N/A\"\n","print(d.get('fish', 'N/A'))    # Get an element with a default; prints \"wet\""]},{"cell_type":"code","execution_count":35,"metadata":{"collapsed":true,"id":"Yo-QGo9YsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"9a7a5f6c-d901-4cdf-d4ba-01485fbdd464","executionInfo":{"status":"ok","timestamp":1732116800543,"user_tz":-60,"elapsed":22,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["N/A\n"]}],"source":["del d['fish']        # Remove an element from a dictionary\n","print(d.get('fish', 'N/A')) # \"fish\" is no longer a key; prints \"N/A\""]},{"cell_type":"markdown","metadata":{"id":"_C-4nMQosgT6"},"source":["You can find all you need to know about dictionaries in the [documentation](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict)."]},{"cell_type":"markdown","metadata":{"id":"D0BELHl8sgT6"},"source":["It is easy to iterate over the keys in a dictionary:"]},{"cell_type":"code","execution_count":36,"metadata":{"collapsed":true,"id":"AWiHpt-0sgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"b3797e52-8d8d-472f-a6fd-276f3f104982","executionInfo":{"status":"ok","timestamp":1732116800543,"user_tz":-60,"elapsed":19,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["A person has 2 legs\n","A cat has 4 legs\n","A spider has 8 legs\n"]}],"source":["d = {'person': 2, 'cat': 4, 'spider': 8}\n","for animal in d:\n","    legs = d[animal]\n","    print(f\"A {animal} has {legs} legs\")"]},{"cell_type":"markdown","metadata":{"id":"vTAMr3whsgT6"},"source":["If you want access to keys and their corresponding values, use the iteritems method:"]},{"cell_type":"code","execution_count":37,"metadata":{"collapsed":true,"id":"Yk5ZlOvlsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"61c11cad-9495-41f9-d4da-30953eee612c","executionInfo":{"status":"ok","timestamp":1732116800543,"user_tz":-60,"elapsed":15,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["A person has 2 legs\n","A cat has 4 legs\n","A spider has 8 legs\n"]}],"source":["d = {'person': 2, 'cat': 4, 'spider': 8}\n","for animal, legs in d.items():\n","    print(f\"A {animal} has {legs} legs\")"]},{"cell_type":"markdown","metadata":{"id":"yNvX-8r_sgT6"},"source":["Dictionary comprehensions: These are similar to list comprehensions, but allow you to easily construct dictionaries. For example:"]},{"cell_type":"code","execution_count":38,"metadata":{"collapsed":true,"id":"NL93tYlDsgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"bae4103f-d91b-4481-ad5f-50bf38a47a0b","executionInfo":{"status":"ok","timestamp":1732116800543,"user_tz":-60,"elapsed":12,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["{0: 0, 2: 4, 4: 16}\n"]}],"source":["nums = [0, 1, 2, 3, 4]\n","even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}\n","print(even_num_to_square)"]},{"cell_type":"markdown","metadata":{"id":"m3cEHm0gsgT6"},"source":["#### Sets"]},{"cell_type":"markdown","metadata":{"id":"FTJLBsRcsgT6"},"source":["A set is an _unordered_ collection of _distinct_ elements. As a simple example, consider the following:"]},{"cell_type":"code","execution_count":39,"metadata":{"collapsed":true,"id":"Ve-21f32sgT6","colab":{"base_uri":"https://localhost:8080/"},"outputId":"15dd5238-b7ab-4498-8cd5-8224c80d0216","executionInfo":{"status":"ok","timestamp":1732116800544,"user_tz":-60,"elapsed":11,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["True\n","False\n"]}],"source":["animals = {'cat', 'dog'}\n","print('cat' in animals)   # Check if an element is in a set; prints \"True\"\n","print('fish' in animals)  # prints \"False\"\n"]},{"cell_type":"code","execution_count":40,"metadata":{"collapsed":true,"id":"WcI37yIgsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"b9764fd2-3d55-48d7-e3d9-fa0c278b09fd","executionInfo":{"status":"ok","timestamp":1732116800544,"user_tz":-60,"elapsed":8,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Is 'fish' contained in animals? True\n","# animals: 3\n"]}],"source":["animals.add('fish')      # Add an element to a set\n","print(\"Is 'fish' contained in animals? {}\".format('fish' in animals))\n","print(f\"# animals: {len(animals)}\")       # Number of elements in a set;"]},{"cell_type":"code","execution_count":41,"metadata":{"collapsed":true,"id":"2GcP4M0tsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"1bf8b500-7330-4cbc-dd39-6bcaf9946d46","executionInfo":{"status":"ok","timestamp":1732116800544,"user_tz":-60,"elapsed":6,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["# animals = 3\n","# animals = 2\n"]}],"source":["animals.add('cat')       # Adding an element that is already in the set does nothing\n","print(\"# animals = {}\".format(len(animals)))\n","animals.remove('cat')    # Remove an element from a set\n","print(\"# animals = {}\".format(len(animals)))"]},{"cell_type":"markdown","metadata":{"id":"Eg3a7QlQsgT7"},"source":["_Loops_: Iterating over a set has the same syntax as iterating over a list; however since sets are unordered, you cannot make assumptions about the order in which you visit the elements of the set:"]},{"cell_type":"code","execution_count":42,"metadata":{"collapsed":true,"id":"wM-GiWOfsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"29213fb9-59dd-4b46-dd60-510bafdfa08c","executionInfo":{"status":"ok","timestamp":1732116800845,"user_tz":-60,"elapsed":305,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["#1: cat\n","#2: dog\n","#3: fish\n"]}],"source":["animals = {'cat', 'dog', 'fish'}\n","for idx, animal in enumerate(animals):\n","    print(\"#{}: {}\".format(idx + 1, animal))\n","# Prints \"#1: fish\", \"#2: dog\", \"#3: cat\""]},{"cell_type":"markdown","metadata":{"id":"liCJSWjosgT7"},"source":["Set comprehensions: Like lists and dictionaries, we can easily construct sets using set comprehensions:"]},{"cell_type":"code","execution_count":43,"metadata":{"collapsed":true,"id":"rOlzSYfpsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"8abc0f51-18e6-4a4b-a433-db8e0e664894","executionInfo":{"status":"ok","timestamp":1732116800845,"user_tz":-60,"elapsed":12,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["{0, 1, 2, 3, 4, 5}\n"]}],"source":["from math import sqrt\n","print({int(sqrt(x)) for x in range(30)})"]},{"cell_type":"markdown","metadata":{"id":"7KcqQaiRsgT7"},"source":["#### Tuples"]},{"cell_type":"markdown","metadata":{"id":"W1rvQ1yNsgT7"},"source":["A tuple is an *immutable ordered* list of values. A tuple is in many ways similar to a list; one of the most important differences is that tuples can be used as keys in dictionaries and as elements of sets, while lists cannot. Here is a trivial example:"]},{"cell_type":"code","execution_count":44,"metadata":{"collapsed":true,"id":"9VM-tWhjsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"dbf214e8-6d18-4345-9d3e-44cc1a2b7ac2","executionInfo":{"status":"ok","timestamp":1732116800845,"user_tz":-60,"elapsed":10,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["type(t) = <class 'tuple'>\n","d[t] = 5\n","d[(1, 2)] = 1\n"]}],"source":["d = {(x, x + 1): x for x in range(10)}  # Create a dictionary with tuple keys\n","t = (5, 6)       # Create a tuple\n","print(\"type(t) = {}\".format(type(t)))\n","print(\"d[t] = {}\".format(d[t]))\n","print(\"d[(1, 2)] = {}\".format(d[(1, 2)]))"]},{"cell_type":"code","execution_count":45,"metadata":{"collapsed":true,"id":"CuQeEuPrsgT7","colab":{"base_uri":"https://localhost:8080/","height":147},"outputId":"07e3f20d-6eb7-45e5-ba4e-f7160e3b9d83","executionInfo":{"status":"error","timestamp":1732116800845,"user_tz":-60,"elapsed":9,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"error","ename":"TypeError","evalue":"'tuple' object does not support item assignment","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)","\u001b[0;32m<ipython-input-45-6df8a3807d95>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mt\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m1\u001b[0m \u001b[0;31m# tuples are immutable, they cannot be modified. We will get a TypeError in this case\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"]}],"source":["t[0] = 1 # tuples are immutable, they cannot be modified. We will get a TypeError in this case"]},{"cell_type":"markdown","metadata":{"id":"c_v2REkIsgT7"},"source":["### Functions"]},{"cell_type":"markdown","metadata":{"id":"D7du0ErUsgT7"},"source":["Python functions are defined using the `def` keyword. For example:"]},{"cell_type":"code","execution_count":46,"metadata":{"collapsed":true,"id":"dWUCJ5d9sgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"b93495c0-f46c-4ef6-e7b3-c5c4fe1077bb","executionInfo":{"status":"ok","timestamp":1732116807038,"user_tz":-60,"elapsed":270,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["negative\n","zero\n","positive\n"]}],"source":["def sign(x):\n","    if x > 0:\n","        return 'positive'\n","    elif x < 0:\n","        return 'negative'\n","    else:\n","        return 'zero'\n","\n","for x in [-1, 0, 1]:\n","    print(sign(x))"]},{"cell_type":"markdown","metadata":{"id":"iU3LsPOJsgT7"},"source":["We will often define functions to take optional keyword arguments, like this:"]},{"cell_type":"code","execution_count":47,"metadata":{"collapsed":true,"id":"vaxwPORdsgT7","colab":{"base_uri":"https://localhost:8080/"},"outputId":"b54fd8e4-5e3f-475f-ec3c-8411dd5f8d2a","executionInfo":{"status":"ok","timestamp":1732116807342,"user_tz":-60,"elapsed":9,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Hello, Bob!\n","HELLO, FRED\n"]}],"source":["def hello(name, loud=False):\n","    if loud:\n","        print('HELLO, {}'.format(name.upper()))\n","    else:\n","        print('Hello, {}!'.format(name))\n","\n","hello('Bob')\n","hello('Fred', loud=True)"]},{"cell_type":"markdown","metadata":{"id":"8u2AoW6_sgT7"},"source":["### Classes"]},{"cell_type":"markdown","metadata":{"id":"VRChzy4KsgT7"},"source":["The syntax for defining classes in Python is straightforward:"]},{"cell_type":"code","execution_count":48,"metadata":{"collapsed":true,"id":"gZQk1gTqsgT8","colab":{"base_uri":"https://localhost:8080/"},"outputId":"ad4de465-d6bf-448c-d896-9a25a5fb5e05","executionInfo":{"status":"ok","timestamp":1732116807342,"user_tz":-60,"elapsed":8,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[{"output_type":"stream","name":"stdout","text":["Hello, Fred\n","HELLO, FRED!\n"]}],"source":["class Greeter:\n","\n","    # Constructor\n","    def __init__(self, name):\n","        self.name = name\n","        # Create an instance variable\n","\n","    # Instance method\n","    def greet(self, loud=False):\n","        if loud:\n","            print ('HELLO, {}!'.format(self.name.upper()))\n","        else:\n","            print ('Hello, {}'.format(self.name))\n","\n","g = Greeter('Fred')  # Construct an instance of the Greeter class\n","g.greet()             # Call an instance method; prints \"Hello, Fred\"\n","g.greet(loud=True)   # Call an instance method; prints \"HELLO, FRED!\""]},{"cell_type":"code","source":[],"metadata":{"id":"tEivU-PeMG1W","executionInfo":{"status":"ok","timestamp":1732116807342,"user_tz":-60,"elapsed":6,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"execution_count":48,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"iF_nQwCZJO2Z"},"source":["### Exercises"]},{"cell_type":"markdown","metadata":{"id":"rCDABzPTJO2Z"},"source":["Using list comprehension, create a list that contains only the odd numbers of the original list. You can do this with a single line of code."]},{"cell_type":"code","metadata":{"id":"GFaRMnBjJO2a"},"source":["even_odd = [5, 7, 11, 3, 2, 6, 1, 9, 8, 4, 10, 12]\n","\n","odd = [x for ... ]\n","print(odd)"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"IwMM8sv9JO2d"},"source":["Write a function that keeps only the unique numbers in the given list (that is, no number is repeated). Hint: the opposite of \"in\" is \"not in\"."]},{"cell_type":"code","metadata":{"id":"EFjzJrw3JO2e","executionInfo":{"status":"aborted","timestamp":1732116807342,"user_tz":-60,"elapsed":4,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"source":["rnd_list = [8, 9, 1, 3, 5, 2, 10, 6, 4, 7, 1, 8, 5, 3, 7, 2, 9, 6, 10, 4]\n","\n","def unique_in_list(random_list):\n","    temp = []\n","    ...\n","    return temp\n","\n","unique = unique_in_list(rnd_list)\n","print(unique)"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"collapsed":true,"id":"i1wkSOgesgUA"},"source":["## Basic I/O"]},{"cell_type":"markdown","metadata":{"id":"mCDbmI80sgUA"},"source":["Reading and writing files in python is easy"]},{"cell_type":"code","execution_count":52,"metadata":{"collapsed":true,"id":"aTqI8lXFsgUA","executionInfo":{"status":"ok","timestamp":1732116860267,"user_tz":-60,"elapsed":282,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# you need to create a file called 'test_file.txt' first otherwise the following instruction will fail\n","with open('test_file.txt', 'r') as fp:\n","    # we don't need to explicitly close the file. the 'with' operator will take care of it\n","    for line in fp:\n","        print(line.strip())\n"]},{"cell_type":"code","execution_count":53,"metadata":{"collapsed":true,"id":"avQ7q0bWsgUA","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116861481,"user_tz":-60,"elapsed":273,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"1b70049d-7aef-4028-9929-652723576e69"},"outputs":[{"output_type":"stream","name":"stdout","text":["[]\n"]}],"source":["# alternative\n","with open('test_file.txt', 'r') as fp:\n","    lines = fp.readlines()\n","    print(lines)"]},{"cell_type":"code","execution_count":54,"metadata":{"collapsed":true,"id":"x8QUo5hxsgUA","executionInfo":{"status":"ok","timestamp":1732116862934,"user_tz":-60,"elapsed":269,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# OLD\n","# 2nd alternative\n","#f = open('test_file.txt', 'r')\n","#lines =f.readlines()\n","#for line in lines:\n","#    print line.strip()\n","#f.close()\n","\n","with open('test_file.txt', 'r') as f:\n","    lines = f.readlines()\n","    for line in lines:\n","        print(line.strip())"]},{"cell_type":"code","execution_count":55,"metadata":{"collapsed":true,"id":"zYMh9w2FsgUA","executionInfo":{"status":"ok","timestamp":1732116864781,"user_tz":-60,"elapsed":253,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}}},"outputs":[],"source":["# OLD\n","# write to file\n","# f = open('test_file.txt', 'a')\n","# f.write(\"\\nNew Line\")\n","# f.close()\n","\n","# writes to the same file and appends new content to it\n","with open('test_file.txt', 'a') as out_file:\n","    out_file.write(\"\\nNew Line\")"]},{"cell_type":"markdown","metadata":{"id":"Ndv2Jj2psgUB"},"source":["## Handling Exceptions\n","\n","Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called *exceptions* and are not unconditionally fatal: you will soon learn how to handle them in Python programs. For more details please refer to the [documentation](https://docs.python.org/3/tutorial/errors.html)."]},{"cell_type":"code","execution_count":60,"metadata":{"collapsed":true,"id":"Jtnq0RDdsgUB","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116885205,"user_tz":-60,"elapsed":406,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"9d902ca5-7eee-4a8d-d23b-cf74fe894337"},"outputs":[{"output_type":"stream","name":"stdout","text":["{0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thurdsay', 4: 'Friday', 5: 'Saturday'}\n"]}],"source":["days = {0 : \"Monday\", 1: \"Tuesday\", 2: \"Wednesday\", 3: \"Thurdsay\", 4: \"Friday\", 5: \"Saturday\"}\n","print(days)"]},{"cell_type":"code","execution_count":61,"metadata":{"collapsed":true,"id":"h9sOr22lsgUB","colab":{"base_uri":"https://localhost:8080/","height":35},"executionInfo":{"status":"ok","timestamp":1732116886163,"user_tz":-60,"elapsed":7,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"2da62886-2ade-4413-e174-04628154948f"},"outputs":[{"output_type":"execute_result","data":{"text/plain":["'Monday'"],"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"}},"metadata":{},"execution_count":61}],"source":["days[0]"]},{"cell_type":"code","execution_count":62,"metadata":{"collapsed":true,"id":"v9ClyLGDsgUB","colab":{"base_uri":"https://localhost:8080/","height":147},"executionInfo":{"status":"error","timestamp":1732116887090,"user_tz":-60,"elapsed":7,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"221fb6b3-d02d-4c57-b6b7-43e1f28ef27b"},"outputs":[{"output_type":"error","ename":"KeyError","evalue":"6","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)","\u001b[0;32m<ipython-input-62-e94948a16592>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mdays\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mKeyError\u001b[0m: 6"]}],"source":["days[6]"]},{"cell_type":"code","execution_count":67,"metadata":{"collapsed":true,"id":"SCK7IX1ZsgUB","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116922132,"user_tz":-60,"elapsed":272,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"cc43d331-9426-4120-dfa5-b650b9b33048"},"outputs":[{"output_type":"stream","name":"stdout","text":["Sunday\n"]}],"source":["try:\n","    print(days[6])\n","except KeyError:\n","    print(\"Sunday\")"]},{"cell_type":"code","execution_count":68,"metadata":{"collapsed":true,"id":"NGOpfWPzsgUB","colab":{"base_uri":"https://localhost:8080/","height":202},"executionInfo":{"status":"error","timestamp":1732116922962,"user_tz":-60,"elapsed":7,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"1cdea51e-9a29-4b51-829c-2d431a1e6ae7"},"outputs":[{"output_type":"stream","name":"stdout","text":["range(0, 10)\n"]},{"output_type":"error","ename":"IndexError","evalue":"range object index out of range","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mIndexError\u001b[0m                                Traceback (most recent call last)","\u001b[0;32m<ipython-input-68-8dfcd02f9c69>\u001b[0m in \u001b[0;36m<cell line: 3>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mIndexError\u001b[0m: range object index out of range"]}],"source":["a = range(10)\n","print(a)\n","print(a[10])"]},{"cell_type":"code","execution_count":69,"metadata":{"collapsed":true,"id":"9QItDdMJsgUB","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1732116936401,"user_tz":-60,"elapsed":261,"user":{"displayName":"Beatrice Portelli","userId":"14323252246116225690"}},"outputId":"8b4c201c-7142-4752-80e1-6e6c13fde9ea"},"outputs":[{"output_type":"stream","name":"stdout","text":["10\n"]}],"source":["try:\n","    a[10]\n","except IndexError:\n","    print(10)"]},{"cell_type":"code","source":[],"metadata":{"id":"mztUtErnNvRM"},"execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.3"},"colab":{"provenance":[],"collapsed_sections":["S4RmF6QAsgT0","wh84gSTZsgT5"],"toc_visible":true}},"nbformat":4,"nbformat_minor":0}