├── Coursera UY67RTQUPHMA.pdf ├── README.md ├── all week python notebooks ├── 3-1.2ExceptionHandling.ipynb ├── PY0101EN-1-1-Write_your_first_python_code (Types, Expressions, and Variables).ipynb ├── PY0101EN-1-2-Strings.ipynb ├── PY0101EN-2-1-Tuples.ipynb ├── PY0101EN-2-2-Lists.ipynb ├── PY0101EN-2-3-Sets.ipynb ├── PY0101EN-2-4-Dictionaries.ipynb ├── PY0101EN-3-1-Conditions.ipynb ├── PY0101EN-3-2-Loops.ipynb ├── PY0101EN-3-3-Functions .ipynb ├── PY0101EN-3-4-Classes.ipynb ├── PY0101EN-4-1-ReadFile.ipynb ├── PY0101EN-4-2-WriteFile.ipynb ├── PY0101EN-4-3-LoadData.ipynb ├── PY0101EN-5-1-Numpy1D.ipynb ├── PY0101EN-5-2-Numpy2D.ipynb ├── PY0101EN-5.1_Simple_API_2__v2.ipynb ├── PY0101EN-5.2_API_2.v2.ipynb └── PY0101EN-5.3_Requests_HTTP.ipynb ├── file handling exercise ├── file_eg1.py ├── file_eg2.py ├── file_exercise.py ├── file_exercise_with_test.py ├── inactive.txt ├── members.txt ├── testAppend.txt └── testWrite.txt ├── oop exercise ├── oops_text_analysis.py └── readme.md └── quizzes ├── Final Exam - Quiz.pdf ├── Module 1 Graded Quiz.pdf ├── Module 2 Graded Quiz.pdf ├── Module 3 Graded Quiz.pdf ├── Module 4 Graded Quiz.pdf ├── Module 5 Graded Quiz.pdf ├── Practice Quiz - Conditions and Branching.pdf ├── Practice Quiz - Exception Handling.pdf ├── Practice Quiz - List and Tuples.pdf ├── Practice Quiz - Loops.pdf ├── Practice Quiz - NumPy in Python.pdf ├── Practice Quiz - Objects and Classes.pdf ├── Practice Quiz - Pandas.pdf ├── Practice Quiz - REST APIs & HTTP Requests.pdf ├── Practice Quiz - Reading and Writing Files with Open.pdf ├── Practice Quiz - Sets.pdf ├── Practice Quiz - Simple APIs.pdf ├── Practice Quiz - String Operation.pdf ├── Practice Quiz - Types.pdf ├── Practice Quiz - Variables and Expression.pdf ├── Practice Quiz -Functions.pdf ├── Practice Quiz- Dictionaries.pdf └── Python Cheat Sheet - The Basics Coursera.pdf /Coursera UY67RTQUPHMA.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/Coursera UY67RTQUPHMA.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## [Python for Data Science, AI & Development](https://www.coursera.org/learn/python-for-applied-data-science-ai) 🔥 2 | 3 | * _Offered By **IBM Skills Network** on **Coursera**_. 4 | 5 | course accomplishment certificate 6 | 7 | [Verify here!](https://coursera.org/verify/UY67RTQUPHMA) 8 | 9 |

What you'll learn? 📊📈👨🏻‍💻🤖🐍

10 |

11 |   🔸 Python Basics including Types, Expressions, and Variables.
12 |   🔸 Data Structures in Python including Lists, Tuples, Dictionaries, Sets.
13 |   🔸 Python programming using Branching, Loops, Functions, Objects & Classes.
14 |   🔸 Working with data in Python using Pandas and Numpy libraries.
15 | 

16 | 17 | ## About this course 18 | This course was designed to provide the building blocks for Python programming and data collection for those choosing a career in Data Science, Data Engineering, AI or Application Development. 19 | 20 | Initially conceived as a foundation course for Data Science and AI it has been refreshed several times to keep pace with emerging career options. Additional content has been added which is applicable to Data Science, Data Engineering, AI or Application Development. 21 | 22 | After completing this course you will have learned foundational skills in Python programming which you can then go on to apply in the Python Project course for your chosen career. The Python Project courses involve real world scenarios where you are in charge of a final project as a Data Scientist, a Data Engineer, or in AI and Application Development. By finishing this course and your follow-on Python Project, you will gain the basic skills to continue the steps on your chosen career path. 23 | 24 | **Note**: This course is a pre-requisite for the Python Project courses and should be completed in full before attempting the appropriate Python Project course. 25 | 26 | 27 | _This course was easy to learn for me because I was already familiar with the topics taught in it. I have also learnt many new things from this course. I am grateful to the instructor._ 28 | 29 | --- 30 | 31 | * Learn NumPy further: click here
32 | * Learn Pandas further: coming soon...
33 | 34 | Thank You! HappY Learning.... 35 | -------------------------------------------------------------------------------- /all week python notebooks/3-1.2ExceptionHandling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": "
\n \"cognitiveclass.ai\n
\n", 27 | "metadata": {} 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": "# **Exception Handling**\n\nEstimated time needed: **15** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Understand exceptions\n* Handle the exceptions\n", 32 | "metadata": {} 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "source": "## Table of Contents\n", 37 | "metadata": {} 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "* What is an Exception?\n* Exception Handling\n", 42 | "metadata": {} 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": "***\n", 47 | "metadata": {} 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "source": "## What is an Exception?\n", 52 | "metadata": {} 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "source": "In this section you will learn about what an exception is and see examples of them.\n", 57 | "metadata": {} 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "source": "### Definition\n", 62 | "metadata": {} 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "source": "An exception is an error that occurs during the execution of code. This error causes the code to raise an exception and if not prepared to handle it will halt the execution of the code.\n", 67 | "metadata": {} 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "source": "### Examples\n", 72 | "metadata": {} 73 | }, 74 | { 75 | "cell_type": "markdown", 76 | "source": "Run each piece of code and observe the exception raised\n", 77 | "metadata": {} 78 | }, 79 | { 80 | "cell_type": "code", 81 | "source": "1/0", 82 | "metadata": {}, 83 | "execution_count": null, 84 | "outputs": [] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "source": "ZeroDivisionError occurs when you try to divide by zero.\n", 89 | "metadata": {} 90 | }, 91 | { 92 | "cell_type": "code", 93 | "source": "y = a + 5", 94 | "metadata": {}, 95 | "execution_count": null, 96 | "outputs": [] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "source": "NameError -- in this case, it means that you tried to use the variable a when it was not defined.\n", 101 | "metadata": {} 102 | }, 103 | { 104 | "cell_type": "code", 105 | "source": "a = [1, 2, 3]\na[10]", 106 | "metadata": {}, 107 | "execution_count": null, 108 | "outputs": [] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "source": "IndexError -- in this case, it occured because you tried to access data from a list using an index that does not exist for this list.\n", 113 | "metadata": {} 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "source": "There are many more exceptions that are built into Python, here is a list of them [https://docs.python.org/3/library/exceptions.html](https://docs.python.org/3/library/exceptions.html?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n", 118 | "metadata": {} 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "source": "## Exception Handling\n", 123 | "metadata": {} 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "source": "In this section you will learn how to handle exceptions. You will understand how to make your program perform specified tasks instead of halting code execution when an exception is encountered.\n", 128 | "metadata": {} 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "source": "### Try Except\n", 133 | "metadata": {} 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "source": "A try except will allow you to execute code that might raise an exception and in the case of any exception or a specific one we can handle or catch the exception and execute specific code. This will allow us to continue the execution of our program even if there is an exception.\n\nPython tries to execute the code in the try block. In this case if there is any exception raised by the code in the try block, it will be caught and the code block in the except block will be executed. After that, the code that comes after the try except will be executed.\n", 138 | "metadata": {} 139 | }, 140 | { 141 | "cell_type": "code", 142 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept:\n # code to execute if there is an exception\n \n# code that will still execute if there is an exception", 143 | "metadata": {}, 144 | "execution_count": null, 145 | "outputs": [] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "source": "### Try Except Example\n", 150 | "metadata": {} 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "source": "In this example we are trying to divide a number given by the user, save the outcome in the variable a, and then we would like to print the result of the operation. When taking user input and dividing a number by it there are a couple of exceptions that can be raised. For example if we divide by zero. Try running the following block of code with b as a number. An exception will only be raised if b is zero.\n", 155 | "metadata": {} 156 | }, 157 | { 158 | "cell_type": "code", 159 | "source": "a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\n print(\"Success a=\",a)\nexcept:\n print(\"There was an error\")\n \n", 160 | "metadata": {}, 161 | "execution_count": null, 162 | "outputs": [] 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "source": "### Try Except Specific\n", 167 | "metadata": {} 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "source": "A specific try except allows you to catch certain exceptions and also execute certain code depending on the exception. This is useful if you do not want to deal with some exceptions and the execution should halt. It can also help you find errors in your code that you might not be aware of. Furthermore, it can help you differentiate responses to different exceptions. In this case, the code after the try except might not run depending on the error.\n", 172 | "metadata": {} 173 | }, 174 | { 175 | "cell_type": "markdown", 176 | "source": "Do not run, just to illustrate:\n", 177 | "metadata": {} 178 | }, 179 | { 180 | "cell_type": "code", 181 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept (ZeroDivisionError, NameError):\n # code to execute if there is an exception of the given types\n \n# code that will execute if there is no exception or a one that we are handling", 182 | "metadata": {}, 183 | "execution_count": null, 184 | "outputs": [] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\n \n# code that will execute if there is no exception or a one that we are handling", 189 | "metadata": {}, 190 | "execution_count": null, 191 | "outputs": [] 192 | }, 193 | { 194 | "cell_type": "markdown", 195 | "source": "You can also have an empty except at the end to catch an unexpected exception:\n", 196 | "metadata": {} 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "source": "Do not run, just to illustrate:\n", 201 | "metadata": {} 202 | }, 203 | { 204 | "cell_type": "code", 205 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\n \n# code that will execute if there is no exception or a one that we are handling", 206 | "metadata": {}, 207 | "execution_count": null, 208 | "outputs": [] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "source": "### Try Except Specific Example\n", 213 | "metadata": {} 214 | }, 215 | { 216 | "cell_type": "markdown", 217 | "source": "This is the same example as above, but now we will add differentiated messages depending on the exception, letting the user know what is wrong with the input.\n", 218 | "metadata": {} 219 | }, 220 | { 221 | "cell_type": "code", 222 | "source": "a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\n print(\"Success a=\",a)\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\n \n", 223 | "metadata": {}, 224 | "execution_count": null, 225 | "outputs": [] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "source": "### Try Except Else and Finally\n", 230 | "metadata": {} 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "source": "else allows one to check if there was no exception when executing the try block. This is useful when we want to execute something only if there were no errors.\n", 235 | "metadata": {} 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "source": "do not run, just to illustrate\n", 240 | "metadata": {} 241 | }, 242 | { 243 | "cell_type": "code", 244 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\nelse:\n # code to execute if there is no exception\n \n# code that will execute if there is no exception or a one that we are handling", 245 | "metadata": {}, 246 | "execution_count": null, 247 | "outputs": [] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "source": "finally allows us to always execute something even if there is an exception or not. This is usually used to signify the end of the try except.\n", 252 | "metadata": {} 253 | }, 254 | { 255 | "cell_type": "code", 256 | "source": "# potential code before try catch\n\ntry:\n # code to try to execute\nexcept ZeroDivisionError:\n # code to execute if there is a ZeroDivisionError\nexcept NameError:\n # code to execute if there is a NameError\nexcept:\n # code to execute if ther is any exception\nelse:\n # code to execute if there is no exception\nfinally:\n # code to execute at the end of the try except no matter what\n \n# code that will execute if there is no exception or a one that we are handling", 257 | "metadata": {}, 258 | "execution_count": null, 259 | "outputs": [] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "source": "### Try Except Else and Finally Example\n", 264 | "metadata": {} 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "source": "You might have noticed that even if there is an error the value of a is always printed. Let's use the else and print the value of a only if there is no error.\n", 269 | "metadata": {} 270 | }, 271 | { 272 | "cell_type": "code", 273 | "source": "a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"success a=\",a)", 274 | "metadata": {}, 275 | "execution_count": null, 276 | "outputs": [] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "source": "Now lets let the user know that we are done processing their answer. Using the finally, let's add a print.\n", 281 | "metadata": {} 282 | }, 283 | { 284 | "cell_type": "code", 285 | "source": "a = 1\n\ntry:\n b = int(input(\"Please enter a number to divide a\"))\n a = a/b\nexcept ZeroDivisionError:\n print(\"The number you provided cant divide 1 because it is 0\")\nexcept ValueError:\n print(\"You did not provide a number\")\nexcept:\n print(\"Something went wrong\")\nelse:\n print(\"success a=\",a)\nfinally:\n print(\"Processing Complete\")", 286 | "metadata": {}, 287 | "execution_count": null, 288 | "outputs": [] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "source": "## Authors\n", 293 | "metadata": {} 294 | }, 295 | { 296 | "cell_type": "markdown", 297 | "source": "Joseph Santarcangelo\n", 298 | "metadata": {} 299 | }, 300 | { 301 | "cell_type": "markdown", 302 | "source": "## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ---------------------------- |\n| 2020-09-02 | 2.0 | Simran | Template updates to the file |\n| | | | |\n| | | | |\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 303 | "metadata": {} 304 | } 305 | ] 306 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-1-2-Strings.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"cell_type":"markdown","metadata":{},"source":["

\n"," \n"," \"Skills\n"," \n","

\n","\n","# String Operations\n","\n","Estimated time needed: **15** minutes\n","\n","## Objectives\n","\n","After completing this lab you will be able to:\n","\n","* Work with Strings\n","* Perform operations on String\n","* Manipulate Strings using indexing and escape sequences\n"]},{"cell_type":"markdown","metadata":{},"source":["

Table of Contents

\n","
\n"," \n","\n","
\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["

What are Strings?

\n"]},{"cell_type":"markdown","metadata":{},"source":["The following example shows a string contained within 2 quotation marks:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Use quotation marks for defining string\n","\n","\"Michael Jackson\""]},{"cell_type":"markdown","metadata":{},"source":["We can also use single quotation marks:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Use single quotation marks for defining string\n","\n","'Michael Jackson'"]},{"cell_type":"markdown","metadata":{},"source":["A string can be a combination of spaces and digits:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Digitals and spaces in string\n","\n","'1 2 3 4 5 6 '"]},{"cell_type":"markdown","metadata":{},"source":["A string can also be a combination of special characters :\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Special characters in string\n","\n","'@#2_#]&*^%$'"]},{"cell_type":"markdown","metadata":{},"source":["We can print our string using the print statement:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the string\n","\n","print(\"hello!\")"]},{"cell_type":"markdown","metadata":{},"source":["We can bind or assign a string to another variable:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Assign string to variable\n","\n","name = \"Michael Jackson\"\n","name"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["

Indexing

\n"]},{"cell_type":"markdown","metadata":{},"source":["It is helpful to think of a string as an ordered sequence. Each element in the sequence can be accessed using an index represented by the array of numbers:\n"]},{"cell_type":"markdown","metadata":{},"source":["\n"]},{"cell_type":"markdown","metadata":{},"source":["The first index can be accessed as follows:\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n","
\n","[Tip]: Because indexing starts at 0, it means the first index is on the index 0.\n","
\n","
\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the first element in the string\n","\n","print(name[0])"]},{"cell_type":"markdown","metadata":{},"source":["We can access index 6:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the element on index 6 in the string\n","\n","print(name[6])"]},{"cell_type":"markdown","metadata":{},"source":["Moreover, we can access the 13th index:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the element on the 13th index in the string\n","\n","print(name[13])"]},{"cell_type":"markdown","metadata":{},"source":["

Negative Indexing

\n"]},{"cell_type":"markdown","metadata":{},"source":["We can also use negative indexing with strings:\n"]},{"cell_type":"markdown","metadata":{},"source":["\n"]},{"cell_type":"markdown","metadata":{},"source":["Negative index can help us to count the element from the end of the string.\n"]},{"cell_type":"markdown","metadata":{},"source":["The last element is given by the index -1:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the last element in the string\n","\n","print(name[-1])"]},{"cell_type":"markdown","metadata":{},"source":["The first element can be obtained by index -15:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the first element in the string\n","\n","print(name[-15])"]},{"cell_type":"markdown","metadata":{},"source":["We can find the number of characters in a string by using len, short for length:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Find the length of string\n","\n","len(\"Michael Jackson\")"]},{"cell_type":"markdown","metadata":{},"source":["

Slicing

\n"]},{"cell_type":"markdown","metadata":{},"source":["We can obtain multiple characters from a string using slicing, we can obtain the 0 to 4th and 8th to the 12th element:\n"]},{"cell_type":"markdown","metadata":{},"source":["\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n","
\n","[Tip]: When taking the slice, the first number means the index (start at 0), and the second number means the length from the index to the last element you want (start at 1)\n","
\n","
\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Take the slice on variable name with only index 0 to index 3\n","\n","name[0:4]"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Take the slice on variable name with only index 8 to index 11\n","\n","name[8:12]"]},{"cell_type":"markdown","metadata":{},"source":["

Stride

\n"]},{"cell_type":"markdown","metadata":{},"source":["We can also input a stride value as follows, with the '2' indicating that we are selecting every second variable:\n"]},{"cell_type":"markdown","metadata":{},"source":["\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Get every second element. The elments on index 1, 3, 5 ...\n","\n","name[::2]"]},{"cell_type":"markdown","metadata":{},"source":["We can also incorporate slicing with the stride. In this case, we select the first five elements and then use the stride:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Get every second element in the range from index 0 to index 4\n","\n","name[0:5:2]"]},{"cell_type":"markdown","metadata":{},"source":["

Concatenate Strings

\n"]},{"cell_type":"markdown","metadata":{},"source":["We can concatenate or combine strings by using the addition symbols, and the result is a new string that is a combination of both:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Concatenate two strings\n","\n","statement = name + \"is the best\"\n","statement"]},{"cell_type":"markdown","metadata":{},"source":["To replicate values of a string we simply multiply the string by the number of times we would like to replicate it. In this case, the number is three. The result is a new string, and this new string consists of three copies of the original string:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Print the string for 3 times\n","\n","3 * \"Michael Jackson\""]},{"cell_type":"markdown","metadata":{},"source":["You can create a new string by setting it to the original variable. Concatenated with a new string, the result is a new string that changes from Michael Jackson to “Michael Jackson is the best\".\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Concatenate strings\n","\n","name = \"Michael Jackson\"\n","name = name + \" is the best\"\n","name"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["

Escape Sequences

\n"]},{"cell_type":"markdown","metadata":{},"source":["Back slashes represent the beginning of escape sequences. Escape sequences represent strings that may be difficult to input. For example, back slash \"n\" represents a new line. The output is given by a new line after the back slash \"n\" is encountered:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# New line escape sequence\n","\n","print(\" Michael Jackson \\n is the best\" )"]},{"cell_type":"markdown","metadata":{},"source":["Similarly, back slash \"t\" represents a tab:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Tab escape sequence\n","\n","print(\" Michael Jackson \\t is the best\" )"]},{"cell_type":"markdown","metadata":{},"source":["If you want to place a back slash in your string, use a double back slash:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Include back slash in string\n","\n","print(\" Michael Jackson \\\\ is the best\" )"]},{"cell_type":"markdown","metadata":{},"source":["We can also place an \"r\" before the string to display the backslash:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# r will tell python that string will be display as raw string\n","\n","print(r\" Michael Jackson \\ is the best\" )"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["

String Operations

\n"]},{"cell_type":"markdown","metadata":{},"source":["There are many string operation methods in Python that can be used to manipulate the data. We are going to use some basic string operations on the data.\n"]},{"cell_type":"markdown","metadata":{},"source":["Let's try with the method upper; this method converts lower case characters to upper case characters:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Convert all the characters in string to upper case\n","\n","a = \"Thriller is the sixth studio album\"\n","print(\"before upper:\", a)\n","b = a.upper()\n","print(\"After upper:\", b)"]},{"cell_type":"markdown","metadata":{},"source":["The method replace replaces a segment of the string, i.e. a substring with a new string. We input the part of the string we would like to change. The second argument is what we would like to exchange the segment with, and the result is a new string with the segment changed:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Replace the old substring with the new target substring is the segment has been found in the string\n","\n","a = \"Michael Jackson is the best\"\n","b = a.replace('Michael', 'Janet')\n","b"]},{"cell_type":"markdown","metadata":{},"source":["The method find finds a sub-string. The argument is the substring you would like to find, and the output is the first index of the sequence. We can find the sub-string jack or el.\n"]},{"cell_type":"markdown","metadata":{},"source":["\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Find the substring in the string. Only the index of the first elment of substring in string will be the output\n","\n","name = \"Michael Jackson\"\n","name.find('el')"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Find the substring in the string.\n","\n","name.find('Jack')"]},{"cell_type":"markdown","metadata":{},"source":["If the sub-string is not in the string then the output is a negative one. For example, the string 'Jasdfasdasdf' is not a substring:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# If cannot find the substring in the string\n","\n","name.find('Jasdfasdasdf')"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["

Quiz on Strings

\n"]},{"cell_type":"markdown","metadata":{},"source":["What is the value of the variable a after the following code is executed?\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute \n","\n","a = \"1\"\n","a"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","\"1\"\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["What is the value of the variable b after the following code is executed?\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","\n","b = \"2\"\n","b"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","\"2\"\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["What is the value of the variable c after the following code is executed?\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute \n","\n","c = a + b\n","c"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","\"12\"\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["Consider the variable d use slicing to print out the first three elements:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","\n","d = \"ABCDEFG\"\n","d[:3]"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","print(d[:3]) \n","\n","# or \n","\n","print(d[0:3])\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["Use a stride value of 2 to print out every second character of the string e:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","\n","e = 'clocrkr1e1c1t'\n","e[::2]"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","print(e[::2])\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["Print out a backslash:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","print(\"\\\\\")\n","print(r'\\ ')"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","print(\"\\\\\\\\\")\n","\n","or\n","\n","print(r\"\\ \")\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["Convert the variable f to uppercase:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","\n","f = \"You are wrong\"\n","f.upper()"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","f.upper()\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n"]},{"cell_type":"markdown","metadata":{},"source":["Consider the variable g, and find the first index of the sub-string snow:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","\n","g = \"Mary had a little lamb Little lamb, little lamb Mary had a little lamb \\\n","Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \\\n","Everywhere that Mary went The lamb was sure to go\""]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Find the substring in the string.\n","g.find('snow')"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","g.find(\"snow\")\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["In the variable g, replace the sub-string Mary with Bob:\n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":["# Write your code below and press Shift+Enter to execute\n","g.replace('Mary', 'Bob')"]},{"cell_type":"markdown","metadata":{},"source":["
Click here for the solution\n","\n","```python\n","g.replace(\"Mary\", \"Bob\")\n","\n","```\n","\n","
\n"]},{"cell_type":"markdown","metadata":{},"source":["
\n","

The last exercise!

\n","

Congratulations, you have completed your first lesson and hands-on lab in Python.\n","


\n"]},{"cell_type":"markdown","metadata":{},"source":["## Author\n","\n","Joseph Santarcangelo\n","\n","## Change Log\n","\n","| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n","| ----------------- | ------- | ---------- | ----------------------------------- |\n","| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n","| 2020-11-11 | 2.1 | Aije | Updated variable names to lowercase |\n","| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n","\n","##

© IBM Corporation 2020. All rights reserved.

\n"]}],"metadata":{"kernelspec":{"display_name":"Python 3.10.5 64-bit","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.10.5"},"vscode":{"interpreter":{"hash":"4680a91a6702f9f4fc404a940ff1aa371c53335c110613442d29ba2eb8adde38"}}},"nbformat":4,"nbformat_minor":2} 2 | -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-2-1-Tuples.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": "
\n \"cognitiveclass.ai\n
\n\n# Tuples in Python\n\nEstimated time needed: **15** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Perform the basics tuple operations in Python, including indexing, slicing and sorting\n", 27 | "metadata": {} 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": "

Table of Contents

\n
\n \n\n
\n\n
\n", 32 | "metadata": {} 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "source": "

About the Dataset

\n", 37 | "metadata": {} 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "Imagine you received album recommendations from your friends and compiled all of the recommendations into a table, with specific information about each album.\n\nThe table has one row for each movie and several columns:\n\n* **artist** - Name of the artist\n* **album** - Name of the album\n* **released_year** - Year the album was released\n* **length_min_sec** - Length of the album (hours,minutes,seconds)\n* **genre** - Genre of the album\n* **music_recording_sales_millions** - Music recording sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n* **claimed_sales_millions** - Album's claimed sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n* **date_released** - Date on which the album was released\n* **soundtrack** - Indicates if the album is the movie soundtrack (Y) or (N)\n* **rating_of_friends** - Indicates the rating from your friends from 1 to 10\n\n
\n
\n\nThe dataset can be seen below:\n\n\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ArtistAlbumReleasedLengthGenreMusic recording sales (millions)Claimed sales (millions)ReleasedSoundtrackRating (friends)
Michael JacksonThriller198200:42:19Pop, rock, R&B466530-Nov-8210.0
AC/DCBack in Black198000:42:11Hard rock26.15025-Jul-808.5
Pink FloydThe Dark Side of the Moon197300:42:49Progressive rock24.24501-Mar-739.5
Whitney HoustonThe Bodyguard199200:57:44Soundtrack/R&B, soul, pop26.15025-Jul-80Y7.0
Meat LoafBat Out of Hell197700:46:33Hard rock, progressive rock20.64321-Oct-777.0
EaglesTheir Greatest Hits (1971-1975)197600:43:08Rock, soft rock, folk rock32.24217-Feb-769.5
Bee GeesSaturday Night Fever19771:15:54Disco20.64015-Nov-77Y9.0
Fleetwood MacRumours197700:40:01Soft rock27.94004-Feb-779.5
\n", 42 | "metadata": {} 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": "
\n", 47 | "metadata": {} 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "source": "

Tuples

\n", 52 | "metadata": {} 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "source": "In Python, there are different data types: string, integer, and float. These data types can all be contained in a tuple as follows:\n", 57 | "metadata": {} 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "source": "\n", 62 | "metadata": {} 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "source": "Now, let us create your first tuple with string, integer and float.\n", 67 | "metadata": {} 68 | }, 69 | { 70 | "cell_type": "code", 71 | "source": "# Create your first tuple\n\ntuple1 = (\"disco\",10,1.2 )\ntuple1", 72 | "metadata": {}, 73 | "execution_count": null, 74 | "outputs": [] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "source": "The type of variable is a **tuple**.\n", 79 | "metadata": {} 80 | }, 81 | { 82 | "cell_type": "code", 83 | "source": "# Print the type of the tuple you created\n\ntype(tuple1)", 84 | "metadata": {}, 85 | "execution_count": null, 86 | "outputs": [] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "source": "

Indexing

\n", 91 | "metadata": {} 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "source": "Each element of a tuple can be accessed via an index. The following table represents the relationship between the index and the items in the tuple. Each element can be obtained by the name of the tuple followed by a square bracket with the index number:\n", 96 | "metadata": {} 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "source": "\n", 101 | "metadata": {} 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "source": "We can print out each value in the tuple:\n", 106 | "metadata": {} 107 | }, 108 | { 109 | "cell_type": "code", 110 | "source": "# Print the variable on each index\n\nprint(tuple1[0])\nprint(tuple1[1])\nprint(tuple1[2])", 111 | "metadata": {}, 112 | "execution_count": null, 113 | "outputs": [] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "source": "We can print out the **type** of each value in the tuple:\n", 118 | "metadata": {} 119 | }, 120 | { 121 | "cell_type": "code", 122 | "source": "# Print the type of value on each index\n\nprint(type(tuple1[0]))\nprint(type(tuple1[1]))\nprint(type(tuple1[2]))", 123 | "metadata": {}, 124 | "execution_count": null, 125 | "outputs": [] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "source": "We can also use negative indexing. We use the same table above with corresponding negative values:\n", 130 | "metadata": {} 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": "\n", 135 | "metadata": {} 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "source": "We can obtain the last element as follows (this time we will not use the print statement to display the values):\n", 140 | "metadata": {} 141 | }, 142 | { 143 | "cell_type": "code", 144 | "source": "# Use negative index to get the value of the last element\n\ntuple1[-1]", 145 | "metadata": {}, 146 | "execution_count": null, 147 | "outputs": [] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "source": "We can display the next two elements as follows:\n", 152 | "metadata": {} 153 | }, 154 | { 155 | "cell_type": "code", 156 | "source": "# Use negative index to get the value of the second last element\n\ntuple1[-2]", 157 | "metadata": {}, 158 | "execution_count": null, 159 | "outputs": [] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "source": "# Use negative index to get the value of the third last element\n\ntuple1[-3]", 164 | "metadata": {}, 165 | "execution_count": null, 166 | "outputs": [] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "source": "

Concatenate Tuples

\n", 171 | "metadata": {} 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "source": "We can concatenate or combine tuples by using the **+** sign:\n", 176 | "metadata": {} 177 | }, 178 | { 179 | "cell_type": "code", 180 | "source": "# Concatenate two tuples\n\ntuple2 = tuple1 + (\"hard rock\", 10)\ntuple2", 181 | "metadata": {}, 182 | "execution_count": null, 183 | "outputs": [] 184 | }, 185 | { 186 | "cell_type": "markdown", 187 | "source": "We can slice tuples obtaining multiple values as demonstrated by the figure below:\n", 188 | "metadata": {} 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "source": "\n", 193 | "metadata": {} 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "source": "

Slicing

\n", 198 | "metadata": {} 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "source": "We can slice tuples, obtaining new tuples with the corresponding elements:\n", 203 | "metadata": {} 204 | }, 205 | { 206 | "cell_type": "code", 207 | "source": "# Slice from index 0 to index 2\n\ntuple2[0:3]", 208 | "metadata": {}, 209 | "execution_count": null, 210 | "outputs": [] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "source": "We can obtain the last two elements of the tuple:\n", 215 | "metadata": {} 216 | }, 217 | { 218 | "cell_type": "code", 219 | "source": "# Slice from index 3 to index 4\n\ntuple2[3:5]", 220 | "metadata": {}, 221 | "execution_count": null, 222 | "outputs": [] 223 | }, 224 | { 225 | "cell_type": "markdown", 226 | "source": "We can obtain the length of a tuple using the length command:\n", 227 | "metadata": {} 228 | }, 229 | { 230 | "cell_type": "code", 231 | "source": "# Get the length of tuple\n\nlen(tuple2)", 232 | "metadata": {}, 233 | "execution_count": null, 234 | "outputs": [] 235 | }, 236 | { 237 | "cell_type": "markdown", 238 | "source": "This figure shows the number of elements:\n", 239 | "metadata": {} 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "source": "\n", 244 | "metadata": {} 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "source": "

Sorting

\n", 249 | "metadata": {} 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "source": "Consider the following tuple:\n", 254 | "metadata": {} 255 | }, 256 | { 257 | "cell_type": "code", 258 | "source": "# A sample tuple\n\nRatings = (0, 9, 6, 5, 10, 8, 9, 6, 2)", 259 | "metadata": { 260 | "tags": [] 261 | }, 262 | "execution_count": null, 263 | "outputs": [] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "source": "We can sort the values in a tuple and save it to a new tuple:\n", 268 | "metadata": {} 269 | }, 270 | { 271 | "cell_type": "code", 272 | "source": "# Sort the tuple\n\nRatingsSorted = sorted(Ratings)\nRatingsSorted", 273 | "metadata": {}, 274 | "execution_count": null, 275 | "outputs": [] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "source": "

Nested Tuple

\n", 280 | "metadata": {} 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "source": "A tuple can contain another tuple as well as other more complex data types. This process is called 'nesting'. Consider the following tuple with several elements:\n", 285 | "metadata": {} 286 | }, 287 | { 288 | "cell_type": "code", 289 | "source": "# Create a nest tuple\n\nNestedT =(1, 2, (\"pop\", \"rock\") ,(3,4),(\"disco\",(1,2)))", 290 | "metadata": { 291 | "collapsed": true, 292 | "jupyter": { 293 | "outputs_hidden": true 294 | } 295 | }, 296 | "execution_count": null, 297 | "outputs": [] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "source": "Each element in the tuple, including other tuples, can be obtained via an index as shown in the figure:\n", 302 | "metadata": {} 303 | }, 304 | { 305 | "cell_type": "markdown", 306 | "source": "\n", 307 | "metadata": {} 308 | }, 309 | { 310 | "cell_type": "code", 311 | "source": "# Print element on each index\n\nprint(\"Element 0 of Tuple: \", NestedT[0])\nprint(\"Element 1 of Tuple: \", NestedT[1])\nprint(\"Element 2 of Tuple: \", NestedT[2])\nprint(\"Element 3 of Tuple: \", NestedT[3])\nprint(\"Element 4 of Tuple: \", NestedT[4])", 312 | "metadata": {}, 313 | "execution_count": null, 314 | "outputs": [] 315 | }, 316 | { 317 | "cell_type": "markdown", 318 | "source": "We can use the second index to access other tuples as demonstrated in the figure:\n", 319 | "metadata": {} 320 | }, 321 | { 322 | "cell_type": "markdown", 323 | "source": "\n", 324 | "metadata": {} 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "source": "We can access the nested tuples:\n", 329 | "metadata": {} 330 | }, 331 | { 332 | "cell_type": "code", 333 | "source": "# Print element on each index, including nest indexes\n\nprint(\"Element 2, 0 of Tuple: \", NestedT[2][0])\nprint(\"Element 2, 1 of Tuple: \", NestedT[2][1])\nprint(\"Element 3, 0 of Tuple: \", NestedT[3][0])\nprint(\"Element 3, 1 of Tuple: \", NestedT[3][1])\nprint(\"Element 4, 0 of Tuple: \", NestedT[4][0])\nprint(\"Element 4, 1 of Tuple: \", NestedT[4][1])", 334 | "metadata": {}, 335 | "execution_count": null, 336 | "outputs": [] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "source": "We can access strings in the second nested tuples using a third index:\n", 341 | "metadata": {} 342 | }, 343 | { 344 | "cell_type": "code", 345 | "source": "# Print the first element in the second nested tuples\n\nNestedT[2][1][0]", 346 | "metadata": {}, 347 | "execution_count": null, 348 | "outputs": [] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "source": "# Print the second element in the second nested tuples\n\nNestedT[2][1][1]", 353 | "metadata": {}, 354 | "execution_count": null, 355 | "outputs": [] 356 | }, 357 | { 358 | "cell_type": "markdown", 359 | "source": "We can use a tree to visualise the process. Each new index corresponds to a deeper level in the tree:\n", 360 | "metadata": {} 361 | }, 362 | { 363 | "cell_type": "markdown", 364 | "source": "\n", 365 | "metadata": {} 366 | }, 367 | { 368 | "cell_type": "markdown", 369 | "source": "Similarly, we can access elements nested deeper in the tree with a third index:\n", 370 | "metadata": {} 371 | }, 372 | { 373 | "cell_type": "code", 374 | "source": "# Print the first element in the second nested tuples\n\nNestedT[4][1][0]", 375 | "metadata": {}, 376 | "execution_count": null, 377 | "outputs": [] 378 | }, 379 | { 380 | "cell_type": "code", 381 | "source": "# Print the second element in the second nested tuples\n\nNestedT[4][1][1]", 382 | "metadata": {}, 383 | "execution_count": null, 384 | "outputs": [] 385 | }, 386 | { 387 | "cell_type": "markdown", 388 | "source": "The following figure shows the relationship of the tree and the element NestedT\\[4]\\[1]\\[1]:\n", 389 | "metadata": {} 390 | }, 391 | { 392 | "cell_type": "markdown", 393 | "source": "\n", 394 | "metadata": {} 395 | }, 396 | { 397 | "cell_type": "markdown", 398 | "source": "

Quiz on Tuples

\n", 399 | "metadata": {} 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "source": "Consider the following tuple:\n", 404 | "metadata": {} 405 | }, 406 | { 407 | "cell_type": "code", 408 | "source": "# sample tuple\n\ngenres_tuple = (\"pop\", \"rock\", \"soul\", \"hard rock\", \"soft rock\", \\\n \"R&B\", \"progressive rock\", \"disco\") \ngenres_tuple", 409 | "metadata": {}, 410 | "execution_count": null, 411 | "outputs": [] 412 | }, 413 | { 414 | "cell_type": "markdown", 415 | "source": "Find the length of the tuple, genres_tuple:\n", 416 | "metadata": {} 417 | }, 418 | { 419 | "cell_type": "code", 420 | "source": "# Write your code below and press Shift+Enter to execute\nlen(genres_tuple)", 421 | "metadata": {}, 422 | "execution_count": null, 423 | "outputs": [] 424 | }, 425 | { 426 | "cell_type": "markdown", 427 | "source": "\n", 428 | "metadata": {} 429 | }, 430 | { 431 | "cell_type": "markdown", 432 | "source": "
Click here for the solution\n\n```python\nlen(genres_tuple)\n```\n\n
\n", 433 | "metadata": {} 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "source": "Access the element, with respect to index 3:\n", 438 | "metadata": {} 439 | }, 440 | { 441 | "cell_type": "code", 442 | "source": "# Write your code below and press Shift+Enter to execute\ngenres_tuple[3]", 443 | "metadata": {}, 444 | "execution_count": null, 445 | "outputs": [] 446 | }, 447 | { 448 | "cell_type": "markdown", 449 | "source": "
Click here for the solution\n\n```python\ngenres_tuple[3]\n\n```\n\n
\n", 450 | "metadata": {} 451 | }, 452 | { 453 | "cell_type": "markdown", 454 | "source": "Use slicing to obtain indexes 3, 4 and 5:\n", 455 | "metadata": {} 456 | }, 457 | { 458 | "cell_type": "code", 459 | "source": "# Write your code below and press Shift+Enter to execute\ngenres_tuple[3:6]", 460 | "metadata": {}, 461 | "execution_count": null, 462 | "outputs": [] 463 | }, 464 | { 465 | "cell_type": "markdown", 466 | "source": "
Click here for the solution\n\n```python\ngenres_tuple[3:6]\n\n```\n\n
\n", 467 | "metadata": {} 468 | }, 469 | { 470 | "cell_type": "markdown", 471 | "source": "Find the first two elements of the tuple genres_tuple:\n", 472 | "metadata": {} 473 | }, 474 | { 475 | "cell_type": "code", 476 | "source": "# Write your code below and press Shift+Enter to execute\ngenres_tuple[:2]", 477 | "metadata": {}, 478 | "execution_count": null, 479 | "outputs": [] 480 | }, 481 | { 482 | "cell_type": "markdown", 483 | "source": "
Click here for the solution\n\n```python\ngenres_tuple[0:2]\n\n```\n\n
\n", 484 | "metadata": {} 485 | }, 486 | { 487 | "cell_type": "markdown", 488 | "source": "Find the first index of \"disco\":\n", 489 | "metadata": {} 490 | }, 491 | { 492 | "cell_type": "code", 493 | "source": "# Write your code below and press Shift+Enter to execute\ngenres_tuple.index('disco')", 494 | "metadata": {}, 495 | "execution_count": null, 496 | "outputs": [] 497 | }, 498 | { 499 | "cell_type": "markdown", 500 | "source": "
Click here for the solution\n\n```python\ngenres_tuple.index(\"disco\")\n\n```\n\n
\n", 501 | "metadata": {} 502 | }, 503 | { 504 | "cell_type": "markdown", 505 | "source": "Generate a sorted List from the Tuple C_tuple=(-5, 1, -3):\n", 506 | "metadata": {} 507 | }, 508 | { 509 | "cell_type": "code", 510 | "source": "# Write your code below and press Shift+Enter to execute\nC_tuple=(-5, 1, -3)\nC_list = sorted(C_tuple)\nC_list", 511 | "metadata": {}, 512 | "execution_count": null, 513 | "outputs": [] 514 | }, 515 | { 516 | "cell_type": "markdown", 517 | "source": "
Click here for the solution\n\n```python\nC_tuple = (-5, 1, -3)\nC_list = sorted(C_tuple)\nC_list\n\n```\n\n
\n", 518 | "metadata": {} 519 | }, 520 | { 521 | "cell_type": "markdown", 522 | "source": "## Author\n\nJoseph Santarcangelo\n\n## Other contributors\n\nMavis Zhou\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ---------------------------------- |\n| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 523 | "metadata": {} 524 | } 525 | ] 526 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-2-2-Lists.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "
\n", 8 | " \"cognitiveclass.ai\n", 9 | "
\n", 10 | "\n", 11 | "# Lists in Python\n", 12 | "\n", 13 | "Estimated time needed: **15** minutes\n", 14 | "\n", 15 | "## Objectives\n", 16 | "\n", 17 | "After completing this lab you will be able to:\n", 18 | "\n", 19 | "* Perform list operations in Python, including indexing, list manipulation, and copy/clone list.\n" 20 | ] 21 | }, 22 | { 23 | "cell_type": "markdown", 24 | "metadata": {}, 25 | "source": [ 26 | "

Table of Contents

\n", 27 | "
\n", 28 | " \n", 45 | "\n", 46 | "
\n", 47 | "\n", 48 | "
\n" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "

About the Dataset

\n" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "metadata": {}, 61 | "source": [ 62 | "Imagine you received album recommendations from your friends and compiled all of the recommandations into a table, with specific information about each album.\n", 63 | "\n", 64 | "The table has one row for each movie and several columns:\n", 65 | "\n", 66 | "* **artist** - Name of the artist\n", 67 | "* **album** - Name of the album\n", 68 | "* **released_year** - Year the album was released\n", 69 | "* **length_min_sec** - Length of the album (hours,minutes,seconds)\n", 70 | "* **genre** - Genre of the album\n", 71 | "* **music_recording_sales_millions** - Music recording sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n", 72 | "* **claimed_sales_millions** - Album's claimed sales (millions in USD) on [SONG://DATABASE](http://www.song-database.com/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2021-01-01)\n", 73 | "* **date_released** - Date on which the album was released\n", 74 | "* **soundtrack** - Indicates if the album is the movie soundtrack (Y) or (N)\n", 75 | "* **rating_of_friends** - Indicates the rating from your friends from 1 to 10\n", 76 | "\n", 77 | "
\n", 78 | "
\n", 79 | "\n", 80 | "The dataset can be seen below:\n", 81 | "\n", 82 | "\n", 83 | "\n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | "
ArtistAlbumReleasedLengthGenreMusic recording sales (millions)Claimed sales (millions)ReleasedSoundtrackRating (friends)
Michael JacksonThriller198200:42:19Pop, rock, R&B466530-Nov-8210.0
AC/DCBack in Black198000:42:11Hard rock26.15025-Jul-808.5
Pink FloydThe Dark Side of the Moon197300:42:49Progressive rock24.24501-Mar-739.5
Whitney HoustonThe Bodyguard199200:57:44Soundtrack/R&B, soul, pop26.15025-Jul-80Y7.0
Meat LoafBat Out of Hell197700:46:33Hard rock, progressive rock20.64321-Oct-777.0
EaglesTheir Greatest Hits (1971-1975)197600:43:08Rock, soft rock, folk rock32.24217-Feb-769.5
Bee GeesSaturday Night Fever19771:15:54Disco20.64015-Nov-77Y9.0
Fleetwood MacRumours197700:40:01Soft rock27.94004-Feb-779.5
\n" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "metadata": {}, 198 | "source": [ 199 | "
\n" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "metadata": {}, 205 | "source": [ 206 | "

Lists

\n" 207 | ] 208 | }, 209 | { 210 | "cell_type": "markdown", 211 | "metadata": {}, 212 | "source": [ 213 | "

Indexing

\n" 214 | ] 215 | }, 216 | { 217 | "cell_type": "markdown", 218 | "metadata": {}, 219 | "source": [ 220 | "We are going to take a look at lists in Python. A list is a sequenced collection of different objects such as integers, strings, and even other lists as well. The address of each element within a list is called an index. An index is used to access and refer to items within a list.\n" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "metadata": {}, 226 | "source": [ 227 | "\n" 228 | ] 229 | }, 230 | { 231 | "cell_type": "markdown", 232 | "metadata": {}, 233 | "source": [ 234 | "To create a list, type the list within square brackets \\[ ], with your content inside the parenthesis and separated by commas. Let’s try it!\n" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "metadata": { 241 | "trusted": true 242 | }, 243 | "outputs": [], 244 | "source": [ 245 | "# Create a list\n", 246 | "\n", 247 | "L = [\"Michael Jackson\", 10.1, 1982]\n", 248 | "L" 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": {}, 254 | "source": [ 255 | "We can use negative and regular indexing with a list:\n" 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": {}, 261 | "source": [ 262 | "\n" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": null, 268 | "metadata": { 269 | "trusted": true 270 | }, 271 | "outputs": [], 272 | "source": [ 273 | "# Print the elements on each index\n", 274 | "\n", 275 | "print('the same element using negative and positive indexing:\\n Postive:',L[0],\n", 276 | "'\\n Negative:' , L[-3] )\n", 277 | "print('the same element using negative and positive indexing:\\n Postive:',L[1],\n", 278 | "'\\n Negative:' , L[-2] )\n", 279 | "print('the same element using negative and positive indexing:\\n Postive:',L[2],\n", 280 | "'\\n Negative:' , L[-1] )" 281 | ] 282 | }, 283 | { 284 | "cell_type": "markdown", 285 | "metadata": {}, 286 | "source": [ 287 | "

List Content

\n" 288 | ] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "metadata": {}, 293 | "source": [ 294 | "Lists can contain strings, floats, and integers. We can nest other lists, and we can also nest tuples and other data structures. The same indexing conventions apply for nesting:\n" 295 | ] 296 | }, 297 | { 298 | "cell_type": "code", 299 | "execution_count": null, 300 | "metadata": { 301 | "trusted": true 302 | }, 303 | "outputs": [], 304 | "source": [ 305 | "# Sample List\n", 306 | "\n", 307 | "[\"Michael Jackson\", 10.1, 1982, [1, 2], (\"A\", 1)]" 308 | ] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "metadata": {}, 313 | "source": [ 314 | "

List Operations

\n" 315 | ] 316 | }, 317 | { 318 | "cell_type": "markdown", 319 | "metadata": {}, 320 | "source": [ 321 | "We can also perform slicing in lists. For example, if we want the last two elements, we use the following command:\n" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "metadata": { 328 | "trusted": true 329 | }, 330 | "outputs": [], 331 | "source": [ 332 | "# Sample List\n", 333 | "\n", 334 | "L = [\"Michael Jackson\", 10.1,1982,\"MJ\",1]\n", 335 | "L" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "metadata": {}, 341 | "source": [ 342 | "\n" 343 | ] 344 | }, 345 | { 346 | "cell_type": "code", 347 | "execution_count": null, 348 | "metadata": { 349 | "trusted": true 350 | }, 351 | "outputs": [], 352 | "source": [ 353 | "# List slicing\n", 354 | "\n", 355 | "L[3:5]" 356 | ] 357 | }, 358 | { 359 | "cell_type": "markdown", 360 | "metadata": {}, 361 | "source": [ 362 | "We can use the method extend to add new elements to the list:\n" 363 | ] 364 | }, 365 | { 366 | "cell_type": "code", 367 | "execution_count": null, 368 | "metadata": { 369 | "trusted": true 370 | }, 371 | "outputs": [], 372 | "source": [ 373 | "# Use extend to add elements to list\n", 374 | "\n", 375 | "L = [ \"Michael Jackson\", 10.2]\n", 376 | "L.extend(['pop', 10])\n", 377 | "L" 378 | ] 379 | }, 380 | { 381 | "cell_type": "markdown", 382 | "metadata": {}, 383 | "source": [ 384 | "Another similar method is append. If we apply append instead of extend, we add one element to the list:\n" 385 | ] 386 | }, 387 | { 388 | "cell_type": "code", 389 | "execution_count": null, 390 | "metadata": { 391 | "trusted": true 392 | }, 393 | "outputs": [], 394 | "source": [ 395 | "# Use append to add elements to list\n", 396 | "\n", 397 | "L = [ \"Michael Jackson\", 10.2]\n", 398 | "L.append(['pop', 10])\n", 399 | "L" 400 | ] 401 | }, 402 | { 403 | "cell_type": "markdown", 404 | "metadata": {}, 405 | "source": [ 406 | "Each time we apply a method, the list changes. If we apply extend we add two new elements to the list. The list L is then modified by adding two new elements:\n" 407 | ] 408 | }, 409 | { 410 | "cell_type": "code", 411 | "execution_count": null, 412 | "metadata": { 413 | "trusted": true 414 | }, 415 | "outputs": [], 416 | "source": [ 417 | "# Use extend to add elements to list\n", 418 | "\n", 419 | "L = [ \"Michael Jackson\", 10.2]\n", 420 | "L.extend(['pop', 10])\n", 421 | "L" 422 | ] 423 | }, 424 | { 425 | "cell_type": "markdown", 426 | "metadata": {}, 427 | "source": [ 428 | "If we append the list \\['a','b'] we have one new element consisting of a nested list:\n" 429 | ] 430 | }, 431 | { 432 | "cell_type": "code", 433 | "execution_count": null, 434 | "metadata": { 435 | "trusted": true 436 | }, 437 | "outputs": [], 438 | "source": [ 439 | "# Use append to add elements to list\n", 440 | "\n", 441 | "L.append(['a','b'])\n", 442 | "L" 443 | ] 444 | }, 445 | { 446 | "cell_type": "markdown", 447 | "metadata": {}, 448 | "source": [ 449 | "As lists are mutable, we can change them. For example, we can change the first element as follows:\n" 450 | ] 451 | }, 452 | { 453 | "cell_type": "code", 454 | "execution_count": null, 455 | "metadata": { 456 | "trusted": true 457 | }, 458 | "outputs": [], 459 | "source": [ 460 | "# Change the element based on the index\n", 461 | "\n", 462 | "A = [\"disco\", 10, 1.2]\n", 463 | "print('Before change:', A)\n", 464 | "A[0] = 'hard rock'\n", 465 | "print('After change:', A)" 466 | ] 467 | }, 468 | { 469 | "cell_type": "markdown", 470 | "metadata": {}, 471 | "source": [ 472 | "We can also delete an element of a list using the del command:\n" 473 | ] 474 | }, 475 | { 476 | "cell_type": "code", 477 | "execution_count": null, 478 | "metadata": { 479 | "trusted": true 480 | }, 481 | "outputs": [], 482 | "source": [ 483 | "# Delete the element based on the index\n", 484 | "\n", 485 | "print('Before change:', A)\n", 486 | "del(A[0])\n", 487 | "print('After change:', A)" 488 | ] 489 | }, 490 | { 491 | "cell_type": "markdown", 492 | "metadata": {}, 493 | "source": [ 494 | "We can convert a string to a list using split. For example, the method split translates every group of characters separated by a space into an element in a list:\n" 495 | ] 496 | }, 497 | { 498 | "cell_type": "code", 499 | "execution_count": null, 500 | "metadata": { 501 | "trusted": true 502 | }, 503 | "outputs": [], 504 | "source": [ 505 | "# Split the string, default is by space\n", 506 | "\n", 507 | "'hard rock'.split()" 508 | ] 509 | }, 510 | { 511 | "cell_type": "markdown", 512 | "metadata": {}, 513 | "source": [ 514 | "We can use the split function to separate strings on a specific character which we call a **delimiter**. We pass the character we would like to split on into the argument, which in this case is a comma. The result is a list, and each element corresponds to a set of characters that have been separated by a comma:\n" 515 | ] 516 | }, 517 | { 518 | "cell_type": "code", 519 | "execution_count": null, 520 | "metadata": { 521 | "trusted": true 522 | }, 523 | "outputs": [], 524 | "source": [ 525 | "# Split the string by comma\n", 526 | "\n", 527 | "'A,B,C,D'.split(',')" 528 | ] 529 | }, 530 | { 531 | "cell_type": "markdown", 532 | "metadata": {}, 533 | "source": [ 534 | "

Copy and Clone List

\n" 535 | ] 536 | }, 537 | { 538 | "cell_type": "markdown", 539 | "metadata": {}, 540 | "source": [ 541 | "When we set one variable B equal to A, both A and B are referencing the same list in memory:\n" 542 | ] 543 | }, 544 | { 545 | "cell_type": "code", 546 | "execution_count": null, 547 | "metadata": { 548 | "trusted": true 549 | }, 550 | "outputs": [], 551 | "source": [ 552 | "# Copy (copy by reference) the list A\n", 553 | "\n", 554 | "A = [\"hard rock\", 10, 1.2]\n", 555 | "B = A\n", 556 | "print('A:', A)\n", 557 | "print('B:', B)" 558 | ] 559 | }, 560 | { 561 | "cell_type": "markdown", 562 | "metadata": {}, 563 | "source": [ 564 | "\n" 565 | ] 566 | }, 567 | { 568 | "cell_type": "markdown", 569 | "metadata": {}, 570 | "source": [ 571 | "Initially, the value of the first element in B is set as \"hard rock\". If we change the first element in A to \"banana\", we get an unexpected side effect. As A and B are referencing the same list, if we change list A, then list B also changes. If we check the first element of B we get \"banana\" instead of \"hard rock\":\n" 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": null, 577 | "metadata": { 578 | "trusted": true 579 | }, 580 | "outputs": [], 581 | "source": [ 582 | "# Examine the copy by reference\n", 583 | "\n", 584 | "print('B[0]:', B[0])\n", 585 | "A[0] = \"banana\"\n", 586 | "print('B[0]:', B[0])" 587 | ] 588 | }, 589 | { 590 | "cell_type": "markdown", 591 | "metadata": {}, 592 | "source": [ 593 | "This is demonstrated in the following figure:\n" 594 | ] 595 | }, 596 | { 597 | "cell_type": "markdown", 598 | "metadata": {}, 599 | "source": [ 600 | "\n" 601 | ] 602 | }, 603 | { 604 | "cell_type": "markdown", 605 | "metadata": {}, 606 | "source": [ 607 | "You can clone list **A** by using the following syntax:\n" 608 | ] 609 | }, 610 | { 611 | "cell_type": "code", 612 | "execution_count": null, 613 | "metadata": { 614 | "trusted": true 615 | }, 616 | "outputs": [], 617 | "source": [ 618 | "# Clone (clone by value) the list A\n", 619 | "\n", 620 | "B = A[:]\n", 621 | "B" 622 | ] 623 | }, 624 | { 625 | "cell_type": "markdown", 626 | "metadata": {}, 627 | "source": [ 628 | "Variable **B** references a new copy or clone of the original list. This is demonstrated in the following figure:\n" 629 | ] 630 | }, 631 | { 632 | "cell_type": "markdown", 633 | "metadata": {}, 634 | "source": [ 635 | "\n" 636 | ] 637 | }, 638 | { 639 | "cell_type": "markdown", 640 | "metadata": {}, 641 | "source": [ 642 | "Now if you change A, B will not change:\n" 643 | ] 644 | }, 645 | { 646 | "cell_type": "code", 647 | "execution_count": null, 648 | "metadata": { 649 | "trusted": true 650 | }, 651 | "outputs": [], 652 | "source": [ 653 | "print('B[0]:', B[0])\n", 654 | "A[0] = \"hard rock\"\n", 655 | "print('B[0]:', B[0])" 656 | ] 657 | }, 658 | { 659 | "cell_type": "markdown", 660 | "metadata": {}, 661 | "source": [ 662 | "

Quiz on List

\n" 663 | ] 664 | }, 665 | { 666 | "cell_type": "markdown", 667 | "metadata": {}, 668 | "source": [ 669 | "Create a list a_list, with the following elements 1, hello, \\[1,2,3] and True.\n" 670 | ] 671 | }, 672 | { 673 | "cell_type": "code", 674 | "execution_count": null, 675 | "metadata": { 676 | "trusted": true 677 | }, 678 | "outputs": [], 679 | "source": [ 680 | "# Write your code below and press Shift+Enter to execute\n", 681 | "a_list = [1, 'hello', [1,2,3], True]\n", 682 | "a_list" 683 | ] 684 | }, 685 | { 686 | "cell_type": "markdown", 687 | "metadata": {}, 688 | "source": [ 689 | "
Click here for the solution\n", 690 | "\n", 691 | "```python\n", 692 | "a_list = [1, 'hello', [1, 2, 3] , True]\n", 693 | "a_list\n", 694 | "\n", 695 | "```\n", 696 | "\n", 697 | "
\n" 698 | ] 699 | }, 700 | { 701 | "cell_type": "markdown", 702 | "metadata": {}, 703 | "source": [ 704 | "Find the value stored at index 1 of a_list.\n" 705 | ] 706 | }, 707 | { 708 | "cell_type": "code", 709 | "execution_count": null, 710 | "metadata": { 711 | "trusted": true 712 | }, 713 | "outputs": [], 714 | "source": [ 715 | "# Write your code below and press Shift+Enter to execute\n", 716 | "a_list[1]" 717 | ] 718 | }, 719 | { 720 | "cell_type": "markdown", 721 | "metadata": {}, 722 | "source": [ 723 | "
Click here for the solution\n", 724 | "\n", 725 | "```python\n", 726 | "a_list[1]\n", 727 | "\n", 728 | "```\n", 729 | "\n", 730 | "
\n" 731 | ] 732 | }, 733 | { 734 | "cell_type": "markdown", 735 | "metadata": {}, 736 | "source": [ 737 | "Retrieve the elements stored at index 1, 2 and 3 of a_list.\n" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": null, 743 | "metadata": { 744 | "trusted": true 745 | }, 746 | "outputs": [], 747 | "source": [ 748 | "# Write your code below and press Shift+Enter to execute\n", 749 | "a_list[1:4]" 750 | ] 751 | }, 752 | { 753 | "cell_type": "markdown", 754 | "metadata": {}, 755 | "source": [ 756 | "
Click here for the solution\n", 757 | "\n", 758 | "```python\n", 759 | "a_list[1:4]\n", 760 | "\n", 761 | "```\n", 762 | "\n", 763 | "
\n" 764 | ] 765 | }, 766 | { 767 | "cell_type": "markdown", 768 | "metadata": {}, 769 | "source": [ 770 | "Concatenate the following lists A = \\[1, 'a'] and B = \\[2, 1, 'd']:\n" 771 | ] 772 | }, 773 | { 774 | "cell_type": "code", 775 | "execution_count": null, 776 | "metadata": { 777 | "trusted": true 778 | }, 779 | "outputs": [], 780 | "source": [ 781 | "# Write your code below and press Shift+Enter to execute\n", 782 | "A = [1, 'a']\n", 783 | "B = [2, 1, 'd']\n", 784 | "A+B" 785 | ] 786 | }, 787 | { 788 | "cell_type": "markdown", 789 | "metadata": {}, 790 | "source": [ 791 | "
Click here for the solution\n", 792 | "\n", 793 | "```python\n", 794 | "A = [1, 'a'] \n", 795 | "B = [2, 1, 'd']\n", 796 | "A + B\n", 797 | "\n", 798 | "```\n", 799 | "\n", 800 | "
\n" 801 | ] 802 | }, 803 | { 804 | "cell_type": "markdown", 805 | "metadata": {}, 806 | "source": [ 807 | "
\n", 808 | "

The last exercise!

\n", 809 | "

Congratulations, you have completed your first lesson and hands-on lab in Python. \n", 810 | "


\n" 811 | ] 812 | }, 813 | { 814 | "cell_type": "markdown", 815 | "metadata": {}, 816 | "source": [ 817 | "## Author\n", 818 | "\n", 819 | "Joseph Santarcangelo\n", 820 | "\n", 821 | "## Other contributors\n", 822 | "\n", 823 | "Mavis Zhou\n", 824 | "\n", 825 | "## Change Log\n", 826 | "\n", 827 | "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n", 828 | "| ----------------- | ------- | ---------- | ---------------------------------- |\n", 829 | "| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n", 830 | "| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n", 831 | "| | | | |\n", 832 | "| | | | |\n", 833 | "\n", 834 | "##

© IBM Corporation 2020. All rights reserved.

\n" 835 | ] 836 | } 837 | ], 838 | "metadata": { 839 | "kernelspec": { 840 | "display_name": "Python 3.10.5 64-bit", 841 | "language": "python", 842 | "name": "python3" 843 | }, 844 | "language_info": { 845 | "codemirror_mode": { 846 | "name": "ipython", 847 | "version": 3 848 | }, 849 | "file_extension": ".py", 850 | "mimetype": "text/x-python", 851 | "name": "python", 852 | "nbconvert_exporter": "python", 853 | "pygments_lexer": "ipython3", 854 | "version": "3.10.5" 855 | }, 856 | "vscode": { 857 | "interpreter": { 858 | "hash": "4680a91a6702f9f4fc404a940ff1aa371c53335c110613442d29ba2eb8adde38" 859 | } 860 | } 861 | }, 862 | "nbformat": 4, 863 | "nbformat_minor": 4 864 | } 865 | -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-2-4-Dictionaries.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": "
\n \"cognitiveclass.ai\n
\n\n# Dictionaries in Python\n\nEstimated time needed: **25** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Work with and perform operations on dictionaries in Python\n", 27 | "metadata": {} 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": "

Table of Contents

\n
\n \n\n
\n\n
\n", 32 | "metadata": {} 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "source": "

Dictionaries

\n", 37 | "metadata": {} 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "

What are Dictionaries?

\n", 42 | "metadata": {} 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": "A dictionary consists of keys and values. It is helpful to compare a dictionary to a list. Instead of being indexed numerically like a list, dictionaries have keys. These keys are the keys that are used to access values within a dictionary.\n", 47 | "metadata": {} 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "source": "\n", 52 | "metadata": {} 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "source": "An example of a Dictionary Dict:\n", 57 | "metadata": {} 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": "# Create the dictionary\n\nDict = {\"key1\": 1, \"key2\": \"2\", \"key3\": [3, 3, 3], \"key4\": (4, 4, 4), ('key5'): 5, (0, 1): 6}\nDict", 62 | "metadata": { 63 | "jupyter": { 64 | "outputs_hidden": false 65 | }, 66 | "collapsed": false 67 | }, 68 | "execution_count": null, 69 | "outputs": [] 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "source": "The keys can be strings:\n", 74 | "metadata": {} 75 | }, 76 | { 77 | "cell_type": "code", 78 | "source": "# Access to the value by the key\n\nDict[\"key1\"]", 79 | "metadata": { 80 | "jupyter": { 81 | "outputs_hidden": false 82 | }, 83 | "collapsed": false 84 | }, 85 | "execution_count": null, 86 | "outputs": [] 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "source": "Keys can also be any immutable object such as a tuple:\n", 91 | "metadata": {} 92 | }, 93 | { 94 | "cell_type": "code", 95 | "source": "# Access to the value by the key\n\nDict[(0, 1)]", 96 | "metadata": { 97 | "jupyter": { 98 | "outputs_hidden": false 99 | }, 100 | "collapsed": false 101 | }, 102 | "execution_count": null, 103 | "outputs": [] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "source": "Each key is separated from its value by a colon \":\". Commas separate the items, and the whole dictionary is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this \"{}\".\n", 108 | "metadata": {} 109 | }, 110 | { 111 | "cell_type": "code", 112 | "source": "# Create a sample dictionary\n\nrelease_year_dict = {\"Thriller\": \"1982\", \"Back in Black\": \"1980\", \\\n \"The Dark Side of the Moon\": \"1973\", \"The Bodyguard\": \"1992\", \\\n \"Bat Out of Hell\": \"1977\", \"Their Greatest Hits (1971-1975)\": \"1976\", \\\n \"Saturday Night Fever\": \"1977\", \"Rumours\": \"1977\"}\nrelease_year_dict", 113 | "metadata": { 114 | "jupyter": { 115 | "outputs_hidden": false 116 | }, 117 | "collapsed": false 118 | }, 119 | "execution_count": null, 120 | "outputs": [] 121 | }, 122 | { 123 | "cell_type": "markdown", 124 | "source": "In summary, like a list, a dictionary holds a sequence of elements. Each element is represented by a key and its corresponding value. Dictionaries are created with two curly braces containing keys and values separated by a colon. For every key, there can only be one single value, however, multiple keys can hold the same value. Keys can only be strings, numbers, or tuples, but values can be any data type.\n", 125 | "metadata": {} 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "source": "It is helpful to visualize the dictionary as a table, as in the following image. The first column represents the keys, the second column represents the values.\n", 130 | "metadata": {} 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": "\n", 135 | "metadata": {} 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "source": "

Keys

\n", 140 | "metadata": {} 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "source": "You can retrieve the values based on the names:\n", 145 | "metadata": {} 146 | }, 147 | { 148 | "cell_type": "code", 149 | "source": "# Get value by keys\n\nrelease_year_dict['Thriller'] ", 150 | "metadata": { 151 | "jupyter": { 152 | "outputs_hidden": false 153 | }, 154 | "collapsed": false 155 | }, 156 | "execution_count": null, 157 | "outputs": [] 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "source": "This corresponds to:\n", 162 | "metadata": {} 163 | }, 164 | { 165 | "cell_type": "markdown", 166 | "source": "\n", 167 | "metadata": {} 168 | }, 169 | { 170 | "cell_type": "markdown", 171 | "source": "Similarly for The Bodyguard\n", 172 | "metadata": {} 173 | }, 174 | { 175 | "cell_type": "code", 176 | "source": "# Get value by key\n\nrelease_year_dict['The Bodyguard'] ", 177 | "metadata": { 178 | "jupyter": { 179 | "outputs_hidden": false 180 | }, 181 | "collapsed": false 182 | }, 183 | "execution_count": null, 184 | "outputs": [] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "source": "\n", 189 | "metadata": {} 190 | }, 191 | { 192 | "cell_type": "markdown", 193 | "source": "Now let us retrieve the keys of the dictionary using the method keys():\n", 194 | "metadata": {} 195 | }, 196 | { 197 | "cell_type": "code", 198 | "source": "# Get all the keys in dictionary\n\nrelease_year_dict.keys() ", 199 | "metadata": { 200 | "jupyter": { 201 | "outputs_hidden": false 202 | }, 203 | "collapsed": false 204 | }, 205 | "execution_count": null, 206 | "outputs": [] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "source": "You can retrieve the values using the method values():\n", 211 | "metadata": {} 212 | }, 213 | { 214 | "cell_type": "code", 215 | "source": "# Get all the values in dictionary\n\nrelease_year_dict.values() ", 216 | "metadata": { 217 | "jupyter": { 218 | "outputs_hidden": false 219 | }, 220 | "collapsed": false 221 | }, 222 | "execution_count": null, 223 | "outputs": [] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "source": "We can add an entry:\n", 228 | "metadata": {} 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": "# Append value with key into dictionary\n\nrelease_year_dict['Graduation'] = '2007'\nrelease_year_dict", 233 | "metadata": { 234 | "jupyter": { 235 | "outputs_hidden": false 236 | }, 237 | "collapsed": false 238 | }, 239 | "execution_count": null, 240 | "outputs": [] 241 | }, 242 | { 243 | "cell_type": "markdown", 244 | "source": "We can delete an entry:\n", 245 | "metadata": {} 246 | }, 247 | { 248 | "cell_type": "code", 249 | "source": "# Delete entries by key\n\ndel(release_year_dict['Thriller'])\ndel(release_year_dict['Graduation'])\nrelease_year_dict", 250 | "metadata": { 251 | "jupyter": { 252 | "outputs_hidden": false 253 | }, 254 | "collapsed": false 255 | }, 256 | "execution_count": null, 257 | "outputs": [] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "source": "We can verify if an element is in the dictionary:\n", 262 | "metadata": {} 263 | }, 264 | { 265 | "cell_type": "code", 266 | "source": "# Verify the key is in the dictionary\n\n'The Bodyguard' in release_year_dict", 267 | "metadata": { 268 | "jupyter": { 269 | "outputs_hidden": false 270 | }, 271 | "collapsed": false 272 | }, 273 | "execution_count": null, 274 | "outputs": [] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "source": "
\n", 279 | "metadata": {} 280 | }, 281 | { 282 | "cell_type": "markdown", 283 | "source": "

Quiz on Dictionaries

\n", 284 | "metadata": {} 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "source": "You will need this dictionary for the next two questions:\n", 289 | "metadata": {} 290 | }, 291 | { 292 | "cell_type": "code", 293 | "source": "# Question sample dictionary\n\nsoundtrack_dic = {\"The Bodyguard\":\"1992\", \"Saturday Night Fever\":\"1977\"}\nsoundtrack_dic ", 294 | "metadata": {}, 295 | "execution_count": null, 296 | "outputs": [] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "source": "a) In the dictionary soundtrack_dic what are the keys ?\n", 301 | "metadata": {} 302 | }, 303 | { 304 | "cell_type": "code", 305 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic.keys()", 306 | "metadata": {}, 307 | "execution_count": null, 308 | "outputs": [] 309 | }, 310 | { 311 | "cell_type": "markdown", 312 | "source": "
Click here for the solution\n\n```python\nsoundtrack_dic.keys() # The Keys \"The Bodyguard\" and \"Saturday Night Fever\" \n\n```\n\n
\n", 313 | "metadata": {} 314 | }, 315 | { 316 | "cell_type": "markdown", 317 | "source": "b) In the dictionary soundtrack_dic what are the values ?\n", 318 | "metadata": {} 319 | }, 320 | { 321 | "cell_type": "code", 322 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic.values()", 323 | "metadata": {}, 324 | "execution_count": null, 325 | "outputs": [] 326 | }, 327 | { 328 | "cell_type": "markdown", 329 | "source": "
Click here for the solution\n\n```python\nsoundtrack_dic.values() # The values are \"1992\" and \"1977\"\n\n```\n\n
\n", 330 | "metadata": {} 331 | }, 332 | { 333 | "cell_type": "markdown", 334 | "source": "
\n", 335 | "metadata": {} 336 | }, 337 | { 338 | "cell_type": "markdown", 339 | "source": "You will need this dictionary for the following questions:\n", 340 | "metadata": {} 341 | }, 342 | { 343 | "cell_type": "markdown", 344 | "source": "The Albums Back in Black, The Bodyguard and Thriller have the following music recording sales in millions 50, 50 and 65 respectively:\n", 345 | "metadata": {} 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "source": "a) Create a dictionary album_sales_dict where the keys are the album name and the sales in millions are the values.\n", 350 | "metadata": {} 351 | }, 352 | { 353 | "cell_type": "code", 354 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic = {'Back in Black':50, 'The Bodyguard':50, 'Thriller':50}\nsoundtrack_dic", 355 | "metadata": {}, 356 | "execution_count": null, 357 | "outputs": [] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "source": "
Click here for the solution\n\n```python\nalbum_sales_dict = {\"The Bodyguard\":50, \"Back in Black\":50, \"Thriller\":65}\n\n```\n\n
\n", 362 | "metadata": {} 363 | }, 364 | { 365 | "cell_type": "markdown", 366 | "source": "b) Use the dictionary to find the total sales of Thriller:\n", 367 | "metadata": {} 368 | }, 369 | { 370 | "cell_type": "code", 371 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic['Thriller']", 372 | "metadata": { 373 | "jupyter": { 374 | "outputs_hidden": false 375 | }, 376 | "collapsed": false 377 | }, 378 | "execution_count": null, 379 | "outputs": [] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "source": "
Click here for the solution\n\n```python\nalbum_sales_dict[\"Thriller\"]\n\n```\n\n
\n", 384 | "metadata": {} 385 | }, 386 | { 387 | "cell_type": "markdown", 388 | "source": "c) Find the names of the albums from the dictionary using the method keys():\n", 389 | "metadata": {} 390 | }, 391 | { 392 | "cell_type": "code", 393 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic.keys()", 394 | "metadata": { 395 | "jupyter": { 396 | "outputs_hidden": false 397 | }, 398 | "collapsed": false 399 | }, 400 | "execution_count": null, 401 | "outputs": [] 402 | }, 403 | { 404 | "cell_type": "markdown", 405 | "source": "
Click here for the solution\n\n```python\nalbum_sales_dict.keys()\n\n```\n\n
\n", 406 | "metadata": {} 407 | }, 408 | { 409 | "cell_type": "markdown", 410 | "source": "d) Find the values of the recording sales from the dictionary using the method values:\n", 411 | "metadata": {} 412 | }, 413 | { 414 | "cell_type": "code", 415 | "source": "# Write your code below and press Shift+Enter to execute\nsoundtrack_dic.values()", 416 | "metadata": { 417 | "jupyter": { 418 | "outputs_hidden": false 419 | }, 420 | "collapsed": false 421 | }, 422 | "execution_count": null, 423 | "outputs": [] 424 | }, 425 | { 426 | "cell_type": "markdown", 427 | "source": "
Click here for the solution\n\n```python\nalbum_sales_dict.values()\n\n```\n\n
\n", 428 | "metadata": {} 429 | }, 430 | { 431 | "cell_type": "markdown", 432 | "source": "
\n

The last exercise!

\n

Congratulations, you have completed your first lesson and hands-on lab in Python. \n


\n", 433 | "metadata": {} 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "source": "## Author\n\nJoseph Santarcangelo\n\n## Other contributors\n\nMavis Zhou\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ------------- | ------------------------------------------------------------------- |\n| 2022-01-10 | 2.2 | Malika Singla | Removed the readme for GitShare |\n| 2020-09-09 | 2.1 | Malika Singla | Updated the variable soundtrack_dict to soundtrack_dic in Questions |\n| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 438 | "metadata": {} 439 | } 440 | ] 441 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-3-2-Loops.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | } 20 | }, 21 | "nbformat_minor": 4, 22 | "nbformat": 4, 23 | "cells": [ 24 | { 25 | "cell_type": "markdown", 26 | "source": "
\n \"cognitiveclass.ai\n
\n\n# Loops in Python\n\nEstimated time needed: **20** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* work with the loop statements in Python, including for-loop and while-loop.\n", 27 | "metadata": {} 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "source": "

Loops in Python

\n", 32 | "metadata": {} 33 | }, 34 | { 35 | "cell_type": "markdown", 36 | "source": "

Welcome! This notebook will teach you about the loops in the Python Programming Language. By the end of this lab, you'll know how to use the loop statements in Python, including for loop, and while loop.

\n", 37 | "metadata": {} 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "source": "

Table of Contents

\n
\n \n\n
\n\n
\n", 42 | "metadata": {} 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "source": "

Loops

\n", 47 | "metadata": {} 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "source": "

Range

\n", 52 | "metadata": {} 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "source": "Sometimes, you might want to repeat a given operation many times. Repeated executions like this are performed by loops. We will look at two types of loops, for loops and while loops.\n\nBefore we discuss loops lets discuss the range object. It is helpful to think of the range object as an ordered list. For now, let's look at the simplest case. If we would like to generate an object that contains elements ordered from 0 to 2 we simply use the following command:\n", 57 | "metadata": {} 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": "# Use the range\n\nrange(3)", 62 | "metadata": {}, 63 | "execution_count": null, 64 | "outputs": [] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "source": "\n", 69 | "metadata": {} 70 | }, 71 | { 72 | "cell_type": "markdown", 73 | "source": "***NOTE: While in Python 2.x it returned a list as seen in video lessons, in 3.x it returns a range object.***\n", 74 | "metadata": {} 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "source": "

What is for loop?

\n", 79 | "metadata": {} 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "source": "The for loop enables you to execute a code block multiple times. For example, you would use this if you would like to print out every element in a list.\\\nLet's try to use a for loop to print all the years presented in the list dates:\n", 84 | "metadata": {} 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "source": "This can be done as follows:\n", 89 | "metadata": {} 90 | }, 91 | { 92 | "cell_type": "code", 93 | "source": "# For loop example\n\ndates = [1982,1980,1973]\nN = len(dates)\n\nfor i in range(N):\n print(dates[i]) ", 94 | "metadata": {}, 95 | "execution_count": null, 96 | "outputs": [] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "source": "The code in the indent is executed N times, each time the value of i is increased by 1 for every execution. The statement executed is to print out the value in the list at index i as shown here:\n", 101 | "metadata": {} 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "source": "\n", 106 | "metadata": {} 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "source": "In this example we can print out a sequence of numbers from 0 to 7:\n", 111 | "metadata": {} 112 | }, 113 | { 114 | "cell_type": "code", 115 | "source": "# Example of for loop\n\nfor i in range(0, 8):\n print(i)", 116 | "metadata": {}, 117 | "execution_count": null, 118 | "outputs": [] 119 | }, 120 | { 121 | "cell_type": "markdown", 122 | "source": "In Python we can directly access the elements in the list as follows:\n", 123 | "metadata": {} 124 | }, 125 | { 126 | "cell_type": "code", 127 | "source": "# Exmaple of for loop, loop through list\n\nfor year in dates: \n print(year) ", 128 | "metadata": {}, 129 | "execution_count": null, 130 | "outputs": [] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "source": "For each iteration, the value of the variable year behaves like the value of dates\\[i] in the first example:\n", 135 | "metadata": {} 136 | }, 137 | { 138 | "cell_type": "markdown", 139 | "source": "\n", 140 | "metadata": {} 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "source": "We can change the elements in a list:\n", 145 | "metadata": {} 146 | }, 147 | { 148 | "cell_type": "code", 149 | "source": "# Use for loop to change the elements in list\n\nsquares = ['red', 'yellow', 'green', 'purple', 'blue']\n\nfor i in range(0, 5):\n print(\"Before square \", i, 'is', squares[i])\n squares[i] = 'white'\n print(\"After square \", i, 'is', squares[i])", 150 | "metadata": {}, 151 | "execution_count": null, 152 | "outputs": [] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "source": "We can access the index and the elements of a list as follows:\n", 157 | "metadata": {} 158 | }, 159 | { 160 | "cell_type": "code", 161 | "source": "# Loop through the list and iterate on both index and element value\n\nsquares=['red', 'yellow', 'green', 'purple', 'blue']\n\nfor i, square in enumerate(squares):\n print(i, square)", 162 | "metadata": {}, 163 | "execution_count": null, 164 | "outputs": [] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "source": "

What is while loop?

\n", 169 | "metadata": {} 170 | }, 171 | { 172 | "cell_type": "markdown", 173 | "source": "As you can see, the for loop is used for a controlled flow of repetition. However, what if we don't know when we want to stop the loop? What if we want to keep executing a code block until a certain condition is met? The while loop exists as a tool for repeated execution based on a condition. The code block will keep being executed until the given logical condition returns a **False** boolean value.\n", 174 | "metadata": {} 175 | }, 176 | { 177 | "cell_type": "markdown", 178 | "source": "Let’s say we would like to iterate through list dates and stop at the year 1973, then print out the number of iterations. This can be done with the following block of code:\n", 179 | "metadata": {} 180 | }, 181 | { 182 | "cell_type": "code", 183 | "source": "# While Loop Example\n\ndates = [1982, 1980, 1973, 2000]\n\ni = 0\nyear = dates[0]\n\nwhile(year != 1973): \n print(year)\n i = i + 1\n year = dates[i]\n \n\nprint(\"It took \", i ,\"repetitions to get out of loop.\")", 184 | "metadata": {}, 185 | "execution_count": null, 186 | "outputs": [] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "source": "A while loop iterates merely until the condition in the argument is not met, as shown in the following figure:\n", 191 | "metadata": {} 192 | }, 193 | { 194 | "cell_type": "markdown", 195 | "source": "\n", 196 | "metadata": {} 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "source": "
\n", 201 | "metadata": {} 202 | }, 203 | { 204 | "cell_type": "markdown", 205 | "source": "

Quiz on Loops

\n", 206 | "metadata": {} 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "source": "Write a for loop the prints out all the element between -5 and 5 using the range function.\n", 211 | "metadata": {} 212 | }, 213 | { 214 | "cell_type": "code", 215 | "source": "# Write your code below and press Shift+Enter to execute\nfor i in range(-4,5):\n print(i)", 216 | "metadata": {}, 217 | "execution_count": null, 218 | "outputs": [] 219 | }, 220 | { 221 | "cell_type": "markdown", 222 | "source": "
Click here for the solution\n\n```python\nfor i in range(-4, 5):\n print(i)\n \n```\n\n
\n", 223 | "metadata": {} 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "source": "Print the elements of the following list: Genres=\\[ 'rock', 'R\\&B', 'Soundtrack', 'R\\&B', 'soul', 'pop']\nMake sure you follow Python conventions.\n", 228 | "metadata": {} 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": "# Write your code below and press Shift+Enter to execute\nGenres=[ 'rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']\nfor genre in Genres:\n print(genre)", 233 | "metadata": {}, 234 | "execution_count": null, 235 | "outputs": [] 236 | }, 237 | { 238 | "cell_type": "markdown", 239 | "source": "
Click here for the solution\n\n```python\nGenres = ['rock', 'R&B', 'Soundtrack', 'R&B', 'soul', 'pop']\nfor Genre in Genres:\n print(Genre)\n \n```\n\n
\n", 240 | "metadata": {} 241 | }, 242 | { 243 | "cell_type": "markdown", 244 | "source": "
\n", 245 | "metadata": {} 246 | }, 247 | { 248 | "cell_type": "markdown", 249 | "source": "Write a for loop that prints out the following list: squares=\\['red', 'yellow', 'green', 'purple', 'blue']\n", 250 | "metadata": {} 251 | }, 252 | { 253 | "cell_type": "code", 254 | "source": "# Write your code below and press Shift+Enter to execute\nsquares=['red', 'yellow', 'green', 'purple', 'blue']\nfor colour in squares:\n print(colour)", 255 | "metadata": {}, 256 | "execution_count": null, 257 | "outputs": [] 258 | }, 259 | { 260 | "cell_type": "markdown", 261 | "source": "
Click here for the solution\n\n```python\nsquares=['red', 'yellow', 'green', 'purple', 'blue']\nfor square in squares:\n print(square)\n \n```\n\n
\n", 262 | "metadata": {} 263 | }, 264 | { 265 | "cell_type": "markdown", 266 | "source": "
\n", 267 | "metadata": {} 268 | }, 269 | { 270 | "cell_type": "markdown", 271 | "source": "Write a while loop to display the values of the Rating of an album playlist stored in the list PlayListRatings. If the score is less than 6, exit the loop. The list PlayListRatings is given by: PlayListRatings = \\[10, 9.5, 10, 8, 7.5, 5, 10, 10]\n", 272 | "metadata": {} 273 | }, 274 | { 275 | "cell_type": "code", 276 | "source": "# Write your code below and press Shift+Enter to execute\nPlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]\ni=0\nRating = PlayListRatings[i]\nwhile(i=6):\n print(Rating)\n i = i + 1 \n Rating = PlayListRatings[i]", 277 | "metadata": {}, 278 | "execution_count": null, 279 | "outputs": [] 280 | }, 281 | { 282 | "cell_type": "markdown", 283 | "source": "
Click here for the solution\n\n```python\nPlayListRatings = [10, 9.5, 10, 8, 7.5, 5, 10, 10]\ni = 0\nRating = PlayListRatings[0]\nwhile(i < len(PlayListRatings) and Rating >= 6):\n print(Rating)\n Rating = PlayListRatings[i]\n i = i + 1\n \n```\n\n
\n", 284 | "metadata": {} 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "source": "Write a while loop to copy the strings 'orange' of the list squares to the list new_squares. Stop and exit the loop if the value on the list is not 'orange':\n", 289 | "metadata": {} 290 | }, 291 | { 292 | "cell_type": "code", 293 | "source": "# Write your code below and press Shift+Enter to execute\n\nsquares = ['orange', 'orange', 'purple', 'blue ', 'orange']\nnew_squares = []\ni = 0\nwhile(squares[i] == 'orange' and i < len(squares)):\n new_squares.append(squares[i])\n i = i + 1\nprint (new_squares)", 294 | "metadata": {}, 295 | "execution_count": null, 296 | "outputs": [] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "source": "
Click here for the solution\n\n```python\nsquares = ['orange', 'orange', 'purple', 'blue ', 'orange']\nnew_squares = []\ni = 0\nwhile(i < len(squares) and squares[i] == 'orange'):\n new_squares.append(squares[i])\n i = i + 1\nprint (new_squares)\n \n```\n\n
\n", 301 | "metadata": {} 302 | }, 303 | { 304 | "cell_type": "markdown", 305 | "source": "
\n

The last exercise!

\n

Congratulations, you have completed your first lesson and hands-on lab in Python. \n


\n", 306 | "metadata": {} 307 | }, 308 | { 309 | "cell_type": "markdown", 310 | "source": "## Author\n\nJoseph Santarcangelo\n\n## Other contributors\n\nMavis Zhou\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ---------------------------------- |\n| 2022-02-24 | 2.2 | Hema | Changed the markdown solution |\n| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n
\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 311 | "metadata": {} 312 | } 313 | ] 314 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-4-1-ReadFile.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "kernelspec": { 4 | "name": "python", 5 | "display_name": "Pyolite", 6 | "language": "python" 7 | }, 8 | "language_info": { 9 | "codemirror_mode": { 10 | "name": "python", 11 | "version": 3 12 | }, 13 | "file_extension": ".py", 14 | "mimetype": "text/x-python", 15 | "name": "python", 16 | "nbconvert_exporter": "python", 17 | "pygments_lexer": "ipython3", 18 | "version": "3.8" 19 | }, 20 | "toc-autonumbering": false 21 | }, 22 | "nbformat_minor": 4, 23 | "nbformat": 4, 24 | "cells": [ 25 | { 26 | "cell_type": "markdown", 27 | "source": "
\n \"cognitiveclass.ai\n
\n\n# Reading Files Python\n\nEstimated time needed: **40** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Read text files using Python libraries\n", 28 | "metadata": {} 29 | }, 30 | { 31 | "cell_type": "markdown", 32 | "source": "

Table of Contents

\n\n\n
\n", 33 | "metadata": {} 34 | }, 35 | { 36 | "cell_type": "markdown", 37 | "source": "

Download Data

\n", 38 | "metadata": {} 39 | }, 40 | { 41 | "cell_type": "code", 42 | "source": "## Uncomment these if working locally, else let the following code cell run.\n\n# import urllib.request\n# url = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/data/example1.txt'\n# filename = 'Example1.txt'\n# urllib.request.urlretrieve(url, filename)\n\n## Download Example file\n# !wget -O /resources/data/Example1.txt https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/data/example1.txt", 43 | "metadata": { 44 | "trusted": true 45 | }, 46 | "execution_count": null, 47 | "outputs": [] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "source": "from pyodide.http import pyfetch\nimport pandas as pd\n\nfilename = \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/data/example1.txt\"\n\nasync def download(url, filename):\n response = await pyfetch(url)\n if response.status == 200:\n with open(filename, \"wb\") as f:\n f.write(await response.bytes())\n\n\nawait download(filename, \"Example1.txt\")", 52 | "metadata": { 53 | "trusted": true 54 | }, 55 | "execution_count": null, 56 | "outputs": [] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "source": "
\n", 61 | "metadata": {} 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "source": "

Reading Text Files

\n", 66 | "metadata": {} 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "source": "One way to read or write a file in Python is to use the built-in open function. The open function provides a **File object** that contains the methods and attributes you need in order to read, save, and manipulate the file. In this notebook, we will only cover **.txt** files. The first parameter you need is the file path and the file name. An example is shown as follow:\n", 71 | "metadata": {} 72 | }, 73 | { 74 | "cell_type": "markdown", 75 | "source": "\n", 76 | "metadata": {} 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "source": "The mode argument is optional and the default value is **r**. In this notebook we only cover two modes:\n\n
    \n
  • **r**: Read mode for reading files
  • \n
  • **w**: Write mode for writing files
  • \n
\n", 81 | "metadata": {} 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "source": "For the next example, we will use the text file **Example1.txt**. The file is shown as follows:\n", 86 | "metadata": {} 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "source": "\n", 91 | "metadata": {} 92 | }, 93 | { 94 | "cell_type": "markdown", 95 | "source": "We read the file:\n", 96 | "metadata": {} 97 | }, 98 | { 99 | "cell_type": "code", 100 | "source": "# Read the Example1.txt\nexample1 = \"Example1.txt\"\nfile1 = open(example1, \"r\")\n", 101 | "metadata": { 102 | "trusted": true 103 | }, 104 | "execution_count": null, 105 | "outputs": [] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "source": "We can view the attributes of the file.\n", 110 | "metadata": {} 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "source": "The name of the file:\n", 115 | "metadata": {} 116 | }, 117 | { 118 | "cell_type": "code", 119 | "source": "# Print the path of file\n\nfile1.name", 120 | "metadata": { 121 | "trusted": true 122 | }, 123 | "execution_count": null, 124 | "outputs": [] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "source": "The mode the file object is in:\n", 129 | "metadata": {} 130 | }, 131 | { 132 | "cell_type": "code", 133 | "source": "# Print the mode of file, either 'r' or 'w'\n\nfile1.mode", 134 | "metadata": { 135 | "trusted": true 136 | }, 137 | "execution_count": null, 138 | "outputs": [] 139 | }, 140 | { 141 | "cell_type": "markdown", 142 | "source": "We can read the file and assign it to a variable :\n", 143 | "metadata": {} 144 | }, 145 | { 146 | "cell_type": "code", 147 | "source": "# Read the file\n\nFileContent = file1.read()\nFileContent", 148 | "metadata": { 149 | "trusted": true 150 | }, 151 | "execution_count": null, 152 | "outputs": [] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "source": "The **/n** means that there is a new line.\n", 157 | "metadata": {} 158 | }, 159 | { 160 | "cell_type": "markdown", 161 | "source": "We can print the file:\n", 162 | "metadata": {} 163 | }, 164 | { 165 | "cell_type": "code", 166 | "source": "# Print the file with '\\n' as a new line\n\nprint(FileContent)", 167 | "metadata": { 168 | "trusted": true 169 | }, 170 | "execution_count": null, 171 | "outputs": [] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "source": "The file is of type string:\n", 176 | "metadata": {} 177 | }, 178 | { 179 | "cell_type": "code", 180 | "source": "# Type of file content\n\ntype(FileContent)", 181 | "metadata": { 182 | "trusted": true 183 | }, 184 | "execution_count": null, 185 | "outputs": [] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "source": "It is very important that the file is closed in the end. This frees up resources and ensures consistency across different python versions.\n", 190 | "metadata": {} 191 | }, 192 | { 193 | "cell_type": "code", 194 | "source": "# Close file after finish\n\nfile1.close()", 195 | "metadata": { 196 | "trusted": true 197 | }, 198 | "execution_count": null, 199 | "outputs": [] 200 | }, 201 | { 202 | "cell_type": "markdown", 203 | "source": "
\n", 204 | "metadata": {} 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "source": "

A Better Way to Open a File

\n", 209 | "metadata": {} 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "source": "Using the with statement is better practice, it automatically closes the file even if the code encounters an exception. The code will run everything in the indent block then close the file object.\n", 214 | "metadata": {} 215 | }, 216 | { 217 | "cell_type": "code", 218 | "source": "# Open file using with\n\nwith open(example1, \"r\") as file1:\n FileContent = file1.read()\n print(FileContent)", 219 | "metadata": { 220 | "trusted": true 221 | }, 222 | "execution_count": null, 223 | "outputs": [] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "source": "The file object is closed, you can verify it by running the following cell:\n", 228 | "metadata": {} 229 | }, 230 | { 231 | "cell_type": "code", 232 | "source": "# Verify if the file is closed\n\nfile1.closed", 233 | "metadata": { 234 | "trusted": true 235 | }, 236 | "execution_count": null, 237 | "outputs": [] 238 | }, 239 | { 240 | "cell_type": "markdown", 241 | "source": "We can see the info in the file:\n", 242 | "metadata": {} 243 | }, 244 | { 245 | "cell_type": "code", 246 | "source": "# See the content of file\n\nprint(FileContent)", 247 | "metadata": { 248 | "trusted": true 249 | }, 250 | "execution_count": null, 251 | "outputs": [] 252 | }, 253 | { 254 | "cell_type": "markdown", 255 | "source": "The syntax is a little confusing as the file object is after the as statement. We also don’t explicitly close the file. Therefore we summarize the steps in a figure:\n", 256 | "metadata": {} 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "source": "\n", 261 | "metadata": {} 262 | }, 263 | { 264 | "cell_type": "markdown", 265 | "source": "We don’t have to read the entire file, for example, we can read the first 4 characters by entering three as a parameter to the method **.read()**:\n", 266 | "metadata": {} 267 | }, 268 | { 269 | "cell_type": "code", 270 | "source": "# Read first four characters\n\nwith open(example1, \"r\") as file1:\n print(file1.read(4))", 271 | "metadata": { 272 | "trusted": true 273 | }, 274 | "execution_count": null, 275 | "outputs": [] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "source": "Once the method .read(4) is called the first 4 characters are called. If we call the method again, the next 4 characters are called. The output for the following cell will demonstrate the process for different inputs to the method read():\n", 280 | "metadata": {} 281 | }, 282 | { 283 | "cell_type": "code", 284 | "source": "# Read certain amount of characters\n\nwith open(example1, \"r\") as file1:\n print(file1.read(4))\n print(file1.read(4))\n print(file1.read(7))\n print(file1.read(15))", 285 | "metadata": { 286 | "trusted": true 287 | }, 288 | "execution_count": null, 289 | "outputs": [] 290 | }, 291 | { 292 | "cell_type": "markdown", 293 | "source": "The process is illustrated in the below figure, and each color represents the part of the file read after the method read() is called:\n", 294 | "metadata": {} 295 | }, 296 | { 297 | "cell_type": "markdown", 298 | "source": "\n", 299 | "metadata": {} 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "source": "Here is an example using the same file, but instead we read 16, 5, and then 9 characters at a time:\n", 304 | "metadata": {} 305 | }, 306 | { 307 | "cell_type": "code", 308 | "source": "# Read certain amount of characters\n\nwith open(example1, \"r\") as file1:\n print(file1.read(16))\n print(file1.read(5))\n print(file1.read(9))", 309 | "metadata": { 310 | "trusted": true 311 | }, 312 | "execution_count": null, 313 | "outputs": [] 314 | }, 315 | { 316 | "cell_type": "markdown", 317 | "source": "We can also read one line of the file at a time using the method readline():\n", 318 | "metadata": {} 319 | }, 320 | { 321 | "cell_type": "code", 322 | "source": "# Read one line\n\nwith open(example1, \"r\") as file1:\n print(\"first line: \" + file1.readline())", 323 | "metadata": { 324 | "trusted": true 325 | }, 326 | "execution_count": null, 327 | "outputs": [] 328 | }, 329 | { 330 | "cell_type": "markdown", 331 | "source": "We can also pass an argument to readline() to specify the number of charecters we want to read. However, unlike read(), readline() can only read one line at most.\n", 332 | "metadata": {} 333 | }, 334 | { 335 | "cell_type": "code", 336 | "source": "with open(example1, \"r\") as file1:\n print(file1.readline(20)) # does not read past the end of line\n print(file1.read(20)) # Returns the next 20 chars\n", 337 | "metadata": { 338 | "trusted": true 339 | }, 340 | "execution_count": null, 341 | "outputs": [] 342 | }, 343 | { 344 | "cell_type": "markdown", 345 | "source": "We can use a loop to iterate through each line:\n", 346 | "metadata": {} 347 | }, 348 | { 349 | "cell_type": "code", 350 | "source": "# Iterate through the lines\n\nwith open(example1,\"r\") as file1:\n i = 0;\n for line in file1:\n print(\"Iteration\", str(i), \": \", line)\n i = i + 1", 351 | "metadata": { 352 | "trusted": true 353 | }, 354 | "execution_count": null, 355 | "outputs": [] 356 | }, 357 | { 358 | "cell_type": "markdown", 359 | "source": "We can use the method readlines() to save the text file to a list:\n", 360 | "metadata": {} 361 | }, 362 | { 363 | "cell_type": "code", 364 | "source": "# Read all lines and save as a list\n\nwith open(example1, \"r\") as file1:\n FileasList = file1.readlines()", 365 | "metadata": { 366 | "trusted": true 367 | }, 368 | "execution_count": null, 369 | "outputs": [] 370 | }, 371 | { 372 | "cell_type": "markdown", 373 | "source": "Each element of the list corresponds to a line of text:\n", 374 | "metadata": {} 375 | }, 376 | { 377 | "cell_type": "code", 378 | "source": "# Print the first line\n\nFileasList[0]", 379 | "metadata": { 380 | "trusted": true 381 | }, 382 | "execution_count": null, 383 | "outputs": [] 384 | }, 385 | { 386 | "cell_type": "markdown", 387 | "source": "# Print the second line\n\nFileasList\\[1]\n", 388 | "metadata": {} 389 | }, 390 | { 391 | "cell_type": "code", 392 | "source": "# Print the third line\n\nFileasList[2]", 393 | "metadata": { 394 | "trusted": true 395 | }, 396 | "execution_count": null, 397 | "outputs": [] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "source": "
\n

The last exercise!

\n

Congratulations, you have completed your first lesson and hands-on lab in Python.\n


\n", 402 | "metadata": {} 403 | }, 404 | { 405 | "cell_type": "markdown", 406 | "source": "## Author\n\nJoseph Santarcangelo\n\n## Other contributors\n\nMavis Zhou\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ------------- | --------------------------------------------------------- |\n| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n| 2020-09-30 | 1.3 | Malika | Deleted exericse \"Weather Data\" |\n| 2020-09-30 | 1.2 | Malika Singla | Weather Data dataset link added |\n| 2020-09-30 | 1.1 | Arjun Swani | Added exericse \"Weather Data\" |\n| 2020-09-30 | 1.0 | Arjun Swani | Added blurbs about closing files and read() vs readline() |\n| 2020-08-26 | 0.2 | Lavanya | Moved lab to course repo in GitLab |\n| | | | |\n| | | | |\n\n
\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 407 | "metadata": {} 408 | } 409 | ] 410 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-4-2-WriteFile.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": { 3 | "interpreter": { 4 | "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49" 5 | }, 6 | "kernelspec": { 7 | "name": "python", 8 | "display_name": "Pyolite", 9 | "language": "python" 10 | }, 11 | "language_info": { 12 | "codemirror_mode": { 13 | "name": "python", 14 | "version": 3 15 | }, 16 | "file_extension": ".py", 17 | "mimetype": "text/x-python", 18 | "name": "python", 19 | "nbconvert_exporter": "python", 20 | "pygments_lexer": "ipython3", 21 | "version": "3.8" 22 | } 23 | }, 24 | "nbformat_minor": 4, 25 | "nbformat": 4, 26 | "cells": [ 27 | { 28 | "cell_type": "markdown", 29 | "source": "

