Skip to content

Instantly share code, notes, and snippets.

@IanLulu
Last active July 18, 2022 20:07
Show Gist options
  • Save IanLulu/0aa3d57bffd12014c00157a98dbf12b6 to your computer and use it in GitHub Desktop.
Save IanLulu/0aa3d57bffd12014c00157a98dbf12b6 to your computer and use it in GitHub Desktop.
eCSR-ML-pre-workshop.ipynb
Display the source blob
Display the rendered blob
Raw
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
},
"colab": {
"name": "eCSR-ML-pre-workshop.ipynb",
"provenance": [],
"collapsed_sections": [],
"include_colab_link": true
}
},
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "view-in-github",
"colab_type": "text"
},
"source": [
"<a href=\"https://colab.research.google.com/gist/IanLulu/0aa3d57bffd12014c00157a98dbf12b6/ecsr-ml-pre-workshop.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gsLe-1j6H1UH"
},
"source": [
"# **Pre-Workshop Assignment**\n",
"The objective of this assignment is to review basic concepts of the Python programming language (functions, strings, lists, dictionaries, control flow) and get started with Google Colab before the exploreCSR Machine Learning workshop.\n",
"\n",
"#### **Instructions:**\n",
"There are 10 short programming tasks below. Complete each task by filling in the blanks (`...`) with one or more lines of code.\n",
"\n",
"#### **References:**\n",
"* [The Python Tutorial](http://docs.python.org/3/tutorial/).\n",
"* [What is Colaboratory?](https://colab.research.google.com/notebooks/intro.ipynb)\n",
"* [Overview of Colaboratory Features](https://colab.research.google.com/notebooks/basic_features_overview.ipynb).\n",
"* Joel Grus. _Data Science from Scratch_ (2019)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DObTEDUpBjJq"
},
"source": [
"### **Part 0: Google Colab**\n",
"**Google Colab** allows you to write and execute Python code in your browser using **notebooks**.\n",
"\n",
"A notebook is a list of **cells** that contain either text or code.\n",
"\n",
"To edit the code in a cell, just click on the cell to select it and start editing. To run the code, click on the **Play** button to the left of the cell, or press `SHIFT+ENTER`. The output of the code will then appear below the cell. Try this out by running the code in the cell below."
]
},
{
"cell_type": "code",
"metadata": {
"id": "JNGKY7UpBVfC",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "58357d55-a3e5-4c92-aa79-1ff722603197"
},
"source": [
"print(\"Hello, World!\")"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello, World!\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aJ06grhwKGBB"
},
"source": [
"Note that variables defined in a cell can be later referenced in any other cell within the same notebook. Try this out by running the code in the two cells below."
]
},
{
"cell_type": "code",
"metadata": {
"id": "kuD7vfGeJ8Dz"
},
"source": [
"x = 1\n",
"y = 2"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "uKduddrUJ70S",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c082671b-290a-48fa-98fa-4fe957fd0e75"
},
"source": [
"x + y"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3"
]
},
"metadata": {},
"execution_count": 3
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "kXnzIYPCBkc-"
},
"source": [
"To learn more about Google Colab, watch this short [introductory video](https://www.youtube.com/watch?v=inN8seMm7UI)."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5bchzjGRH1UN"
},
"source": [
"### **Part 1: Functions**\n",
"**Functions** in Python are defined using the keyword `def`, followed by the function name and the list of **parameters** or **arguments** in parentheses.\n",
"\n",
"The statements that form the body of the function start in the next line and must be indented. The first statement of the function body can optionally be a string containing the function's documentation string or **docstring**. The use of docstrings is strongly recommended.\n",
"\n",
"Most functions end with a `return` statement that returns a value from the function. Functions without a `return` statement return `None`."
]
},
{
"cell_type": "code",
"metadata": {
"id": "lrLXICSXH1UN",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "cf76ea94-95be-4cd1-c785-b0d45b0e97a0"
},
"source": [
"def add1(x):\n",
" \"\"\"This function adds 1 to x and returns the result.\"\"\"\n",
" return x + 1\n",
"add1(2) # returns 3"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3"
]
},
"metadata": {},
"execution_count": 4
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "wjkXtpseH1UO",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "bf90e9c1-9225-41eb-dd1b-767d5c1e3726"
},
"source": [
"help(add1) # returns information about function add1"
],
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Help on function add1 in module __main__:\n",
"\n",
"add1(x)\n",
" This function adds 1 to x and returns the result.\n",
"\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "nTgl8zaBH1UO"
},
"source": [
"**Task 01 (of 10): Write a function that returns the square of `x`.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "iE2YTk7uH1UO"
},
"source": [
"def squared(x):\n",
" return x * x"
],
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "eJ4WOMVzH1UO",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "afd98be3-8033-4ae5-dcf5-499c23f3f164"
},
"source": [
"squared(3) # should return 9"
],
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"9"
]
},
"metadata": {},
"execution_count": 7
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Ijv5t_X7H1UQ"
},
"source": [
"### **Part 2: Strings**\n",
"**Strings** in Python can be enclosed in single quotes or double quotes. The backslash symbol (`\\`) can be used to escape quotes.\n",
"\n",
"The `print()` function can be used to output a string and the `len()` function can be used to return the **length** of a string."
]
},
{
"cell_type": "code",
"metadata": {
"id": "IgY83tFMH1UQ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "d6bf52fc-8b80-4d26-db2d-9e4fcbc09afc"
},
"source": [
"string1 = 'Hello'\n",
"print(string1)\n",
"string2 = \"world!\"\n",
"print(string2)\n",
"string3 = '\\\"Hello world!\\\"'\n",
"print(string3)"
],
"execution_count": 1,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello\n",
"world!\n",
"\"Hello world!\"\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "h2uNFwTVH1UQ",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f2ce46e8-4c53-47f4-af03-fc26cc61b3cb"
},
"source": [
"len(string1) # returns 5"
],
"execution_count": 2,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"5"
]
},
"metadata": {},
"execution_count": 2
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TCYLX_VtH1UR"
},
"source": [
"Strings can span multiple lines using three single quotes or double quotes."
]
},
{
"cell_type": "code",
"metadata": {
"id": "PYTcSdWHH1UR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "f5ad3b67-f0de-4a5c-cd89-25cd6219bd90"
},
"source": [
"string_multi = '''Hello\n",
"world!'''\n",
"print(string_multi)"
],
"execution_count": 3,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Hello\n",
"world!\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JjjCAxBzH1UR"
},
"source": [
"Strings can be concatenated using the `+` operator and repeated using the `*` operator.\n",
"\n",
"**Task 02 (of 10): Concatenate strings `x` and `y` and repeat string `y` two times.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "hjRolQGqH1UR"
},
"source": [
"x = \"good\"\n",
"y = \"bye\"\n",
"xy = x + y\n",
"yy = y * 2"
],
"execution_count": 12,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "MR3Q47z2H1UR",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "2a1471b9-fc44-4e5a-b3a0-ce292c00a1fe"
},
"source": [
"print(xy) # should return goodbye\n",
"print(yy) # should return byebye"
],
"execution_count": 13,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"goodbye\n",
"byebye\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3RZvCucqH1UR"
},
"source": [
"Strings can be **indexed**. The first character has index 0. Negative indices start counting from the right.\n",
"\n",
"Strings can also be **sliced** to obtain **substrings**. For example, `x[i:j]` returns the substring of `x` that starts in position `i` and ends in, **but does not include**, position `j`. If index `i` is omitted, it defaults to 0, and if index `j` is omitted, it defaults to the size of the string.\n",
"\n",
"**Task 03 (of 10): Return the first character, the next-to-last character, the first three characters, and the last eight characters of string `word`.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "mqYc2yNAH1US"
},
"source": [
"word = \"Introduction to Machine Learning\"\n",
"first = word[:1]\n",
"next_to_last = word[-2:-1]\n",
"first_three = word[:3]\n",
"last_eight = word[-8:]"
],
"execution_count": 23,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "zsze3eDqH1US",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "050bbeb4-7987-4ba3-8211-bc59ce063ac1"
},
"source": [
"print(first) # should return I\n",
"print(next_to_last) # should return n\n",
"print(first_three) # should return Int\n",
"print(last_eight) # should return Learning"
],
"execution_count": 24,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"I\n",
"n\n",
"Int\n",
"Learning\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "vHSUrawbH1US"
},
"source": [
"Python strings are **immutable**; that is, they cannot be changed. Trying to assign a value to a position in a string results in an error."
]
},
{
"cell_type": "code",
"metadata": {
"id": "FwCaxiGdH1US",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 165
},
"outputId": "5afa73fb-49aa-424b-bad5-c92ccee3911f"
},
"source": [
"word[0] = 'i' # results in an error"
],
"execution_count": 25,
"outputs": [
{
"output_type": "error",
"ename": "TypeError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-25-894f9d1f2d5c>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mword\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'i'\u001b[0m \u001b[0;31m# results in an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Mk0iYYz0H1US"
},
"source": [
"### **Part 3: Lists**\n",
"**Lists** are one the most useful data structures in Python. Lists can be written as a comma-separated list of **items** between brackets.\n",
"\n",
"The `print()` function can be used to output a list, the `len()` function can be used to return the **number of items** in a list, and the `in` operator can be used to check whether an item is in a list."
]
},
{
"cell_type": "code",
"metadata": {
"id": "9bYi7aIwH1UT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "47de0796-ebf1-4ff2-8729-175673b1cff0"
},
"source": [
"even_list = [0, 2, 4, 6, 8, 10]\n",
"print(even_list)"
],
"execution_count": 26,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[0, 2, 4, 6, 8, 10]\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "gPSvTf-YH1UT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "b337d005-1175-4968-d927-a010c31e003b"
},
"source": [
"len(even_list) # returns 6"
],
"execution_count": 27,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"6"
]
},
"metadata": {},
"execution_count": 27
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "GymdKPsCH1UT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a84a0e78-b574-4a68-8fb8-a88d51d9db5f"
},
"source": [
"1 in even_list # returns False"
],
"execution_count": 28,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 28
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "rCP1RdP5H1UT"
},
"source": [
"Like strings, lists can be **indexed** and **sliced**.\n",
"\n",
"**Task 04 (of 10): Return the second item, the last item, the middle two items, and the items in even positions of list `even_list`.**\n",
"_Hint:_ A slice can take a third parameter that specifies its **stride**; that is, the number of characters to move forward after the previous character."
]
},
{
"cell_type": "code",
"metadata": {
"id": "EraX35bhH1UT"
},
"source": [
"second = even_list[1]\n",
"last = even_list[-1:]\n",
"middle_two = even_list[2:4]\n",
"even_positions = even_list[::2]"
],
"execution_count": 30,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "Ifs7C4zdH1UT",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "aee6eb3f-169c-4880-85dd-0ae1d098b810"
},
"source": [
"print(second) # should return 2\n",
"print(last) # should return 10\n",
"print(middle_two) # should return [4, 6]\n",
"print(even_positions) # should return [0, 4, 8]"
],
"execution_count": 31,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"2\n",
"[10]\n",
"[4, 6]\n",
"[0, 4, 8]\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "CIwQc2lTH1UU"
},
"source": [
"Unlike strings, lists are **mutable**; that is, their content can be changed. It is also possible to add a new item at the end of a list using the `append()` method."
]
},
{
"cell_type": "code",
"metadata": {
"id": "6fHMC0g4H1UU",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6ec0eb62-7f58-4528-8b1e-d14f4d461e7d"
},
"source": [
"even_list.append(12) # appends 12 to end of list\n",
"even_list.append(15) # appends 15 to end of list\n",
"print(even_list)\n",
"even_list[-1] = 14 # changes last element of list\n",
"print(even_list)\n",
"even_list[-2:] = [] # removes last two elements of list\n",
"print(even_list)"
],
"execution_count": 32,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[0, 2, 4, 6, 8, 10, 12, 15]\n",
"[0, 2, 4, 6, 8, 10, 12, 14]\n",
"[0, 2, 4, 6, 8, 10]\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2ir3Me3xH1UU"
},
"source": [
"Lists can be **sorted** using the `sort` method (in-place) or the `sorted()` function (not in-place)"
]
},
{
"cell_type": "code",
"metadata": {
"id": "OV5D93eGH1UU",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "bbd03f1a-9605-4d59-bf0b-29bd5aba9596"
},
"source": [
"some_list = [2, -5, 11, 8, -3]\n",
"some_list_sorted = sorted(some_list) # sort items from smallest to largest\n",
"print(some_list_sorted)"
],
"execution_count": 38,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[-5, -3, 2, 8, 11]\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1cYyMQH1H1UU"
},
"source": [
"**Task 05 (of 10): Sort the items of list `some_list` by absolute value from largest to smallest.**\n",
"_Hint:_ Check the parameters of the `sorted()` function."
]
},
{
"cell_type": "code",
"metadata": {
"id": "OzwftwMEH1UU"
},
"source": [
"# help(sorted)\n",
"\n",
"def f(x):\n",
" return abs(x)\n",
"\n",
"some_list_sorted_again = sorted(some_list, key = f, reverse = True)"
],
"execution_count": 48,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "jk34dycTH1UU",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6ea9f701-ce70-435b-df6f-afc20cc30904"
},
"source": [
"print(some_list_sorted_again) # should return [11, 8, -5, -3, 2]"
],
"execution_count": 49,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"[11, 8, -5, -3, 2]\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HBevFV41H1UV"
},
"source": [
"### **Part 4: Dictionaries**\n",
"Another useful data structure in Python are **dictionaries**, which are sets of **keys** associated with **values**. Keys must be unique and can be of any immutable type, such as strings and numbers. Dictionaries can be written as a comma-separated list of `key: value` pairs between braces.\n",
"\n",
"The `print()` function can be used to output a dictionary, the `len()` function can be used to return the **number of key-value pairs** in a dictionary, the `list()` function can be used to return a list of all keys in a dictionary, and the `in` operator can be used to check whether a key is in a dictionary."
]
},
{
"cell_type": "code",
"metadata": {
"id": "o4w4gIwJH1UV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "eb97a5c5-ce62-4e61-f8a9-8b143ab7866d"
},
"source": [
"grades = {'Joe': 85, 'Ana': 97, 'Rob': 78}\n",
"print(grades)"
],
"execution_count": 50,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"{'Joe': 85, 'Ana': 97, 'Rob': 78}\n"
]
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "i17_EqGzH1UV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c87b99ed-d8df-46ab-81cb-66ac80af9468"
},
"source": [
"len(grades) # returns 3"
],
"execution_count": 51,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"3"
]
},
"metadata": {},
"execution_count": 51
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "8Q7x1ZCLH1UV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6e1d9aaf-44be-4f19-8cce-fb33b5b02a93"
},
"source": [
"list(grades) # returns ['Joe', 'Ana', 'Rob']"
],
"execution_count": 52,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"['Joe', 'Ana', 'Rob']"
]
},
"metadata": {},
"execution_count": 52
}
]
},
{
"cell_type": "code",
"metadata": {
"id": "0oSYt9tzH1UV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "da5844ed-6103-4577-c630-7bf610a1f54f"
},
"source": [
"'Sue' in grades # returns False"
],
"execution_count": 53,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"False"
]
},
"metadata": {},
"execution_count": 53
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "UGHw3sX1H1UW"
},
"source": [
"Trying to access a key that is not in a dictionary results in an error."
]
},
{
"cell_type": "code",
"metadata": {
"id": "zQUl6Z6eH1UW",
"colab": {
"base_uri": "https://localhost:8080/",
"height": 165
},
"outputId": "c3f9e028-c9e2-41b8-88c3-f80a1e0e98d9"
},
"source": [
"print(grades['Sue']) # results in an error"
],
"execution_count": 54,
"outputs": [
{
"output_type": "error",
"ename": "KeyError",
"evalue": "ignored",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-54-7468b91773fd>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgrades\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'Sue'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# results in an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mKeyError\u001b[0m: 'Sue'"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "05B1TmvfH1UX"
},
"source": [
"**Task 06 (of 10): Modify dictionary `grades` by changing Rob's grade to 88, adding Sue with grade 90, and deleting Joe using the `del` statement.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "faCvHn3gyt9w"
},
"source": [
"grades['Rob'] = 88\n",
"grades['Sue'] = 90\n",
"del grades['Joe']"
],
"execution_count": 56,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "9XPp35mFH1UX",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "109c5d6b-809a-4afe-b58d-a3f6ff359740"
},
"source": [
"print(grades) # should return {'Ana': 97, 'Rob': 88, 'Sue': 90}"
],
"execution_count": 57,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"{'Ana': 97, 'Rob': 88, 'Sue': 90}\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zbCyB8M5H1UZ"
},
"source": [
"### **Part 5: Control Flow**\n",
"As in other programming languages, we can write **`if`**, **`while`**, and **`for`** statements in Python.\n",
"\n",
"An `if` statement can be written using the keywords `if`, `elif` (short for `else if`), and `else`."
]
},
{
"cell_type": "code",
"metadata": {
"id": "pjkmSYM2H1Ua",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "643000ee-2693-48b2-ca10-8c0f1e282673"
},
"source": [
"x = 1\n",
"if x > 0:\n",
" print(\"Positive\")\n",
"elif x < 0:\n",
" print(\"Negative\")\n",
"else:\n",
" print(\"Zero\")"
],
"execution_count": 58,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Positive\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BYuW_oqBH1Ua"
},
"source": [
"**Task 07 (of 10): Write a function, using an `if` statement, that returns `True` if `x` is even and `False` if `x` is odd.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "Pq3c4SJLH1Ua"
},
"source": [
"def is_even(x):\n",
" if x % 2 == 0:\n",
" return True\n",
" elif x % 2 != 0:\n",
" return False"
],
"execution_count": 62,
"outputs": []
},
{
"cell_type": "code",
"metadata": {
"id": "IRXhrqNaH1Ua",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4371d26e-16e1-4e4e-dbc8-12bbe415a21e"
},
"source": [
"print(is_even(2)) # should return True\n",
"print(is_even(5)) # should return False"
],
"execution_count": 63,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"True\n",
"False\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JYEAA-4kH1Ua"
},
"source": [
"A `while` statement executes as long as a condition is `True`."
]
},
{
"cell_type": "code",
"metadata": {
"id": "Pyxyj8_vH1Ua",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "da5f48e6-4afb-4d28-a2b9-dafbb8177b14"
},
"source": [
"x = 1\n",
"while x < 5:\n",
" print(x)\n",
" x = x + 1"
],
"execution_count": 64,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1\n",
"2\n",
"3\n",
"4\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_In4k8xWH1Ua"
},
"source": [
"**Task 08 (of 10): Write a `while` statement that prints and then squares `x` as long as `x` is less than 100.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "PyPu16-MH1Ub",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "a8ce6bbd-e0d1-4370-dead-0702da25eab2"
},
"source": [
"x = 2\n",
"while x < 100: # should return 2, 4, 16\n",
" print(x)\n",
" x = x * x"
],
"execution_count": 65,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"2\n",
"4\n",
"16\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "NXfgtIiaH1Ub"
},
"source": [
"A `for` statement iterates over the items of a sequence, such as a list or a string, in the order that they appear in the sequence."
]
},
{
"cell_type": "code",
"metadata": {
"id": "r2eMAc0BH1Ub",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "4ef0bd8c-9864-4b38-fd31-4e97cb58f30e"
},
"source": [
"words = ['introduction', 'to', 'machine', 'learning']\n",
"for w in words:\n",
" print(w, len(w))"
],
"execution_count": 66,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"introduction 12\n",
"to 2\n",
"machine 7\n",
"learning 8\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "-8E6p1MwH1Ub"
},
"source": [
"**Task 09 (of 10): Write a `for` statement that iterates over the characters in string `long_word` and prints those that are vowels.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "hK_2pi7bH1Ub",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "0c6a2874-469f-4310-d830-446942e0db1c"
},
"source": [
"long_word = \"computation\"\n",
"for c in long_word: # should return o, u, a, i, o\n",
" if c in ['a', 'i', 'u', 'e', 'o']:\n",
" print(c)"
],
"execution_count": 67,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"o\n",
"u\n",
"a\n",
"i\n",
"o\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "f5EmuSifH1Ub"
},
"source": [
"A `for` statement can also be used to iterate over the key-value pairs in a dictionary."
]
},
{
"cell_type": "code",
"metadata": {
"id": "ITu_soZBH1Ub",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "14a7b76f-6afa-45da-f5b4-806906c86587"
},
"source": [
"for student, grade in grades.items():\n",
" print(\"The grade of\", student, \"is\", grade)"
],
"execution_count": 68,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"The grade of Ana is 97\n",
"The grade of Rob is 88\n",
"The grade of Sue is 90\n"
]
}
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2HhAgfrQH1Uc"
},
"source": [
"To iterate over a sequence of numbers, the `range()` function can be used. For example, `range(10)` returns a sequence from 0 to 9 and `range(5, 10)` returns a sequence from 5 to 9.\n",
"\n",
"**Task 10 (of 10): Write a `for` statement, using the `range()` function, that iterates over the first 10 positive integers and prints those that are multiples of 3.**"
]
},
{
"cell_type": "code",
"metadata": {
"id": "GuDpK0-7H1Uc",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "651b6dac-64ff-4fc7-83c9-58d95292e9ae"
},
"source": [
"for i in range(1, 11): # should return 3, 6, 9\n",
" if i % 3 == 0:\n",
" print(i)"
],
"execution_count": 69,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"3\n",
"6\n",
"9\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"**You have completed the assignment. Good job!**"
],
"metadata": {
"id": "L9wEWqOHU4Qg"
}
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment