{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "W1_S2_Tutorial.ipynb",
"provenance": [],
"toc_visible": true,
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"
"
]
},
{
"cell_type": "markdown",
"source": [
"# Data Structure, Functions, and Classes\n",
"\n",
"In this notebook, we will be discovering how data is stored in Python. We will cover:\n",
"\n",
"1. Lists\n",
"2. Tuples\n",
"3. Dictionaries\n",
"\n",
"Reference:\n",
"* IBM Congnitive Class - Intro to Python (https://github.com/computationalcore/introduction-to-python)\n",
"* CUSP UCSL bootcamp 2017 (https://github.com/Mohitsharma44/ucsl17)"
],
"metadata": {
"id": "As6EA_JX91Ue"
}
},
{
"cell_type": "markdown",
"source": [
"## **Lists**\n",
"Creating lists is very easy in Python. We can create lists by separating different items with commas in square brackets:\\\n",
"`[Item1,Item2,Item3]`\n",
"\n",
"There are many different ways to interact with lists. Exploring them is part of the fun of Python.\n",
"\n",
"**list.append(x)** Add an item to the end of the list. Equivalent to `a[len(a):] = [x]`.\n",
"\n",
"**list.extend(L)** Extend the list by appending all the items in the given list. Equivalent to `a[len(a):] = L`.\n",
"\n",
"**list.insert(i, x)** Insert an item at a given position. The first argument is\n",
"the index of the element before which to insert, so `a.insert(0, x)` inserts\n",
"at the front of the list, and `a.insert(len(a), x)` is equivalent to\n",
"`a.append(x)`.\n",
"\n",
"**list.remove(x)** Remove the first item from the list whose value is x. It is an error if there is no such item.\n",
"\n",
"**list.pop([i])** Remove the item at the given position in the list, and return it.\n",
"If no index is specified, `a.pop()` removes and returns the last item in the list.\n",
"(The square brackets around the i in the method signature denote that the\n",
" parameter is optional, not that you should type square brackets at that\n",
" position. You will see this notation frequently in the Python Library Reference.)\n",
"\n",
"**list.clear()** Remove all items from the list. Equivalent to `del a[:]`.\n",
"\n",
"**list.index(x)** Return the index in the list of the first item whose value is x.\n",
"It is an error if there is no such item.\n",
"\n",
"**list.count(x)** Return the number of times x appears in the list.\n",
"\n",
"**list.sort()** Sort the items of the list in place.\n",
"\n",
"**list.reverse()** Reverse the elements of the list in place.\n",
"\n",
"**list.copy()** Return a shallow copy of the list. Equivalent to `a[:]`."
],
"metadata": {
"id": "CzbcuCye96oD"
}
},
{
"cell_type": "code",
"source": [
"# Let's experiment with some of these methods!\n",
"# 1. Create a list first\n",
"l = ['dog', 'cat', 'fish','chicken','eggs','duck']\n",
"type(l)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "D7hU4VTd98ni",
"outputId": "79bcc55d-7bb8-47f6-f147-c0d147c9841c"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"list"
]
},
"metadata": {},
"execution_count": 1
}
]
},
{
"cell_type": "code",
"source": [
"# Slicing the list\n",
"print(l[0],l[-1],l[0:3],l[-3:-1])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ktyeLG7Z927-",
"outputId": "6460253b-b572-4dc0-a487-c654267b0283"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"dog duck ['dog', 'cat', 'fish'] ['chicken', 'eggs']\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Consider memorizing this syntax!**\n",
"It is central to so much of Python and often proves confusing for users coming from other languages."
],
"metadata": {
"id": "GLjJPEh59-aj"
}
},
{
"cell_type": "markdown",
"source": [
"#### **Updating list**\n",
"Unlike strings and tuples, lists are mutable. You can update the list and change the items whenever you want."
],
"metadata": {
"id": "gdeI3-vu-DHd"
}
},
{
"cell_type": "code",
"source": [
"my_list = ['dog', 'cat', 'fish','chicken','eggs','duck']\n",
"my_list[2] = 'Tree'\n",
"print('Original Contents: \\n', my_list)\n",
"print('Original Length of array: \\n', len(my_list))\n",
"\n",
"# Remove some elements/ changing the size\n",
"my_list[2:4] = []\n",
"print('Modified Contents: \\n', my_list)\n",
"print('Modified Length of array: \\n', len(my_list))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "yAkzz4d1-AVO",
"outputId": "e75c417d-5321-459c-a6c6-74459b7dd89c"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Original Contents: \n",
" ['dog', 'cat', 'Tree', 'chicken', 'eggs', 'duck']\n",
"Original Length of array: \n",
" 6\n",
"Modified Contents: \n",
" ['dog', 'cat', 'eggs', 'duck']\n",
"Modified Length of array: \n",
" 4\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Let modify the list with some list specific methods we have discussed earlier"
],
"metadata": {
"id": "yHVTz0Dj_GGF"
}
},
{
"cell_type": "code",
"source": [
"#@title #### **Add new items to list**\n",
"my_list = ['dog', 'cat', 'fish','chicken','eggs','duck']\n",
"my_list.append('Python') # It will append the item to the end of the list\n",
"print(my_list)\n",
"my_list.insert(0, 'Julia')\n",
"print(my_list)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "4oWAQmg2-GA9",
"outputId": "e2af3d1d-2d84-46fb-d6ca-a48df18d7993"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['dog', 'cat', 'fish', 'chicken', 'eggs', 'duck', 'Python']\n",
"['Julia', 'dog', 'cat', 'fish', 'chicken', 'eggs', 'duck', 'Python']\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Remove list items**\n",
"my_list.pop(0)\n",
"print(my_list)\n",
"del(my_list[-1])\n",
"print(my_list)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "0YkFz9AI_LEG",
"outputId": "ca5012be-ced9-4ee1-a560-6f75a46c8004"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['dog', 'cat', 'fish', 'chicken', 'eggs', 'duck', 'Python']\n",
"['dog', 'cat', 'fish', 'chicken', 'eggs', 'duck']\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Count, Index**\n",
"print(my_list.count('fish'))\n",
"print(my_list.index('duck'))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "T-Y-PmwF_MUQ",
"outputId": "ddc1d28c-fdbc-4b74-94f2-9327f4a8f224"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1\n",
"5\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Sort, Reverse**\n",
"my_list = ['dog', 'cat', 'fish','chicken','eggs','duck']\n",
"my_list.reverse()\n",
"print(my_list)\n",
"my_list.sort()\n",
"print(my_list)\n",
"my_list.sort(reverse=True)\n",
"print(my_list)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "-mUrFOuA_N2S",
"outputId": "fd172054-ec70-44e2-e202-cb60ac818e05"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['duck', 'eggs', 'chicken', 'fish', 'cat', 'dog']\n",
"['cat', 'chicken', 'dog', 'duck', 'eggs', 'fish']\n",
"['fish', 'eggs', 'duck', 'dog', 'chicken', 'cat']\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **List Concatenation**\n",
"my_list = ['dog', 'cat', 'fish','chicken','eggs','duck']\n",
"my_list2 = ['Python','Julia','C++']\n",
"print(my_list+my_list2)\n",
"my_list.extend(my_list2)\n",
"print(my_list)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Y5iyUrwW_Qub",
"outputId": "353f0efc-a673-4bf9-984e-9d33a91d0eea"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['dog', 'cat', 'fish', 'chicken', 'eggs', 'duck', 'Python', 'Julia', 'C++']\n",
"['dog', 'cat', 'fish', 'chicken', 'eggs', 'duck', 'Python', 'Julia', 'C++']\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"#### **Use lists in loops**"
],
"metadata": {
"id": "iEuE6l38_TDj"
}
},
{
"cell_type": "code",
"source": [
"for index in range(len(my_list)): # start from 0 and go till the length of the list.\n",
" print(\"my_list[{}] : {}\".format(index, my_list[index]))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "DuGwy4v0_adM",
"outputId": "8c5ae2e6-5b2d-40a5-bcf5-a35e66181db9"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"my_list[0] : dog\n",
"my_list[1] : cat\n",
"my_list[2] : fish\n",
"my_list[3] : chicken\n",
"my_list[4] : eggs\n",
"my_list[5] : duck\n",
"my_list[6] : Python\n",
"my_list[7] : Julia\n",
"my_list[8] : C++\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# We can actually do the same thing with enumerate()\n",
"for index,items in enumerate(my_list):\n",
" print(\"my_list[{}] : {}\".format(index,items))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "6FBpPecA_d-0",
"outputId": "c236b7dd-e4b8-4794-bab7-da656564f38a"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"my_list[0] : dog\n",
"my_list[1] : cat\n",
"my_list[2] : fish\n",
"my_list[3] : chicken\n",
"my_list[4] : eggs\n",
"my_list[5] : duck\n",
"my_list[6] : Python\n",
"my_list[7] : Julia\n",
"my_list[8] : C++\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**List Comprehension**\n",
"\n",
"List comprehension is a syntactic way of creating a list based on the existing list, just like we did when copying the lists above. The basic structure of the syntax includes a for loop that traverses the list and evaluates a condition using the if.. else condition. It then stores the output of the condition as a new list. Let's take a look at a quick example:"
],
"metadata": {
"id": "X7mxdvzL_swr"
}
},
{
"cell_type": "code",
"source": [
"my_list1 = [elem for index,elem in enumerate(my_list) if index % 2 == 0]\n",
"print(my_list1)\n",
"\n",
"squares = [n**2 for n in range(5)]\n",
"print(squares)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "Lpg1hilm_gZm",
"outputId": "679e92d5-b378-46c8-e8e7-607948cecbf3"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['dog', 'fish', 'eggs', 'Python', 'C++']\n",
"[0, 1, 4, 9, 16]\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**Traverse two lists together with `zip()`**"
],
"metadata": {
"id": "JeZ4qEmv_ZdH"
}
},
{
"cell_type": "code",
"source": [
"# iterate over two lists together uzing zip\n",
"for item1, item2 in zip(['pig','duck','butterfly'],[0,1,2]):\n",
" print('first:', item1, 'second:', item2)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "OXc3dNzA_ztj",
"outputId": "acc36254-7c41-4be3-ad9c-a7026ee2f105"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"first: pig second: 0\n",
"first: duck second: 1\n",
"first: butterfly second: 2\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## **Tuples**\n",
"Tuples are similar to lists, but they are *immutable*—they can’t be extended or modified. What is the point of this? Generally speaking: to pack together inhomogeneous data. Tuples can then be unpacked and distributed by other parts of your code.\n",
"\n",
"Tuples may seem confusing at first, but with time you will come to appreciate them."
],
"metadata": {
"id": "Gwkq2ppUAeiw"
}
},
{
"cell_type": "code",
"source": [
"# tuples are created with parentheses, or just commas\n",
"a = ('Ryan', 33, True)\n",
"b = 'Takaya', 25, False\n",
"type(b)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "s2DOjqpjAfbE",
"outputId": "1217ae37-ee6e-4054-d4e1-71a4e44d3ec5"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"tuple"
]
},
"metadata": {},
"execution_count": 14
}
]
},
{
"cell_type": "code",
"source": [
"# can be indexed like arrays\n",
"print(a[1]) # not the first element!"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "JFllK1E2Ahed",
"outputId": "b41e7805-dcd0-4b07-8c24-96d33831db4f"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"33\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# and they can be unpacked\n",
"name, age, status = a\n",
"print(name,age,status)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "KRV2yk6TAjzj",
"outputId": "835d0b18-6d9a-4f2e-f702-9e74064c92bf"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Ryan 33 True\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"print(a.index('Ryan'))"
],
"metadata": {
"id": "w3QMVyLvAlhC"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## **Dictionaries**\n",
"This is an extremely useful data structure. It maps **keys** to **values**.\n",
"\n",
"Dictionaries are unordered!"
],
"metadata": {
"id": "wlCgfXt7Am59"
}
},
{
"cell_type": "code",
"source": [
"#@title #### **Different ways to create dictionaries**\n",
"d = {'name': 'Timothee', 'age': 1} # Write your name and your age here\n",
"e = dict(name='Timothee', age=1) # Write someone else's name and their age here"
],
"metadata": {
"id": "165sS3z5A4CD"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#@title #### **Access Dictionary Items**\n",
"print(d['name'])\n",
"print(\"name: \", d.get('name' , 'Not Found'))\n",
"print(\"gender: \", d.get('gender', 'Not Found'))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "T94QBiI3A734",
"outputId": "63a691b1-23c5-4ad1-a46f-865771101cba"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Timothee\n",
"name: Timothee\n",
"gender: Not Found\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Updating Dictionary**\n",
"# Add a new variable-value pair:\n",
"d['height'] = (1,50) # a tuple, e.g. your height in (meters,centimeters)\n",
"d"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "I_XHDwZiA9Pa",
"outputId": "961e1d48-3c40-4971-ec75-090982564ddf"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"{'name': 'Timothee', 'age': 1, 'height': (1, 50)}"
]
},
"metadata": {},
"execution_count": 19
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Append Dictionary**\n",
"# update() add two dictionary together\n",
"newdict = dict(location='Lausanne',nationality='CH',birth_year='2021')\n",
"d.update(newdict)\n",
"print(d)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "rqIhYfWBA-ar",
"outputId": "5239fe5c-5477-4280-a72c-f4757144d683"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"{'name': 'Timothee', 'age': 1, 'height': (1, 50), 'location': 'Lausanne', 'nationality': 'CH', 'birth_year': '2021'}\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Remove Elements from Dictionary**\n",
"# pop(),del()\n",
"d2 = d.copy()\n",
"d2.pop('age')\n",
"del d['age']\n",
"print(f\"Identical? {d==d2}\")"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "v_1gPA7jA_qB",
"outputId": "c871d444-7081-4d2e-de2b-c0ded18e47d5"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Identical? True\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Traverse Dictionary**\n",
"# iterate over keys\n",
"for k in d:\n",
" print(k, d[k])"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "XLZvTWWFBFKd",
"outputId": "967b5a23-77e1-4ab2-b6ae-ea6be5c58d70"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"name Timothee\n",
"height (1, 50)\n",
"location Lausanne\n",
"nationality CH\n",
"birth_year 2021\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"# better way\n",
"for key, val in d.items():\n",
" print(key, val)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "oR4Wt1faBGen",
"outputId": "a9e3bcea-1672-4e11-be51-522aefef49d9"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"name Timothee\n",
"height (1, 50)\n",
"location Lausanne\n",
"nationality CH\n",
"birth_year 2021\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"print(list(d.keys()))\n",
"print(list(d.values()))\n",
"print(list(d.items()))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "ZvXtIujQBH5N",
"outputId": "676bce08-7053-4b12-fd98-ff028ae8d661"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['name', 'height', 'location', 'nationality', 'birth_year']\n",
"['Timothee', (1, 50), 'Lausanne', 'CH', '2021']\n",
"[('name', 'Timothee'), ('height', (1, 50)), ('location', 'Lausanne'), ('nationality', 'CH'), ('birth_year', '2021')]\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"#@title #### **Sort Dictionary**\n",
"# sorted()\n",
"states_dict = {'AL': 'Alabama', 'CA': 'California',\n",
" 'NJ': 'New Jersey', 'NY': 'New York'}\n",
"sorted_keys = sorted(list(states_dict.keys()), reverse=False)\n",
"for key in sorted_keys:\n",
" print('{} : {}'.format(key, states_dict[key]))"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "xA9cTpBrBJiH",
"outputId": "9ee837be-c9d3-420b-a57e-c1fa4b3163d1"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"AL : Alabama\n",
"CA : California\n",
"NJ : New Jersey\n",
"NY : New York\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"## **Functions and Classes**\n",
"For longer and more complex tasks, it is important to organize your code into reuseable elements. For example, if you find yourself cutting and pasting the same or similar lines of code over and over, you probably need to define a *function* to encapsulate that code and make it reusable. An important principle in programming in **DRY**: “don’t repeat yourself”. Repetition is tedious and opens you up to errors. Strive for elegance and simplicity in your programs.\n",
"\n",
"We can use the following two things to organize our code:\n",
"\n",
"1. Functions\n",
"2. Classes\n",
"\n",
"Reference:\n",
"* IBM Congnitive Class - Intro to Python (https://github.com/computationalcore/introduction-to-python)\n",
"* CUSP UCSL bootcamp 2017 (https://github.com/Mohitsharma44/ucsl17)\n",
"* Introduction to Python (Ryan Abernathy; https://rabernat.github.io/research_computing/intro-to-python.html)"
],
"metadata": {
"id": "hrRHXOpMBzwQ"
}
},
{
"cell_type": "markdown",
"source": [
"### **Functions**\n",
"Functions are a central part of advanced python programming. Functions take some inputs (“arguments”) and do something in response. Usually functions return something, but not always."
],
"metadata": {
"id": "1nCJwF_EB5jT"
}
},
{
"cell_type": "code",
"source": [
"#@title **Define a Function**\n",
"def say_hello():\n",
" \"\"\"Return the word hello.\"\"\"\n",
" return 'Hello'\n",
"\n",
"def say_hello_to(name=None):\n",
" \"\"\"\n",
" Return the word hello to someone\n",
" \"\"\"\n",
" return 'Hello, '+str(name)\n",
"\n",
"# take an optional keyword argument\n",
"def say_hello_or_hola(name, french=False):\n",
" \"\"\"Say hello in multiple languages.\"\"\"\n",
" if french:\n",
" greeting = 'Bonjour '\n",
" else:\n",
" greeting = 'Hello '\n",
" return greeting + name\n",
"\n",
"# flexible number of arguments\n",
"def say_hello_to_everyone(*args):\n",
" return ['Bonjour ' + str(a) for a in args]"
],
"metadata": {
"id": "QDxK4lbAB0tJ"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"print(say_hello())\n",
"res = say_hello()\n",
"print(res)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "lc7m5iPKB28A",
"outputId": "72d0038f-6785-4962-f64d-c3db881fcf87"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello\n",
"Hello\n"
]
}
]
},
{
"cell_type": "code",
"source": [
"print(say_hello_or_hola('Frédéric', french=True)) # Greet the rector\n",
"print(say_hello_or_hola('Frédéric', french=False))\n",
"print(say_hello_to_everyone('Niklas', 'Valérie', 'Marie-Élodie')) # Greet the deans"
],
"metadata": {
"id": "3mYjOk7QB_km"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#@title **Anonymous Function**\n",
"mul = lambda a, b: a*b\n",
"print(mul(4,5))"
],
"metadata": {
"id": "4AgbvjCUCGOh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#@title **Map Function**\n",
"# syntax: map(function,iterator)\n",
"numbers = range(1, 10)\n",
"def square(num):\n",
" return num**2\n",
"list(map(square, numbers))\n",
"# The equivalent of this function is:\n",
"# result = []\n",
"# for i in range(1, 10):\n",
"# result.append(i**2)"
],
"metadata": {
"id": "vJBzGbhBCKMp"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# We can also write this in a single line!\n",
"list(map(lambda x: x**2, range(1, 10)))"
],
"metadata": {
"id": "Y7wsf8UACMZl"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Return all values for which %2 is non zero.. (List of all odd numbers, right?)\n",
"list(filter(lambda x: x%2, range(1, 10)))"
],
"metadata": {
"id": "DTNuq98dCNqj"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### **Pure vs Impure Functions**\n",
"Functions that don’t modify their arguments or produce any other side-effects are called *pure*.\n",
"\n",
"Functions that modify their arguments or cause other actions to occur are"
],
"metadata": {
"id": "uDf3R29HCSIx"
}
},
{
"cell_type": "code",
"source": [
"# Impure Functions\n",
"def remove_last_from_list(input_list):\n",
" input_list.pop()\n",
"names = ['Niklas', 'Valérie', 'Marie-Élodie']\n",
"remove_last_from_list(names)\n",
"print(names)\n",
"remove_last_from_list(names)\n",
"print(names)"
],
"metadata": {
"id": "ZFXukQonCSuA"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"#We can do something similar with a pure function. In general, pure functions are safer and more reliable.\n",
"def remove_last_from_list_pure(input_list):\n",
" new_list = input_list.copy()\n",
" new_list.pop()\n",
" return new_list\n",
"\n",
"names = ['Niklas', 'Valérie', 'Marie-Élodie']\n",
"new_names = remove_last_from_list_pure(names)\n",
"print(names)\n",
"print(new_names)"
],
"metadata": {
"id": "rWgib83NCVU9"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### **Namespace**\n",
"In python, a namespace is a mapping between variable names and python object. You can think of it like a dictionary.\n",
"The namespace can change depending on where you are in your program. Functions can “see” the variables in the parent namespace, but they can also redefine them in a private scope.\n",
"\n",
"It's important that you be aware of the name spaces in your code, specially when dealing with mutable objects."
],
"metadata": {
"id": "6H4j6r_-CZBJ"
}
},
{
"cell_type": "code",
"source": [
"name = 'Tom' # Enter your name here\n",
"def print_name():\n",
" print(name)\n",
"\n",
"def print_name_v2():\n",
" name = 'Estelle'\n",
" print(name)\n",
"\n",
"print_name()\n",
"print_name_v2()\n",
"print(name)"
],
"metadata": {
"id": "Yc5umEuVCaQv"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"friends_list = ['Mario', 'Florence', 'Richard']\n",
"pet_tuple = ('Hedwig', 'Na-paw-lyon', 'Cat-hilda')"
],
"metadata": {
"id": "Q-0HxsCmCbie"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"def greeter(friends, pets):\n",
" print(\"It's time to say hi to my friends.\")\n",
" [print(f'Hi {name}! ', end=\"\") for name in friends]\n",
" print('\\nThese are the names of my pets:')\n",
" [print(f'{pet} ', end=\"\") for pet in pets]\n",
" print('\\n')\n",
"\n",
"def pets_are_friends(friends, pets):\n",
" print(\"I consider both my pets and my friend's pets my friends!\")\n",
"\n",
" #add friend's pets\n",
" full_pets = pets\n",
" full_pets += ('Clifford', 'Crookshanks')\n",
"\n",
" full_friends_list = friends\n",
" full_friends_list.extend(full_pets)\n",
"\n",
" print('These are all my friends:')\n",
" [print(f'{name} ', end=\"\") for name in full_friends_list]\n",
" print('\\n')"
],
"metadata": {
"id": "FkdM5aWnCcxh"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"greeter(friends_list, pet_tuple)\n",
"pets_are_friends(friends_list, pet_tuple)\n",
"greeter(friends_list, pet_tuple)"
],
"metadata": {
"id": "aI8z7gV0CebN"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"### **Classes**\n",
"We have worked with many different types of python objects so far:\n",
"strings, lists, dictionaries, etc.\n",
"These objects have different attributes and respond in different ways to\n",
"the built-in functions (`len`, etc.)\n",
"\n",
"How can we make our own, custom objects? Answer: by defining classes."
],
"metadata": {
"id": "3pvm8Lo7Cgvi"
}
},
{
"cell_type": "markdown",
"source": [
"#### **A class to represent a hurricane**\n",
"\n",
"Let's create our first class below,"
],
"metadata": {
"id": "tlhUVq_9Cp0J"
}
},
{
"cell_type": "code",
"source": [
"class Hurricane:\n",
"\n",
" def __init__(self, name):\n",
" self.name = name"
],
"metadata": {
"id": "WxZOIzTpChaH"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"And now let's create an *instance* of that class, `h`:"
],
"metadata": {
"id": "fdFHL4vmC1xl"
}
},
{
"cell_type": "code",
"source": [
"h = Hurricane('florence')\n",
"print(h,h.name)"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "3DS4U1GuCwV3",
"outputId": "31ff8452-5b31-4b42-ca07-b974d6090a23"
},
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"<__main__.Hurricane object at 0x7feac096e8d0> florence\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"Let’s add more, along with some input validation:\n"
],
"metadata": {
"id": "MCk7twL4C61s"
}
},
{
"cell_type": "code",
"source": [
"class Hurricane:\n",
"\n",
" def __init__(self, name, category, lon):\n",
" self.name = name.upper()\n",
" self.category = int(category)\n",
"\n",
" if lon > 180 or lon < -180:\n",
" raise ValueError(f'Invalid lon {lon}')\n",
" self.lon = lon"
],
"metadata": {
"id": "rhrtC-TJC5ta"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"h = Hurricane('florence', 4, -46)\n",
"print(h,h.name)\n",
"h = Hurricane('Ida', 5, 300)"
],
"metadata": {
"id": "sLdd00qRC_F4"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Now let’s add a custom method:\n",
"class Hurricane:\n",
"\n",
" def __init__(self, name, category, lon):\n",
" self.name = name.upper()\n",
" self.category = int(category)\n",
"\n",
" if lon > 180 or lon < -180:\n",
" raise ValueError(f'Invalid lon {lon}')\n",
" self.lon = lon\n",
"\n",
" def is_dangerous(self):\n",
" return self.category > 1"
],
"metadata": {
"id": "cppN0ttsDAgE"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"f = Hurricane('florence', 4, -46)\n",
"f.is_dangerous()"
],
"metadata": {
"id": "Z0iAkf9LDB0c"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### **Magic / Dunder Methods**\n",
"We can implement special methods that begin with double-underscores (i.e. “dunder” methods), which allow us to customize the behavior of our classes. ([Read more here](https://www.python-course.eu/python3_magic_methods.php)). We have already learned one: `__init__`. Let’s implement the `__repr__` method to make our class display something pretty."
],
"metadata": {
"id": "upOCfE5jDEDr"
}
},
{
"cell_type": "code",
"source": [
"class Hurricane:\n",
"\n",
" def __init__(self, name, category, lon):\n",
" self.name = name.upper()\n",
" self.category = int(category)\n",
"\n",
" if lon > 180 or lon < -180:\n",
" raise ValueError(f'Invalid lon {lon}')\n",
" self.lon = lon\n",
"\n",
" def __repr__(self):\n",
" return f\"\"\n",
"\n",
" def is_dangerous(self):\n",
" return self.category > 1"
],
"metadata": {
"id": "6U_YXzB6DEpL"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"f = Hurricane('florence', 4, -46)\n",
"f"
],
"metadata": {
"id": "SLxt3EqoDIAS"
},
"execution_count": null,
"outputs": []
}
]
}