\n \n \"Skills\n \n

\n\n# Write and Save Files in Python\n\nEstimated time needed: **25** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Write to files using Python libraries\n", 30 | "metadata": {} 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "source": "

Table of Contents

\n\n\n
\n", 35 | "metadata": {} 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "source": "

Writing Files

\n", 40 | "metadata": {} 41 | }, 42 | { 43 | "cell_type": "markdown", 44 | "source": "We can open a file object using the method write() to save the text file to a list. To write to a file, the mode argument must be set to **w**. Let’s write a file **Example2.txt** with the line: **“This is line A”**\n", 45 | "metadata": {} 46 | }, 47 | { 48 | "cell_type": "code", 49 | "source": "# Write line to file\nexmp2 = '/resources/data/Example2.txt'\nwith open(exmp2, 'w') as writefile:\n writefile.write(\"This is line A\")", 50 | "metadata": {}, 51 | "execution_count": null, 52 | "outputs": [] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "source": "We can read the file to see if it worked:\n", 57 | "metadata": {} 58 | }, 59 | { 60 | "cell_type": "code", 61 | "source": "# Read file\n\nwith open(exmp2, 'r') as testwritefile:\n print(testwritefile.read())", 62 | "metadata": {}, 63 | "execution_count": null, 64 | "outputs": [] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "source": "We can write multiple lines:\n", 69 | "metadata": {} 70 | }, 71 | { 72 | "cell_type": "code", 73 | "source": "# Write lines to file\n\nwith open(exmp2, 'w') as writefile:\n writefile.write(\"This is line A\\n\")\n writefile.write(\"This is line B\\n\")", 74 | "metadata": {}, 75 | "execution_count": null, 76 | "outputs": [] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "source": "The method .write() works similar to the method .readline(), except instead of reading a new line it writes a new line. The process is illustrated in the figure. The different colour coding of the grid represents a new line added to the file after each method call.\n", 81 | "metadata": {} 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "source": "\n", 86 | "metadata": {} 87 | }, 88 | { 89 | "cell_type": "markdown", 90 | "source": "You can check the file to see if your results are correct\n", 91 | "metadata": {} 92 | }, 93 | { 94 | "cell_type": "code", 95 | "source": "# Check whether write to file\n\nwith open(exmp2, 'r') as testwritefile:\n print(testwritefile.read())", 96 | "metadata": {}, 97 | "execution_count": null, 98 | "outputs": [] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "source": "We write a list to a **.txt** file as follows:\n", 103 | "metadata": {} 104 | }, 105 | { 106 | "cell_type": "code", 107 | "source": "# Sample list of text\n\nLines = [\"This is line A\\n\", \"This is line B\\n\", \"This is line C\\n\"]\nLines", 108 | "metadata": {}, 109 | "execution_count": null, 110 | "outputs": [] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "source": "# Write the strings in the list to text file\n\nwith open('Example2.txt', 'w') as writefile:\n for line in Lines:\n print(line)\n writefile.write(line)", 115 | "metadata": {}, 116 | "execution_count": null, 117 | "outputs": [] 118 | }, 119 | { 120 | "cell_type": "markdown", 121 | "source": "We can verify the file is written by reading it and printing out the values:\n", 122 | "metadata": {} 123 | }, 124 | { 125 | "cell_type": "code", 126 | "source": "# Verify if writing to file is successfully executed\n\nwith open('Example2.txt', 'r') as testwritefile:\n print(testwritefile.read())", 127 | "metadata": {}, 128 | "execution_count": null, 129 | "outputs": [] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "source": "However, note that setting the mode to **w** overwrites all the existing data in the file.\n", 134 | "metadata": {} 135 | }, 136 | { 137 | "cell_type": "code", 138 | "source": "with open('Example2.txt', 'w') as writefile:\n writefile.write(\"Overwrite\\n\")\nwith open('Example2.txt', 'r') as testwritefile:\n print(testwritefile.read())", 139 | "metadata": {}, 140 | "execution_count": null, 141 | "outputs": [] 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "source": "
\n

Appending Files

\n", 146 | "metadata": {} 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "source": "We can write to files without losing any of the existing data as follows by setting the mode argument to append: **a**. you can append a new line as follows:\n", 151 | "metadata": {} 152 | }, 153 | { 154 | "cell_type": "code", 155 | "source": "# Write a new line to text file\n\nwith open('Example2.txt', 'a') as testwritefile:\n testwritefile.write(\"This is line C\\n\")\n testwritefile.write(\"This is line D\\n\")\n testwritefile.write(\"This is line E\\n\")", 156 | "metadata": {}, 157 | "execution_count": null, 158 | "outputs": [] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "source": "You can verify the file has changed by running the following cell:\n", 163 | "metadata": {} 164 | }, 165 | { 166 | "cell_type": "code", 167 | "source": "# Verify if the new line is in the text file\n\nwith open('Example2.txt', 'r') as testwritefile:\n print(testwritefile.read())", 168 | "metadata": {}, 169 | "execution_count": null, 170 | "outputs": [] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "source": "
\n

Additional modes

\n", 175 | "metadata": {} 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "source": "It's fairly ineffecient to open the file in **a** or **w** and then reopening it in **r** to read any lines. Luckily we can access the file in the following modes:\n\n* **r+** : Reading and writing. Cannot truncate the file.\n* **w+** : Writing and reading. Truncates the file.\n* **a+** : Appending and Reading. Creates a new file, if none exists.\n\nYou dont have to dwell on the specifics of each mode for this lab.\n", 180 | "metadata": {} 181 | }, 182 | { 183 | "cell_type": "markdown", 184 | "source": "Let's try out the **a+** mode:\n", 185 | "metadata": {} 186 | }, 187 | { 188 | "cell_type": "code", 189 | "source": "with open('Example2.txt', 'a+') as testwritefile:\n testwritefile.write(\"This is line E\\n\")\n print(testwritefile.read())", 190 | "metadata": {}, 191 | "execution_count": null, 192 | "outputs": [] 193 | }, 194 | { 195 | "cell_type": "markdown", 196 | "source": "There were no errors but read() also did not output anything. This is because of our location in the file.\n", 197 | "metadata": {} 198 | }, 199 | { 200 | "cell_type": "markdown", 201 | "source": "Most of the file methods we've looked at work in a certain location in the file. .write() writes at a certain location in the file. .read() reads at a certain location in the file and so on. You can think of this as moving your pointer around in the notepad to make changes at specific location.\n", 202 | "metadata": {} 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "source": "Opening the file in **w** is akin to opening the .txt file, moving your cursor to the beginning of the text file, writing new text and deleting everything that follows.\nWhereas opening the file in **a** is similiar to opening the .txt file, moving your cursor to the very end and then adding the new pieces of text.
\nIt is often very useful to know where the 'cursor' is in a file and be able to control it. The following methods allow us to do precisely this -\n\n* .tell() - returns the current position in bytes\n* .seek(offset,from) - changes the position by 'offset' bytes with respect to 'from'. From can take the value of 0,1,2 corresponding to beginning, relative to current position and end\n", 207 | "metadata": {} 208 | }, 209 | { 210 | "cell_type": "markdown", 211 | "source": "Now lets revisit **a+**\n", 212 | "metadata": {} 213 | }, 214 | { 215 | "cell_type": "code", 216 | "source": "with open('Example2.txt', 'a+') as testwritefile:\n print(\"Initial Location: {}\".format(testwritefile.tell()))\n \n data = testwritefile.read()\n if (not data): #empty strings return false in python\n print('Read nothing') \n else: \n print(testwritefile.read())\n \n testwritefile.seek(0,0) # move 0 bytes from beginning.\n \n print(\"\\nNew Location : {}\".format(testwritefile.tell()))\n data = testwritefile.read()\n if (not data): \n print('Read nothing') \n else: \n print(data)\n \n print(\"Location after read: {}\".format(testwritefile.tell()) )", 217 | "metadata": {}, 218 | "execution_count": null, 219 | "outputs": [] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "source": "Finally, a note on the difference between **w+** and **r+**. Both of these modes allow access to read and write methods, however, opening a file in **w+** overwrites it and deletes all pre-existing data.
\nTo work with a file on existing data, use **r+** and **a+**. While using **r+**, it can be useful to add a .truncate() method at the end of your data. This will reduce the file to your data and delete everything that follows.
\nIn the following code block, Run the code as it is first and then run it with the .truncate().\n", 224 | "metadata": {} 225 | }, 226 | { 227 | "cell_type": "code", 228 | "source": "with open('Example2.txt', 'r+') as testwritefile:\n data = testwritefile.readlines()\n testwritefile.seek(0,0) #write at beginning of file\n \n testwritefile.write(\"Line 1\" + \"\\n\")\n testwritefile.write(\"Line 2\" + \"\\n\")\n testwritefile.write(\"Line 3\" + \"\\n\")\n testwritefile.write(\"finished\\n\")\n #Uncomment the line below\n #testwritefile.truncate()\n testwritefile.seek(0,0)\n print(testwritefile.read())\n ", 229 | "metadata": {}, 230 | "execution_count": null, 231 | "outputs": [] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "source": "
\n", 236 | "metadata": {} 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "source": "

Copy a File

\n", 241 | "metadata": {} 242 | }, 243 | { 244 | "cell_type": "markdown", 245 | "source": "Let's copy the file **Example2.txt** to the file **Example3.txt**:\n", 246 | "metadata": {} 247 | }, 248 | { 249 | "cell_type": "code", 250 | "source": "# Copy file to another\n\nwith open('Example2.txt','r') as readfile:\n with open('Example3.txt','w') as writefile:\n for line in readfile:\n writefile.write(line)", 251 | "metadata": {}, 252 | "execution_count": null, 253 | "outputs": [] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "source": "We can read the file to see if everything works:\n", 258 | "metadata": {} 259 | }, 260 | { 261 | "cell_type": "code", 262 | "source": "# Verify if the copy is successfully executed\n\nwith open('Example3.txt','r') as testwritefile:\n print(testwritefile.read())", 263 | "metadata": {}, 264 | "execution_count": null, 265 | "outputs": [] 266 | }, 267 | { 268 | "cell_type": "markdown", 269 | "source": "After reading files, we can also write data into files and save them in different file formats like **.txt, .csv, .xls (for excel files) etc**. You will come across these in further examples\n", 270 | "metadata": {} 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "source": "**NOTE:** If you wish to open and view the `example3.txt` file, download this lab [here](https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/PY0101EN-4-2-WriteFile.ipynb) and run it locally on your machine. Then go to the working directory to ensure the `example3.txt` file exists and contains the summary data that we wrote.\n", 275 | "metadata": {} 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "source": "
\n", 280 | "metadata": {} 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "source": "

Exercise

\n", 285 | "metadata": {} 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "source": "Your local university's Raptors fan club maintains a register of its active members on a .txt document. Every month they update the file by removing the members who are not active. You have been tasked with automating this with your Python skills.
\nGiven the file `currentMem`, Remove each member with a 'no' in their Active column. Keep track of each of the removed members and append them to the `exMem` file. Make sure that the format of the original files in preserved. (*Hint: Do this by reading/writing whole lines and ensuring the header remains* )
\nRun the code block below prior to starting the exercise. The skeleton code has been provided for you. Edit only the `cleanFiles` function.\n", 290 | "metadata": {} 291 | }, 292 | { 293 | "cell_type": "code", 294 | "source": "#Run this prior to starting the exercise\nfrom random import randint as rnd\n\nmemReg = 'members.txt'\nexReg = 'inactive.txt'\nfee =('yes','no')\n\ndef genFiles(current,old):\n with open(current,'w+') as writefile: \n writefile.write('Membership No Date Joined Active \\n')\n data = \"{:^13} {:<11} {:<6}\\n\"\n\n for rowno in range(20):\n date = str(rnd(2015,2020))+ '-' + str(rnd(1,12))+'-'+str(rnd(1,25))\n writefile.write(data.format(rnd(10000,99999),date,fee[rnd(0,1)]))\n\n\n with open(old,'w+') as writefile: \n writefile.write('Membership No Date Joined Active \\n')\n data = \"{:^13} {:<11} {:<6}\\n\"\n for rowno in range(3):\n date = str(rnd(2015,2020))+ '-' + str(rnd(1,12))+'-'+str(rnd(1,25))\n writefile.write(data.format(rnd(10000,99999),date,fee[1]))\n\n\ngenFiles(memReg,exReg)\n", 295 | "metadata": {}, 296 | "execution_count": null, 297 | "outputs": [] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "source": "Now that you've run the prerequisite code cell above, which prepared the files for this exercise, you are ready to move on to the implementation.\n\n#### **Exercise:** Implement the cleanFiles function in the code cell below.\n", 302 | "metadata": {} 303 | }, 304 | { 305 | "cell_type": "code", 306 | "source": " \n'''\nThe two arguments for this function are the files:\n - currentMem: File containing list of current members\n - exMem: File containing list of old members\n \n This function should remove all rows from currentMem containing 'no' \n in the 'Active' column and appends them to exMem.\n '''\ndef cleanFiles(currentMem, exMem):\n with open(currentMem, 'r+') as readfile:\n #TODO: Open the exMem file in a+ mode\n with open(exMem, 'a+') as appendfile:\n # Hint: Recall that the first line in the file is the header.\n header = readfile.readline()\n #TODO: Read each member in the currentMem (1 member per row) file into a list.\n list_of_lines = readfile.readlines()\n # Go to the beginning of the currentMem file\n readfile.seek(0)\n readfile.write(header)\n #TODO: iterate through the members list.\n for line in list_of_lines:\n # If a member is inactive, add them to exMem, otherwise write them into currentMem\n if 'no' in line:\n appendfile.write(line)\n else:\n readfile.write(line)\n readfile.truncate()\n # pass # Remove this line when done implementation\n\n\n# The code below is to help you view the files.\n# Do not modify this code for this exercise.\nmemReg = 'members.txt'\nexReg = 'inactive.txt'\ncleanFiles(memReg,exReg)\n\n\nheaders = \"Membership No Date Joined Active \\n\"\nwith open(memReg,'r') as readFile:\n print(\"Active Members: \\n\\n\")\n print(readFile.read())\n \nwith open(exReg,'r') as readFile:\n print(\"Inactive Members: \\n\\n\")\n print(readFile.read())\n \n ", 307 | "metadata": {}, 308 | "execution_count": null, 309 | "outputs": [] 310 | }, 311 | { 312 | "cell_type": "markdown", 313 | "source": "The code cell below is to verify your solution. Please do not modify the code and run it to test your implementation of `cleanFiles`.\n", 314 | "metadata": {} 315 | }, 316 | { 317 | "cell_type": "code", 318 | "source": "def testMsg(passed):\n if passed:\n return 'Test Passed'\n else :\n return 'Test Failed'\n\ntestWrite = \"testWrite.txt\"\ntestAppend = \"testAppend.txt\" \npassed = True\n\ngenFiles(testWrite,testAppend)\n\nwith open(testWrite,'r') as file:\n ogWrite = file.readlines()\n\nwith open(testAppend,'r') as file:\n ogAppend = file.readlines()\n\ntry:\n cleanFiles(testWrite,testAppend)\nexcept:\n print('Error')\n\nwith open(testWrite,'r') as file:\n clWrite = file.readlines()\n\nwith open(testAppend,'r') as file:\n clAppend = file.readlines()\n \n# checking if total no of rows is same, including headers\n\nif (len(ogWrite) + len(ogAppend) != len(clWrite) + len(clAppend)):\n print(\"The number of rows do not add up. Make sure your final files have the same header and format.\")\n passed = False\n \nfor line in clWrite:\n if 'no' in line:\n passed = False\n print(\"Inactive members in file\")\n break\n else:\n if line not in ogWrite:\n print(\"Data in file does not match original file\")\n passed = False\nprint (\"{}\".format(testMsg(passed)))\n \n\n", 319 | "metadata": {}, 320 | "execution_count": null, 321 | "outputs": [] 322 | }, 323 | { 324 | "cell_type": "markdown", 325 | "source": "
Click here for the solution\n\n```python\ndef cleanFiles(currentMem,exMem):\n with open(currentMem,'r+') as writeFile: \n with open(exMem,'a+') as appendFile:\n #get the data\n writeFile.seek(0)\n members = writeFile.readlines()\n #remove header\n header = members[0]\n members.pop(0)\n \n inactive = [member for member in members if ('no' in member)]\n '''\n The above is the same as \n\n for member in members:\n if 'no' in member:\n inactive.append(member)\n '''\n #go to the beginning of the write file\n writeFile.seek(0) \n writeFile.write(header)\n for member in members:\n if (member in inactive):\n appendFile.write(member)\n else:\n writeFile.write(member) \n writeFile.truncate()\n \nmemReg = 'members.txt'\nexReg = 'inactive.txt'\ncleanFiles(memReg,exReg)\n\n# code to help you see the files\n\nheaders = \"Membership No Date Joined Active \\n\"\n\nwith open(memReg,'r') as readFile:\n print(\"Active Members: \\n\\n\")\n print(readFile.read())\n \nwith open(exReg,'r') as readFile:\n print(\"Inactive Members: \\n\\n\")\n print(readFile.read())\n \n```\n\n
\n", 326 | "metadata": {} 327 | }, 328 | { 329 | "cell_type": "markdown", 330 | "source": "
\n

The last exercise!

\n

Congratulations, you have completed this lesson and hands-on lab in Python. \n


\n", 331 | "metadata": {} 332 | }, 333 | { 334 | "cell_type": "markdown", 335 | "source": "## Author\n\nJoseph Santarcangelo\n\n### Other Contributors\n\nMavis Zhou\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ----------- | ----------------------------------- |\n| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n| 2020-10-16 | 1.3 | Arjun Swani | Added exercise |\n| 2020-10-16 | 1.2 | Arjun Swani | Added section additional file modes |\n| 2020-10-16 | 1.1 | Arjun Swani | Made append a different section |\n| 2020-08-28 | 0.2 | Lavanya | Moved lab to course repo in GitLab |\n\n
\n\n##

© IBM Corporation 2020. All rights reserved.

\n", 336 | "metadata": {} 337 | } 338 | ] 339 | } -------------------------------------------------------------------------------- /all week python notebooks/PY0101EN-4-3-LoadData.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "

\n", 8 | " \n", 9 | " \"Skills\n", 10 | " \n", 11 | "

\n", 12 | "\n", 13 | "# Introduction to Pandas in Python\n", 14 | "\n", 15 | "Estimated time needed: **15** minutes\n", 16 | "\n", 17 | "## Objectives\n", 18 | "\n", 19 | "After completing this lab you will be able to:\n", 20 | "\n", 21 | "* Use Pandas to access and view data\n" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "metadata": {}, 27 | "source": [ 28 | "

Table of Contents

\n", 29 | "
\n", 30 | " \n", 36 | "\n", 37 | "
\n", 38 | "\n", 39 | "
\n" 40 | ] 41 | }, 42 | { 43 | "cell_type": "markdown", 44 | "metadata": {}, 45 | "source": [ 46 | "

About the Dataset

\n" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "metadata": {}, 52 | "source": [ 53 | "The table has one row for each album and several columns.\n", 54 | "\n", 55 | "
    \n", 56 | "
  • artist: Name of the artist
  • \n", 57 | "
  • album: Name of the album
  • \n", 58 | "
  • released_year: Year the album was released
  • \n", 59 | "
  • length_min_sec: Length of the album (hours,minutes,seconds)
  • \n", 60 | "
  • genre: Genre of the album
  • \n", 61 | "
  • music_recording_sales_millions: Music recording sales (millions in USD) on [SONG://DATABASE]
  • \n", 62 | "
  • claimed_sales_millions: Album's claimed sales (millions in USD) on [SONG://DATABASE]
  • \n", 63 | "
  • date_released: Date on which the album was released
  • \n", 64 | "
  • soundtrack: Indicates if the album is the movie soundtrack (Y) or (N)
  • \n", 65 | "
  • rating_of_friends: Indicates the rating from your friends from 1 to 10
  • \n", 66 | "
\n", 67 | "\n", 68 | "You can see the dataset here:\n", 69 | "\n", 70 | "\n", 71 | "\n", 72 | " \n", 73 | " \n", 74 | " \n", 75 | " \n", 76 | " \n", 77 | " \n", 78 | " \n", 79 | " \n", 80 | " \n", 81 | " \n", 82 | " \n", 83 | " \n", 84 | " \n", 85 | " \n", 86 | " \n", 87 | " \n", 88 | " \n", 89 | " \n", 90 | " \n", 91 | " \n", 92 | " \n", 93 | " \n", 94 | " \n", 95 | " \n", 96 | " \n", 97 | " \n", 98 | " \n", 99 | " \n", 100 | " \n", 101 | " \n", 102 | " \n", 103 | " \n", 104 | " \n", 105 | " \n", 106 | " \n", 107 | " \n", 108 | " \n", 109 | " \n", 110 | " \n", 111 | " \n", 112 | " \n", 113 | " \n", 114 | " \n", 115 | " \n", 116 | " \n", 117 | " \n", 118 | " \n", 119 | " \n", 120 | " \n", 121 | " \n", 122 | " \n", 123 | " \n", 124 | " \n", 125 | " \n", 126 | " \n", 127 | " \n", 128 | " \n", 129 | " \n", 130 | " \n", 131 | " \n", 132 | " \n", 133 | " \n", 134 | " \n", 135 | " \n", 136 | " \n", 137 | " \n", 138 | " \n", 139 | " \n", 140 | " \n", 141 | " \n", 142 | " \n", 143 | " \n", 144 | " \n", 145 | " \n", 146 | " \n", 147 | " \n", 148 | " \n", 149 | " \n", 150 | " \n", 151 | " \n", 152 | " \n", 153 | " \n", 154 | " \n", 155 | " \n", 156 | " \n", 157 | " \n", 158 | " \n", 159 | " \n", 160 | " \n", 161 | " \n", 162 | " \n", 163 | " \n", 164 | " \n", 165 | " \n", 166 | " \n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | "
ArtistAlbumReleasedLengthGenreMusic recording sales (millions)Claimed sales (millions)ReleasedSoundtrackRating (friends)
Michael JacksonThriller198200:42:19Pop, rock, R&B466530-Nov-8210.0
AC/DCBack in Black198000:42:11Hard rock26.15025-Jul-808.5
Pink FloydThe Dark Side of the Moon197300:42:49Progressive rock24.24501-Mar-739.5
Whitney HoustonThe Bodyguard199200:57:44Soundtrack/R&B, soul, pop26.15025-Jul-80Y7.0
Meat LoafBat Out of Hell197700:46:33Hard rock, progressive rock20.64321-Oct-777.0
EaglesTheir Greatest Hits (1971-1975)197600:43:08Rock, soft rock, folk rock32.24217-Feb-769.5
Bee GeesSaturday Night Fever19771:15:54Disco20.64015-Nov-77Y9.0
Fleetwood MacRumours197700:40:01Soft rock27.94004-Feb-779.5
\n" 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "metadata": {}, 186 | "source": [ 187 | "
\n" 188 | ] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "metadata": {}, 193 | "source": [ 194 | "

Introduction of Pandas

\n" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": null, 200 | "metadata": {}, 201 | "outputs": [], 202 | "source": [ 203 | "# Dependency needed to install file\n", 204 | "\n", 205 | "!pip install xlrd" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "metadata": {}, 212 | "outputs": [], 213 | "source": [ 214 | "# Import required library\n", 215 | "\n", 216 | "import pandas as pd" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "After the import command, we now have access to a large number of pre-built classes and functions. This assumes the library is installed; in our lab environment all the necessary libraries are installed. One way pandas allows you to work with data is a dataframe. Let's go through the process to go from a comma separated values (.csv) file to a dataframe. This variable csv_path stores the path of the .csv, that is used as an argument to the read_csv function. The result is stored in the object df, this is a common short form used for a variable referring to a Pandas dataframe.\n" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": { 230 | "scrolled": true 231 | }, 232 | "outputs": [], 233 | "source": [ 234 | "# Read data from CSV file\n", 235 | "\n", 236 | "csv_path = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/labs/Module%204/data/TopSellingAlbums.csv'\n", 237 | "df = pd.read_csv(csv_path)" 238 | ] 239 | }, 240 | { 241 | "cell_type": "markdown", 242 | "metadata": {}, 243 | "source": [ 244 | "We can use the method head() to examine the first five rows of a dataframe:\n" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "metadata": {}, 251 | "outputs": [], 252 | "source": [ 253 | "# Print first five rows of the dataframe\n", 254 | "\n", 255 | "df.head()" 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": {}, 261 | "source": [ 262 | "We use the path of the excel file and the function read_excel. The result is a data frame as before:\n" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": null, 268 | "metadata": {}, 269 | "outputs": [], 270 | "source": [ 271 | "# Read data from Excel File and print the first five rows\n", 272 | "\n", 273 | "xlsx_path = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%204/Datasets/TopSellingAlbums.xlsx'\n", 274 | "\n", 275 | "df = pd.read_excel(xlsx_path)\n", 276 | "df.head()" 277 | ] 278 | }, 279 | { 280 | "cell_type": "markdown", 281 | "metadata": {}, 282 | "source": [ 283 | "We can access the column Length and assign it a new dataframe x:\n" 284 | ] 285 | }, 286 | { 287 | "cell_type": "code", 288 | "execution_count": null, 289 | "metadata": {}, 290 | "outputs": [], 291 | "source": [ 292 | "# Access to the column Length\n", 293 | "\n", 294 | "x = df[['Length']]\n", 295 | "x" 296 | ] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "metadata": {}, 301 | "source": [ 302 | "The process is shown in the figure:\n" 303 | ] 304 | }, 305 | { 306 | "cell_type": "markdown", 307 | "metadata": {}, 308 | "source": [ 309 | "\n" 310 | ] 311 | }, 312 | { 313 | "cell_type": "markdown", 314 | "metadata": {}, 315 | "source": [ 316 | "
\n" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "metadata": {}, 322 | "source": [ 323 | "

Viewing Data and Accessing Data

\n" 324 | ] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "metadata": {}, 329 | "source": [ 330 | "You can also get a column as a series. You can think of a Pandas series as a 1-D dataframe. Just use one bracket:\n" 331 | ] 332 | }, 333 | { 334 | "cell_type": "code", 335 | "execution_count": null, 336 | "metadata": {}, 337 | "outputs": [], 338 | "source": [ 339 | "# Get the column as a series\n", 340 | "\n", 341 | "x = df['Length']\n", 342 | "x" 343 | ] 344 | }, 345 | { 346 | "cell_type": "markdown", 347 | "metadata": {}, 348 | "source": [ 349 | "You can also get a column as a dataframe. For example, we can assign the column Artist:\n" 350 | ] 351 | }, 352 | { 353 | "cell_type": "code", 354 | "execution_count": null, 355 | "metadata": {}, 356 | "outputs": [], 357 | "source": [ 358 | "# Get the column as a dataframe\n", 359 | "\n", 360 | "x = df[['Artist']]\n", 361 | "type(x)" 362 | ] 363 | }, 364 | { 365 | "cell_type": "markdown", 366 | "metadata": {}, 367 | "source": [ 368 | "You can do the same thing for multiple columns; we just put the dataframe name, in this case, df, and the name of the multiple column headers enclosed in double brackets. The result is a new dataframe comprised of the specified columns:\n" 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": null, 374 | "metadata": {}, 375 | "outputs": [], 376 | "source": [ 377 | "# Access to multiple columns\n", 378 | "\n", 379 | "y = df[['Artist','Length','Genre']]\n", 380 | "y" 381 | ] 382 | }, 383 | { 384 | "cell_type": "markdown", 385 | "metadata": {}, 386 | "source": [ 387 | "The process is shown in the figure:\n" 388 | ] 389 | }, 390 | { 391 | "cell_type": "markdown", 392 | "metadata": {}, 393 | "source": [ 394 | "\n" 395 | ] 396 | }, 397 | { 398 | "cell_type": "markdown", 399 | "metadata": {}, 400 | "source": [ 401 | "One way to access unique elements is the iloc method, where you can access the 1st row and the 1st column as follows:\n" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "metadata": {}, 408 | "outputs": [], 409 | "source": [ 410 | "# Access the value on the first row and the first column\n", 411 | "\n", 412 | "df.iloc[0, 0]" 413 | ] 414 | }, 415 | { 416 | "cell_type": "markdown", 417 | "metadata": {}, 418 | "source": [ 419 | "You can access the 2nd row and the 1st column as follows:\n" 420 | ] 421 | }, 422 | { 423 | "cell_type": "code", 424 | "execution_count": null, 425 | "metadata": {}, 426 | "outputs": [], 427 | "source": [ 428 | "# Access the value on the second row and the first column\n", 429 | "\n", 430 | "df.iloc[1,0]" 431 | ] 432 | }, 433 | { 434 | "cell_type": "markdown", 435 | "metadata": {}, 436 | "source": [ 437 | "You can access the 1st row and the 3rd column as follows:\n" 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": null, 443 | "metadata": {}, 444 | "outputs": [], 445 | "source": [ 446 | "# Access the value on the first row and the third column\n", 447 | "\n", 448 | "df.iloc[0,2]" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": null, 454 | "metadata": {}, 455 | "outputs": [], 456 | "source": [ 457 | "# Access the value on the second row and the third column\n", 458 | "df.iloc[1,2]" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": null, 464 | "metadata": {}, 465 | "outputs": [], 466 | "source": [] 467 | }, 468 | { 469 | "cell_type": "markdown", 470 | "metadata": {}, 471 | "source": [ 472 | "This is shown in the following image\n" 473 | ] 474 | }, 475 | { 476 | "cell_type": "markdown", 477 | "metadata": {}, 478 | "source": [ 479 | "\n" 480 | ] 481 | }, 482 | { 483 | "cell_type": "markdown", 484 | "metadata": {}, 485 | "source": [ 486 | "You can access the column using the name as well, the following are the same as above:\n" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": null, 492 | "metadata": {}, 493 | "outputs": [], 494 | "source": [ 495 | "# Access the column using the name\n", 496 | "\n", 497 | "df.loc[1, 'Artist']" 498 | ] 499 | }, 500 | { 501 | "cell_type": "code", 502 | "execution_count": null, 503 | "metadata": {}, 504 | "outputs": [], 505 | "source": [ 506 | "# Access the column using the name\n", 507 | "\n", 508 | "df.loc[1, 'Artist']" 509 | ] 510 | }, 511 | { 512 | "cell_type": "code", 513 | "execution_count": null, 514 | "metadata": {}, 515 | "outputs": [], 516 | "source": [ 517 | "# Access the column using the name\n", 518 | "\n", 519 | "df.loc[0, 'Released']" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": null, 525 | "metadata": {}, 526 | "outputs": [], 527 | "source": [ 528 | "# Access the column using the name\n", 529 | "\n", 530 | "df.loc[1, 'Released']" 531 | ] 532 | }, 533 | { 534 | "cell_type": "markdown", 535 | "metadata": {}, 536 | "source": [ 537 | "\n" 538 | ] 539 | }, 540 | { 541 | "cell_type": "markdown", 542 | "metadata": {}, 543 | "source": [ 544 | "You can perform slicing using both the index and the name of the column:\n" 545 | ] 546 | }, 547 | { 548 | "cell_type": "code", 549 | "execution_count": null, 550 | "metadata": {}, 551 | "outputs": [], 552 | "source": [ 553 | "# Slicing the dataframe\n", 554 | "\n", 555 | "df.iloc[0:2, 0:3]" 556 | ] 557 | }, 558 | { 559 | "cell_type": "markdown", 560 | "metadata": {}, 561 | "source": [ 562 | "\n" 563 | ] 564 | }, 565 | { 566 | "cell_type": "code", 567 | "execution_count": null, 568 | "metadata": {}, 569 | "outputs": [], 570 | "source": [ 571 | "# Slicing the dataframe using name\n", 572 | "\n", 573 | "df.loc[0:2, 'Artist':'Released']" 574 | ] 575 | }, 576 | { 577 | "cell_type": "markdown", 578 | "metadata": {}, 579 | "source": [ 580 | "\n" 581 | ] 582 | }, 583 | { 584 | "cell_type": "markdown", 585 | "metadata": {}, 586 | "source": [ 587 | "
\n" 588 | ] 589 | }, 590 | { 591 | "cell_type": "markdown", 592 | "metadata": {}, 593 | "source": [ 594 | "

Quiz on DataFrame

\n" 595 | ] 596 | }, 597 | { 598 | "cell_type": "markdown", 599 | "metadata": {}, 600 | "source": [ 601 | "Use a variable q to store the column Rating as a dataframe\n" 602 | ] 603 | }, 604 | { 605 | "cell_type": "code", 606 | "execution_count": null, 607 | "metadata": {}, 608 | "outputs": [], 609 | "source": [ 610 | "# Write your code below and press Shift+Enter to execute\n", 611 | "\n", 612 | "q = df[['Rating']]\n", 613 | "q" 614 | ] 615 | }, 616 | { 617 | "cell_type": "markdown", 618 | "metadata": {}, 619 | "source": [ 620 | "
Click here for the solution\n", 621 | "\n", 622 | "```python\n", 623 | "q = df[['Rating']]\n", 624 | "q\n", 625 | " \n", 626 | "```\n", 627 | "\n", 628 | "
\n" 629 | ] 630 | }, 631 | { 632 | "cell_type": "markdown", 633 | "metadata": {}, 634 | "source": [ 635 | "Assign the variable q to the dataframe that is made up of the column Released and Artist:\n" 636 | ] 637 | }, 638 | { 639 | "cell_type": "code", 640 | "execution_count": null, 641 | "metadata": {}, 642 | "outputs": [], 643 | "source": [ 644 | "# Write your code below and press Shift+Enter to execute\n", 645 | "q = df[['Released', 'Artist']]\n", 646 | "q" 647 | ] 648 | }, 649 | { 650 | "cell_type": "markdown", 651 | "metadata": {}, 652 | "source": [ 653 | "
Click here for the solution\n", 654 | "\n", 655 | "```python\n", 656 | "q = df[['Released', 'Artist']]\n", 657 | "q\n", 658 | " \n", 659 | "```\n", 660 | "\n", 661 | "
\n" 662 | ] 663 | }, 664 | { 665 | "cell_type": "markdown", 666 | "metadata": {}, 667 | "source": [ 668 | "Access the 2nd row and the 3rd column of df:\n" 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "execution_count": null, 674 | "metadata": {}, 675 | "outputs": [], 676 | "source": [ 677 | "# Write your code below and press Shift+Enter to execute\n", 678 | "x = df.iloc[1,2]\n", 679 | "x" 680 | ] 681 | }, 682 | { 683 | "cell_type": "markdown", 684 | "metadata": {}, 685 | "source": [ 686 | "
Click here for the solution\n", 687 | "\n", 688 | "```python\n", 689 | "df.iloc[1, 2]\n", 690 | " \n", 691 | "```\n", 692 | "\n", 693 | "
\n" 694 | ] 695 | }, 696 | { 697 | "cell_type": "markdown", 698 | "metadata": {}, 699 | "source": [ 700 | "Use the following list to convert the dataframe index df to characters and assign it to df_new; find the element corresponding to the row index a and column 'Artist'. Then select the rows a through d for the column 'Artist'\n" 701 | ] 702 | }, 703 | { 704 | "cell_type": "code", 705 | "execution_count": null, 706 | "metadata": {}, 707 | "outputs": [], 708 | "source": [ 709 | "new_index = ['a','b','c','d','e','f','g','h']\n", 710 | "df_new = df[::] # equal by value, but not by reference \n", 711 | "df_new.index = new_index\n", 712 | "print(df_new.loc['a','Artist'])\n", 713 | "print(df_new.loc['a':'d','Artist'])" 714 | ] 715 | }, 716 | { 717 | "cell_type": "markdown", 718 | "metadata": {}, 719 | "source": [ 720 | "
Click here for the solution\n", 721 | "\n", 722 | "```python\n", 723 | "df_new=df\n", 724 | "df_new.index=new_index\n", 725 | "df_new.loc['a', 'Artist']\n", 726 | "df_new.loc['a':'d', 'Artist']\n", 727 | " \n", 728 | "```\n", 729 | "\n", 730 | "
\n" 731 | ] 732 | }, 733 | { 734 | "cell_type": "markdown", 735 | "metadata": {}, 736 | "source": [ 737 | "
\n", 738 | "

The last exercise!

\n", 739 | "

Congratulations, you have completed your first lesson and hands-on lab in Python. \n", 740 | "


\n" 741 | ] 742 | }, 743 | { 744 | "cell_type": "markdown", 745 | "metadata": {}, 746 | "source": [ 747 | "## Authors:\n", 748 | "\n", 749 | "[Joseph Santarcangelo](https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkPY0101ENSkillsNetwork19487395-2022-01-01)\n", 750 | "\n", 751 | "Joseph Santarcangelo has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.\n", 752 | "\n", 753 | "## Change Log\n", 754 | "\n", 755 | "| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n", 756 | "| ----------------- | ------- | ---------- | ---------------------------------- |\n", 757 | "| 2022-01-10 | 2.1 | Malika | Removed the readme for GitShare |\n", 758 | "| 2020-08-26 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n", 759 | "| 2020-11-24 | 3.0 | Nayef | Added new images |\n", 760 | "| | | | |\n", 761 | "\n", 762 | "
\n", 763 | "\n", 764 | "##

© IBM Corporation 2020. All rights reserved.

\n" 765 | ] 766 | } 767 | ], 768 | "metadata": { 769 | "anaconda-cloud": {}, 770 | "kernelspec": { 771 | "display_name": "Python", 772 | "language": "python", 773 | "name": "conda-env-python-py" 774 | }, 775 | "language_info": { 776 | "codemirror_mode": { 777 | "name": "ipython", 778 | "version": 3 779 | }, 780 | "file_extension": ".py", 781 | "mimetype": "text/x-python", 782 | "name": "python", 783 | "nbconvert_exporter": "python", 784 | "pygments_lexer": "ipython3", 785 | "version": "3.7.12" 786 | } 787 | }, 788 | "nbformat": 4, 789 | "nbformat_minor": 4 790 | } 791 | -------------------------------------------------------------------------------- /file handling exercise/file_eg1.py: -------------------------------------------------------------------------------- 1 | with open('readme.txt', 'a+') as testwritefile: 2 | print("Initial Location: {}".format(testwritefile.tell())) 3 | 4 | data = testwritefile.read() 5 | if (not data): #empty strings return false in python 6 | print('Read nothing') 7 | else: 8 | print(testwritefile.read()) 9 | 10 | testwritefile.seek(0,0) # move 0 bytes from beginning. 11 | 12 | print("\nNew Location : {}".format(testwritefile.tell())) 13 | data = testwritefile.read() 14 | if (not data): 15 | print('Read nothing') 16 | else: 17 | testwritefile.write('hello world\n') 18 | print(data) 19 | 20 | print("Location after read: {}".format(testwritefile.tell()) ) 21 | -------------------------------------------------------------------------------- /file handling exercise/file_eg2.py: -------------------------------------------------------------------------------- 1 | with open('readme.txt', 'r+') as testwritefile: 2 | data = testwritefile.readlines() 3 | testwritefile.seek(0,0) #write at beginning of file 4 | 5 | testwritefile.write("Line 1" + "\n") 6 | testwritefile.write("Line 2" + "\n") 7 | testwritefile.write("Line 3" + "\n") 8 | testwritefile.write("finished\n") 9 | #Uncomment the line below 10 | #testwritefile.truncate() 11 | testwritefile.seek(0,0) 12 | print(testwritefile.read()) 13 | 14 | -------------------------------------------------------------------------------- /file handling exercise/file_exercise.py: -------------------------------------------------------------------------------- 1 | # Exercise 2 | # Your local university's Raptors fan club maintains a register of its active members on a .txt document. Every month they update the file by removing the members who are not active. You have been tasked with automating this with your Python skills. 3 | # Given the file currentMem, Remove each member with a 'no' in their Active column. Keep track of each of the removed members and append them to the exMem file. Make sure that the format of the original files in preserved. (Hint: Do this by reading/writing whole lines and ensuring the header remains ) 4 | # Run the code block below prior to starting the exercise. The skeleton code has been provided for you. Edit only the cleanFiles function. 5 | 6 | from random import randint as rnd 7 | 8 | memReg = 'members.txt' 9 | exReg = 'inactive.txt' 10 | fee = ('yes', 'no') 11 | 12 | 13 | # generate some informations in files 14 | 15 | def genFiles(current, old): 16 | with open(current, 'w+') as writefile: 17 | writefile.write('Membership No Date Joined Active \n') 18 | data = "{:^13} {:<11} {:<6}\n" 19 | 20 | for rowno in range(20): 21 | date = str(rnd(2015, 2020)) + '-' + \ 22 | str(rnd(1, 12))+'-'+str(rnd(1, 25)) 23 | writefile.write(data.format( 24 | rnd(10000, 99999), date, fee[rnd(0, 1)])) 25 | 26 | with open(old, 'w+') as writefile: 27 | writefile.write('Membership No Date Joined Active \n') 28 | data = "{:^13} {:<11} {:<6}\n" 29 | for rowno in range(3): 30 | date = str(rnd(2015, 2020)) + '-' + \ 31 | str(rnd(1, 12))+'-'+str(rnd(1, 25)) 32 | writefile.write(data.format(rnd(10000, 99999), date, fee[1])) 33 | 34 | 35 | genFiles(memReg, exReg) 36 | 37 | 38 | ''' 39 | The two arguments for this function are the files: 40 | - currentMem: File containing list of current members 41 | - exMem: File containing list of old members 42 | 43 | This function removes all rows from currentMem containing 'no' 44 | in the 'Active' column and appends them to exMem. 45 | ''' 46 | 47 | 48 | def cleanFiles(currentMem, exMem): 49 | with open(currentMem, 'r+') as readfile: 50 | with open(exMem, 'a+') as appendfile: 51 | header = readfile.readline() 52 | list_of_lines = readfile.readlines() 53 | readfile.seek(0) 54 | readfile.write(header) 55 | for line in list_of_lines: 56 | if 'yes' in line: 57 | readfile.write(line) 58 | # print(line) # just to check if works 59 | else: 60 | appendfile.write(line) 61 | 62 | readfile.truncate() 63 | 64 | 65 | memReg = 'members.txt' 66 | exReg = 'inactive.txt' 67 | cleanFiles(memReg, exReg) 68 | 69 | # same as cleanFiles() function above, just different indent. 70 | # def cleanFiles_(currentMem, exMem): 71 | # with open(currentMem, 'r+') as readfile: 72 | # header = readfile.readline() 73 | # list_of_lines = readfile.readlines() 74 | # readfile.seek(0) 75 | # readfile.write(header) 76 | # for line in list_of_lines: 77 | # if 'yes' in line: 78 | # readfile.write(line) 79 | # print(line) 80 | # readfile.truncate() 81 | 82 | # with open(exMem, 'a+') as appendfile: 83 | # for line in list_of_lines: 84 | # if 'no' in line: 85 | # appendfile.write(line) 86 | 87 | 88 | # The code below is to help you view the files after cleaning above. 89 | headers = "Membership No Date Joined Active \n" 90 | with open(memReg, 'r') as readFile: 91 | print("Active Members: \n\n") 92 | print(readFile.read()) 93 | 94 | with open(exReg, 'r') as readFile: 95 | print("Inactive Members: \n\n") 96 | print(readFile.read()) 97 | 98 | 99 | # sample data 100 | # Membership No Date Joined Active 101 | # 44014 2020-6-12 no 102 | # 89670 2017-9-23 yes 103 | # 45860 2017-1-19 no 104 | # 77252 2017-9-3 no 105 | # 75242 2020-11-5 no 106 | # 89655 2018-8-6 no 107 | # 49878 2020-5-1 no 108 | # 65044 2019-12-24 no 109 | # 19725 2015-4-5 no 110 | # 22818 2017-5-4 no 111 | # 41366 2018-8-10 yes 112 | # 38772 2019-11-13 yes 113 | # 55186 2019-8-15 yes 114 | # 17742 2019-1-23 no 115 | # 81492 2019-11-6 yes 116 | # 79966 2020-2-18 no 117 | # 95802 2016-9-8 no 118 | # 28483 2017-9-2 yes 119 | # 47500 2018-12-12 no 120 | # 50210 2015-6-15 yes 121 | -------------------------------------------------------------------------------- /file handling exercise/file_exercise_with_test.py: -------------------------------------------------------------------------------- 1 | # Exercise : 2 | # Your local university's Raptors fan club maintains a register of its active members on a .txt document. Every month they update the file by removing the members who are not active. You have been tasked with automating this with your Python skills. 3 | # Given the file currentMem, Remove each member with a 'no' in their Active column. Keep track of each of the removed members and append them to the exMem file. Make sure that the format of the original files in preserved. (Hint: Do this by reading/writing whole lines and ensuring the header remains ) 4 | # Run the code block below prior to starting the exercise. The skeleton code has been provided for you. Edit only the cleanFiles function. 5 | 6 | # Run this prior to starting the exercise 7 | 8 | from random import randint as rnd 9 | 10 | memReg = 'members.txt' 11 | exReg = 'inactive.txt' 12 | fee = ('yes', 'no') 13 | 14 | 15 | def genFiles(current, old): 16 | with open(current, 'w+') as writefile: 17 | writefile.write('Membership No Date Joined Active \n') 18 | data = "{:^13} {:<11} {:<6}\n" 19 | 20 | for rowno in range(20): 21 | date = str(rnd(2015, 2020)) + '-' + \ 22 | str(rnd(1, 12))+'-'+str(rnd(1, 25)) 23 | writefile.write(data.format( 24 | rnd(10000, 99999), date, fee[rnd(0, 1)])) 25 | 26 | with open(old, 'w+') as writefile: 27 | writefile.write('Membership No Date Joined Active \n') 28 | data = "{:^13} {:<11} {:<6}\n" 29 | for rowno in range(3): 30 | date = str(rnd(2015, 2020)) + '-' + \ 31 | str(rnd(1, 12))+'-'+str(rnd(1, 25)) 32 | writefile.write(data.format(rnd(10000, 99999), date, fee[1])) 33 | 34 | 35 | genFiles(memReg, exReg) 36 | 37 | 38 | # Now that you've run the prerequisite code cell above, which prepared the files for this exercise, you are ready to move on to the implementation. 39 | 40 | # Exercise: Implement the cleanFiles function in the code cell below. 41 | 42 | 43 | ''' 44 | The two arguments for this function are the files: 45 | - currentMem: File containing list of current members 46 | - exMem: File containing list of old members 47 | 48 | This function should remove all rows from currentMem containing 'no' 49 | in the 'Active' column and appends them to exMem. 50 | ''' 51 | 52 | 53 | def cleanFiles(currentMem, exMem): 54 | 55 | with open(currentMem, 'r+') as readfile: # Open the currentMem file as in r+ mode 56 | with open(exMem, 'a+') as appendfile: # Open the exMem file in a+ mode 57 | # Hint: Recall that the first line in the file is the header. 58 | header = readfile.readline() 59 | # Read each member in the currentMem (1 member per row) file into a list. 60 | list_of_members = readfile.readlines() 61 | # Go to the beginning of the currentMem file 62 | readfile.seek(0) 63 | readfile.write(header) 64 | for line in list_of_members: # iterate through the members list 65 | if 'no' in line: # If a member is inactive, add them to exMem 66 | appendfile.write(line) 67 | # print(line) # just to check if works 68 | else: # otherwise write them into currentMem 69 | readfile.write(line) 70 | 71 | readfile.truncate() 72 | 73 | 74 | # The code below is to help you view the files. 75 | # Do not modify this code for this exercise. 76 | memReg = 'members.txt' 77 | exReg = 'inactive.txt' 78 | cleanFiles(memReg, exReg) 79 | 80 | 81 | headers = "Membership No Date Joined Active \n" 82 | with open(memReg, 'r') as readFile: 83 | print("Active Members: \n\n") 84 | print(readFile.read()) 85 | 86 | with open(exReg, 'r') as readFile: 87 | print("Inactive Members: \n\n") 88 | print(readFile.read()) 89 | 90 | 91 | # The code cell below is to verify your solution. Please do not modify the code and run it to test your implementation of cleanFiles. 92 | 93 | def testMsg(passed): 94 | if passed: 95 | return 'Test Passed' 96 | else: 97 | return 'Test Failed' 98 | 99 | 100 | testWrite = "testWrite.txt" 101 | testAppend = "testAppend.txt" 102 | passed = True 103 | 104 | genFiles(testWrite, testAppend) 105 | 106 | with open(testWrite, 'r') as file: 107 | ogWrite = file.readlines() 108 | 109 | with open(testAppend, 'r') as file: 110 | ogAppend = file.readlines() 111 | 112 | try: 113 | cleanFiles(testWrite, testAppend) 114 | except: 115 | print('Error') 116 | 117 | with open(testWrite, 'r') as file: 118 | clWrite = file.readlines() 119 | 120 | with open(testAppend, 'r') as file: 121 | clAppend = file.readlines() 122 | 123 | # checking if total no of rows is same, including headers 124 | 125 | if (len(ogWrite) + len(ogAppend) != len(clWrite) + len(clAppend)): 126 | print("The number of rows do not add up. Make sure your final files have the same header and format.") 127 | passed = False 128 | 129 | for line in clWrite: 130 | if 'no' in line: 131 | passed = False 132 | print("Inactive members in file") 133 | break 134 | else: 135 | if line not in ogWrite: 136 | print("Data in file does not match original file") 137 | passed = False 138 | print("{}".format(testMsg(passed))) 139 | -------------------------------------------------------------------------------- /file handling exercise/inactive.txt: -------------------------------------------------------------------------------- 1 | Membership No Date Joined Active 2 | 50276 2016-11-7 no 3 | 87105 2017-10-3 no 4 | 69311 2019-6-18 no 5 | 34715 2019-6-8 no 6 | 77918 2015-7-12 no 7 | 77534 2015-12-24 no 8 | 49179 2019-11-16 no 9 | 76493 2015-5-2 no 10 | 12437 2015-5-24 no 11 | 38400 2016-10-15 no 12 | 77325 2020-5-11 no 13 | -------------------------------------------------------------------------------- /file handling exercise/members.txt: -------------------------------------------------------------------------------- 1 | Membership No Date Joined Active 2 | 95957 2019-10-23 yes 3 | 63740 2017-10-24 yes 4 | 77939 2015-4-13 yes 5 | 66247 2020-7-20 yes 6 | 51220 2020-4-9 yes 7 | 63620 2020-6-18 yes 8 | 61797 2019-12-24 yes 9 | 51677 2018-5-7 yes 10 | 35915 2019-5-16 yes 11 | 45434 2016-5-24 yes 12 | 41852 2018-8-7 yes 13 | 97061 2019-7-6 yes 14 | -------------------------------------------------------------------------------- /file handling exercise/testAppend.txt: -------------------------------------------------------------------------------- 1 | Membership No Date Joined Active 2 | 37590 2019-8-8 no 3 | 72110 2016-7-3 no 4 | 38684 2019-8-10 no 5 | 17913 2018-7-22 no 6 | 13947 2020-1-19 no 7 | 13206 2015-3-8 no 8 | 54949 2020-2-13 no 9 | 61146 2018-10-5 no 10 | 55793 2018-10-12 no 11 | 65041 2019-10-24 no 12 | -------------------------------------------------------------------------------- /file handling exercise/testWrite.txt: -------------------------------------------------------------------------------- 1 | Membership No Date Joined Active 2 | 19043 2015-12-13 yes 3 | 55919 2020-9-11 yes 4 | 66060 2020-12-25 yes 5 | 93576 2019-9-19 yes 6 | 87260 2017-5-14 yes 7 | 26168 2016-8-24 yes 8 | 27639 2016-7-14 yes 9 | 24997 2019-2-21 yes 10 | 90913 2018-9-16 yes 11 | 45105 2020-12-24 yes 12 | 64196 2018-2-18 yes 13 | 36596 2017-4-8 yes 14 | 51222 2017-9-7 yes 15 | -------------------------------------------------------------------------------- /oop exercise/oops_text_analysis.py: -------------------------------------------------------------------------------- 1 | # Exercises 2 | # Text Analysis 3 | # You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class 'analysedText' with the following methods - 4 | 5 | # Constructor (__init__) - This method should take the argument text, make it lower case, and remove all punctuation. Assume only the following punctuation is used: period (.), exclamation mark (!), comma (,) and question mark (?). Assign this newly formatted text to a new attribute called fmtText. 6 | # freqAll - This method should create and return dictionary of all unique words in the text, along with the number of times they occur in the text. Each key in the dictionary should be the unique word appearing in the text and the associated value should be the number of times it occurs in the text. Create this dictionary from the fmtText attribute. 7 | # freqOf - This method should take a word as an argument and return the number of occurrences of that word in fmtText. 8 | 9 | import sys 10 | 11 | class analysedText(object): 12 | 13 | def __init__(self, text): 14 | 15 | # TODO: Remove the punctuation from and make it lower case. 16 | # punctuations = ['.', '!', ',', '?'] 17 | x = text.replace('.', '') 18 | x = x.replace('!', '') 19 | x = x.replace(',', '') 20 | x = x.replace('?', '') 21 | x = x.lower() 22 | 23 | # TODO: Assign the formatted text to a new attribute called "fmtText" 24 | self.fmtText = x 25 | pass 26 | 27 | 28 | def freqAll(self): 29 | 30 | # TODO: Split the text into a list of words 31 | words = self.fmtText.split(' ') 32 | 33 | # TODO: Create a dictionary with the unique words in the text as keys 34 | # and the number of times they occur in the text as values 35 | dict = {} 36 | for word in words: 37 | if word not in dict: 38 | dict[word] = 1 39 | else: 40 | dict[word] += 1 41 | return dict 42 | 43 | def freqOf(self, word): 44 | 45 | # TODO: return the number of occurrences of in 46 | occurence = self.freqAll()[word] 47 | # return self.fmtText.count(word) 48 | return occurence 49 | 50 | 51 | obj = analysedText( 52 | "Lorem ipsum dolor! diam amet, consetetur Lorem magna. sed diam nonumy eirmod tempor. diam et labore? et diam magna. et diam amet.") 53 | print(obj.freqAll()) 54 | print(obj.freqOf('et')) 55 | 56 | 57 | sampleMap = {'eirmod': 1, 'sed': 1, 'amet': 2, 'diam': 5, 'consetetur': 1, 'labore': 1, 58 | 'tempor': 1, 'dolor': 1, 'magna': 2, 'et': 3, 'nonumy': 1, 'ipsum': 1, 'lorem': 2} 59 | 60 | 61 | def testMsg(passed): 62 | if passed: 63 | return 'Test Passed' 64 | else: 65 | return 'Test Failed' 66 | 67 | 68 | # below code is for testing. 'do not change' 69 | print("Constructor: ") 70 | try: 71 | samplePassage = analysedText( 72 | "Lorem ipsum dolor! diam amet, consetetur Lorem magna. sed diam nonumy eirmod tempor. diam et labore? et diam magna. et diam amet.") 73 | print(testMsg(samplePassage.fmtText == 74 | "lorem ipsum dolor diam amet consetetur lorem magna sed diam nonumy eirmod tempor diam et labore et diam magna et diam amet")) 75 | except: 76 | print("Error detected. Recheck your function ") 77 | print("freqAll: ") 78 | try: 79 | wordMap = samplePassage.freqAll() 80 | print(testMsg(wordMap == sampleMap)) 81 | except: 82 | print("Error detected. Recheck your function ") 83 | print("freqOf: ") 84 | try: 85 | passed = True 86 | for word in sampleMap: 87 | if samplePassage.freqOf(word) != sampleMap[word]: 88 | print('err', word) 89 | passed = False 90 | break 91 | print(testMsg(passed)) 92 | 93 | except: 94 | print("Error detected. Recheck your function ") 95 | -------------------------------------------------------------------------------- /oop exercise/readme.md: -------------------------------------------------------------------------------- 1 |

Exercises

2 |

Text Analysis

3 | You have been recruited by your friend, a linguistics enthusiast, to create a utility tool that can perform analysis on a given piece of text. Complete the class 4 | 'analysedText' with the following methods - 5 | 6 |
    7 |
  • Constructor (__init__) - This method should take the argument text, make it lower case, and remove all punctuation. Assume only the following punctuation is used: period (.), exclamation mark (!), comma (,) and question mark (?). Assign this newly formatted text to a new attribute called fmtText. 8 |
  • freqAll - This method should create and return dictionary of all unique words in the text, along with the number of times they occur in the text. Each key in the dictionary should be the unique word appearing in the text and the associated value should be the number of times it occurs in the text. Create this dictionary from the fmtText attribute. 9 |
  • freqOf - This method should take a word as an argument and return the number of occurrences of that word in fmtText. 10 |
11 | The skeleton code has been given to you. Docstrings can be ignored for the purpose of the exercise.
12 | Hint: Some useful functions are replace(), lower(), split(), count()
13 | -------------------------------------------------------------------------------- /quizzes/Final Exam - Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Final Exam - Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Module 1 Graded Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Module 1 Graded Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Module 2 Graded Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Module 2 Graded Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Module 3 Graded Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Module 3 Graded Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Module 4 Graded Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Module 4 Graded Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Module 5 Graded Quiz.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Module 5 Graded Quiz.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Conditions and Branching.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Conditions and Branching.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Exception Handling.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Exception Handling.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - List and Tuples.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - List and Tuples.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Loops.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Loops.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - NumPy in Python.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - NumPy in Python.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Objects and Classes.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Objects and Classes.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Pandas.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Pandas.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - REST APIs & HTTP Requests.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - REST APIs & HTTP Requests.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Reading and Writing Files with Open.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Reading and Writing Files with Open.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Sets.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Sets.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Simple APIs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Simple APIs.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - String Operation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - String Operation.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Types.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Types.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz - Variables and Expression.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz - Variables and Expression.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz -Functions.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz -Functions.pdf -------------------------------------------------------------------------------- /quizzes/Practice Quiz- Dictionaries.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Practice Quiz- Dictionaries.pdf -------------------------------------------------------------------------------- /quizzes/Python Cheat Sheet - The Basics Coursera.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Python-for-Data-Science-AI-and-Development/ea7ba1811fd9d7df5e70721524ae2d582ec51dae/quizzes/Python Cheat Sheet - The Basics Coursera.pdf --------------------------------------------------------------------------------