{"cells":[{"cell_type":"markdown","metadata":{"id":"iSp3eA9a2TX3"},"source":["# **Basic Programming in Python**\n","For Numpy Library visit https://www.w3schools.com/python/numpy/default.asp"]},{"cell_type":"markdown","metadata":{"id":"u8E9QCWj2s6R"},"source":["## **What's Python**\n","  Python is a high level programming language\n"," - it uses an interpreter instead of compiler\n"," - easy to pick up\n"," - well documented and supported\n"," - it's a very flexible, high-level, general-purpose, dynamic programming language widely used in Machine learning and deep learning\n"]},{"cell_type":"markdown","metadata":{"id":"7hKT8LGN4gp-"},"source":["## **Variables and data types**\n","* In Python, we declare a variable by assigning it a value with the = sign\n","    * Variables are ***pointers***, not data stores!\n","* Python supports a variety of data types and structures:\n","    * booleans (True or False)\n","    * numbers (ints, floats, etc.)\n","    * strings\n","    * lists\n","    * dictionaries\n","    * many others!\n","* We don't specify a variable's type at assignment"]},{"cell_type":"markdown","metadata":{"id":"Ur5KbgpI4whc"},"source":["## **Basic Syntax**"]},{"cell_type":"markdown","metadata":{"id":"MV-4xHVn5PhW"},"source":["Variable naming convention: use lower case, separate words with an underscore"]},{"cell_type":"markdown","metadata":{"id":"jJ242Lv55XLl"},"source":["#### Comments"]},{"cell_type":"markdown","metadata":{"id":"HdLN9l1-5c4w"},"source":["A comment is a piece of text within a program that is not executed. It can be used to provide additional information to aid in understanding the code.\n","\n","Python interprets anything after a `#` as a comment.\n","- ****Single-line Comments****\n","    \n","    Inline comments should be used when you have a short comment that you would like to include after a line of code.\n","- ****Multi-line Comments****\n","\n","    Python does not have a specific syntax for multi-line comments, unlike some other languages.\n","    \n","    Instead, multiple `#` characters can be used\n","    \n","    Another, less official way of writing comments in Python is to use a multi-line string, created by surrounding text with triple quotes \"\"\"\n","\n","Comments can:\n","\n","- provide context for why something is written the way it is\n","- help other people reading the code understand it faster\n","- ignore a line of code and see how a program will run without it"]},{"cell_type":"code","execution_count":1,"metadata":{"executionInfo":{"elapsed":546,"status":"ok","timestamp":1701922557164,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"WsEveYoO40ai"},"outputs":[],"source":["# Comment on a single line\n","name = \"Pied Piper\" # Comment after code <- that's an inline short comment"]},{"cell_type":"code","execution_count":2,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":0,"status":"ok","timestamp":1701922557195,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"84yN6KAj41g4","outputId":"6dd991b6-3603-4e02-d8a7-4cbc371bc832"},"outputs":[{"name":"stdout","output_type":"stream","text":["Hello, World!\n"]}],"source":["# This is a comment written over\n","# more than one line\n","print(\"Hello, World!\")"]},{"cell_type":"code","execution_count":3,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":0,"status":"ok","timestamp":1701922557197,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"lDUFthiR41d6","outputId":"a637a570-6213-406c-cab1-21ccc405dd5a"},"outputs":[{"name":"stdout","output_type":"stream","text":["Hello, World!\n"]}],"source":["\"\"\"\n","This is a string written over\n","more than one line\n","\"\"\"\n","print(\"Hello, World!\")"]},{"cell_type":"markdown","metadata":{"id":"BhS4jsz_7Vae"},"source":["#### main()"]},{"cell_type":"markdown","metadata":{"id":"lNi-USJR7X-2"},"source":["We frequently use the **`main()`** function to define the starting point of our program. Including the **`main()`** function allows us to import and run this program in another script.\n","\n","Placing the if statement in our program basically checks whether the program is being run independently as the primary module or as a library in another script."]},{"cell_type":"code","execution_count":4,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":1069,"status":"ok","timestamp":1701922562962,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"WKe12QQ_7VJV","outputId":"45410be3-5179-4123-edff-c6d67b265fe0"},"outputs":[{"name":"stdout","output_type":"stream","text":["This line is printed directly from the main function of the program\n","This line is printed from a secondary function call within the main function\n"]}],"source":["def main():\n","  print('This line is printed directly from the main function of the program')\n","  secondary_function()\n","\n","def secondary_function():\n","  print('This line is printed from a secondary function call within the main function')\n","\n","if __name__ == '__main__':\n","  main()"]},{"cell_type":"markdown","metadata":{"id":"3WBMcoj28CBd"},"source":["#### print()"]},{"cell_type":"markdown","metadata":{"id":"r5Nbdpy68EOd"},"source":["The `print()` function accepts an object as a parameter, such as a string, a number, or a list. It is then converted to a string through an implicit call of the built-in `str()` function and the value is printed to an output stream.\n","\n","The object to be printed is passed to the `print()` function as a parameter:"]},{"cell_type":"code","execution_count":6,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":430,"status":"ok","timestamp":1701922577119,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"PRkw2sKl41bR","outputId":"34313061-dc51-47c9-e7a7-e4f161aa7f0c"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n"]}],"source":["object = '1'\n","print(object)"]},{"cell_type":"markdown","metadata":{"id":"IDMAEMWz_sn_"},"source":["#### Data Types"]},{"cell_type":"markdown","metadata":{"id":"fsLNi-to_vJ9"},"source":["- **Integer**\n","    \n","    We can specify that the variable is a integer by using a whole number or we can use **`int()`** to cast numerical variables as an integer.\n","    \n","- **Float**\n","    \n","    **`float()`** is the built-in function that stores numerical values with their decimal points.\n","    \n","- **Boolean**\n","    \n","    **`boolean`** variables hold two values, **`True`** or **`False`**. We can use the words **`True`** or **`False`** to assign it to our variable or use **`bool()`**.\n","    \n","- **String**\n","    \n","    **`string`** variables hold characters and can be created by using single quotes **`’`** or double quotes **`”`**. You can also use the built-in function **`str()`** to specify that you are storing a string."]},{"cell_type":"code","execution_count":7,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":655,"status":"ok","timestamp":1701922581347,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"4NqwdfaF9BXm","outputId":"f943da05-2fa0-402a-f5d7-aaa2f7dafbdd"},"outputs":[{"data":{"text/plain":["int"]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["# An integer. Notice the variable naming convention.\n","age_in_years = 28\n","type(age_in_years)"]},{"cell_type":"code","execution_count":8,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":7,"status":"ok","timestamp":1701922582195,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"DnK1J7gZ41Q1","outputId":"b2fa258b-1b23-4b7d-e413-f11e92694715"},"outputs":[{"data":{"text/plain":["float"]},"execution_count":8,"metadata":{},"output_type":"execute_result"}],"source":["# A float\n","almost_pi = 3.14\n","type(almost_pi)"]},{"cell_type":"code","execution_count":9,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":11,"status":"ok","timestamp":1701922582568,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"yzAhxpvkAz06","outputId":"c6995670-d16f-40ad-a9cf-52003529edc8"},"outputs":[{"data":{"text/plain":["bool"]},"execution_count":9,"metadata":{},"output_type":"execute_result"}],"source":["# A boolean takes on only the values True or False\n","enjoying_tutorial = True\n","type(enjoying_tutorial)"]},{"cell_type":"code","execution_count":10,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":9,"status":"ok","timestamp":1701922582569,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"WHgv7tY_AufQ","outputId":"6ff58e09-c320-4dcc-863c-95f038c361cc"},"outputs":[{"data":{"text/plain":["str"]},"execution_count":10,"metadata":{},"output_type":"execute_result"}],"source":["# A string\n","proton = \"P is for proton\"\n","type(proton)"]},{"cell_type":"code","execution_count":11,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":193},"executionInfo":{"elapsed":857,"status":"error","timestamp":1701922583421,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"kOjKFInOAub3","outputId":"f69e0f98-4651-44c7-9e12-1ef2bf87929c"},"outputs":[{"ename":"TypeError","evalue":"ignored","output_type":"error","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)","\u001b[0;32m<ipython-input-11-470e529ce94a>\u001b[0m in \u001b[0;36m<cell line: 2>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;31m#string are immutable (cannot be changed)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mproton\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m\"s\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment"]}],"source":["#string are immutable (cannot be changed)\n","proton[3] = \"s\""]},{"cell_type":"markdown","metadata":{"id":"Zh7XN-PPU6Lg"},"source":["#### Operators"]},{"cell_type":"markdown","metadata":{"id":"fZFFMi9qVCdq"},"source":["Operators are used to perform operations on variables in Python. We will cover the following operators in this article:\n","\n","- **Arithmetic Operators**\n","    \n","    they are used to perform mathematical operations on numerical variables such as int or float\n"]},{"cell_type":"code","execution_count":15,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":480,"status":"ok","timestamp":1701922752501,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"esDvUPNnsApE","outputId":"fb4e6256-159f-44c9-eb87-a28b02f27edd"},"outputs":[{"data":{"text/plain":["7"]},"execution_count":15,"metadata":{},"output_type":"execute_result"}],"source":["#Arithmetic Operators\n","x = 4\n","y = 3\n","\n","x + y"]},{"cell_type":"code","execution_count":16,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":432,"status":"ok","timestamp":1701922756492,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"OdAxyUUbf3kb","outputId":"f01ad453-29df-48b3-d85e-77e7e68a3ea4"},"outputs":[{"data":{"text/plain":["1"]},"execution_count":16,"metadata":{},"output_type":"execute_result"}],"source":["x - y"]},{"cell_type":"code","execution_count":17,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":468,"status":"ok","timestamp":1701922760710,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"wfvYesBIf5Xe","outputId":"1bdfaff1-8d34-4fe2-d970-921e9d94252c"},"outputs":[{"data":{"text/plain":["12"]},"execution_count":17,"metadata":{},"output_type":"execute_result"}],"source":["x * y"]},{"cell_type":"code","execution_count":18,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":482,"status":"ok","timestamp":1701922764543,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"v42eXsMLf7UC","outputId":"da56cbf9-0f0b-4182-fe40-f36db3f78c2f"},"outputs":[{"data":{"text/plain":["64"]},"execution_count":18,"metadata":{},"output_type":"execute_result"}],"source":["x ** y"]},{"cell_type":"code","execution_count":19,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":398,"status":"ok","timestamp":1701922768486,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"ywm84SIUf8xz","outputId":"b21b3e45-94d6-4cdf-a2a1-a81865d7879b"},"outputs":[{"data":{"text/plain":["1.3333333333333333"]},"execution_count":19,"metadata":{},"output_type":"execute_result"}],"source":["x / y"]},{"cell_type":"code","execution_count":20,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":470,"status":"ok","timestamp":1701922772778,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"DrF-Ho8Rf_gb","outputId":"adde0508-63a4-467a-e197-38936ccac7b6"},"outputs":[{"data":{"text/plain":["1"]},"execution_count":20,"metadata":{},"output_type":"execute_result"}],"source":["x // y"]},{"cell_type":"code","execution_count":21,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":392,"status":"ok","timestamp":1701922776345,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"KbZSVKGFgAON","outputId":"bc3bf787-3bb8-4753-ec08-481bacf70b53"},"outputs":[{"data":{"text/plain":["1"]},"execution_count":21,"metadata":{},"output_type":"execute_result"}],"source":["x % y"]},{"cell_type":"markdown","metadata":{"id":"aVns_a5qr2FA"},"source":["- **Assignment Operators**\n","\n","    - assignment operator **`=`**, is used to assign values to variables\n","    - compound assignment operator are used to perform arithmetic operations on a variable and reassign its value at the same time\n","  "]},{"cell_type":"code","execution_count":24,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":446,"status":"ok","timestamp":1701922813736,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"W5Sv9F-WsAJp","outputId":"097b3c4f-6382-4efe-9371-cfb52774659c"},"outputs":[{"data":{"text/plain":["8"]},"execution_count":24,"metadata":{},"output_type":"execute_result"}],"source":["#Assignment Operators\n","x += 4\n","x"]},{"cell_type":"code","execution_count":25,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":382,"status":"ok","timestamp":1701922823506,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"ujn2ovvvgNup","outputId":"a1c7b1b4-a018-4107-a279-42d0446711d5"},"outputs":[{"data":{"text/plain":["4"]},"execution_count":25,"metadata":{},"output_type":"execute_result"}],"source":["x -= 4\n","x"]},{"cell_type":"code","execution_count":26,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":528,"status":"ok","timestamp":1701922841202,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"jiwT0BvNgXGs","outputId":"3b61dd63-f013-401d-8e25-9bf61f742dc4"},"outputs":[{"data":{"text/plain":["16"]},"execution_count":26,"metadata":{},"output_type":"execute_result"}],"source":["x *= 4\n","x"]},{"cell_type":"code","execution_count":28,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":559,"status":"ok","timestamp":1701922853067,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"sZOPgehugagC","outputId":"95d675be-4d14-440c-b6cc-4e7ff64c6071"},"outputs":[{"data":{"text/plain":["0.0"]},"execution_count":28,"metadata":{},"output_type":"execute_result"}],"source":["x /= 4\n","x"]},{"cell_type":"code","execution_count":30,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":631,"status":"ok","timestamp":1701922892403,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"1WVwgge6gdBh","outputId":"709e482c-234b-4e09-8a90-665eb26db337"},"outputs":[{"data":{"text/plain":["0.0"]},"execution_count":30,"metadata":{},"output_type":"execute_result"}],"source":["x %= 4\n","x"]},{"cell_type":"markdown","metadata":{"id":"srM1jdorr36Z"},"source":["- **Comparison Operators**\n","    \n","    comparison operators are used to compare two variables. The result from these operators is a bool ((**`True`** or **`False`**)"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"Sa5ajaOTsENt"},"outputs":[],"source":["#Comparision Operators\n","x = 4\n","y = 3\n","\n","x == y"]},{"cell_type":"code","execution_count":38,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":371,"status":"ok","timestamp":1701922992945,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"I8Ds88LKgoc-","outputId":"b9dee817-8072-4554-c559-c3cc2ceb809d"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":38,"metadata":{},"output_type":"execute_result"}],"source":["x != y"]},{"cell_type":"code","execution_count":39,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":6,"status":"ok","timestamp":1701922993628,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"mHuiCGO9gqHw","outputId":"0f178fba-06e1-45b6-8c8b-ce35f238de23"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":39,"metadata":{},"output_type":"execute_result"}],"source":["x > y"]},{"cell_type":"code","execution_count":40,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701922994143,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"7jIBfCqMgrpM","outputId":"8fe0b884-a4f2-4c3b-e935-246a3999a088"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":40,"metadata":{},"output_type":"execute_result"}],"source":["x < y"]},{"cell_type":"code","execution_count":41,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":6,"status":"ok","timestamp":1701922994883,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"7zEv9ITRgtFq","outputId":"26f21a01-2c0f-4c4c-dccc-d1f906398e5b"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":41,"metadata":{},"output_type":"execute_result"}],"source":["x >= y"]},{"cell_type":"code","execution_count":42,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701922995912,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"cVYH1apxgvJa","outputId":"1b381870-e87a-4048-e0ba-a22109445f4f"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":42,"metadata":{},"output_type":"execute_result"}],"source":["x <= y"]},{"cell_type":"markdown","metadata":{"id":"mlk9RTaMr6tW"},"source":["- **Logical Operators**\n","    \n","    Logical operators are used to combine and evaluate multiple conditions. The result is a bool (**`True`** or **`False`**)."]},{"cell_type":"code","execution_count":43,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":872,"status":"ok","timestamp":1701923095926,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"IE_sbN1CsEj1","outputId":"c6397213-1448-413e-e209-1e2de188812b"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":43,"metadata":{},"output_type":"execute_result"}],"source":["#Logical Operators\n","x = 4\n","y = 3\n","\n","x > 2 and y > 1"]},{"cell_type":"code","execution_count":46,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":817,"status":"ok","timestamp":1701923110206,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"pOe-OFP8hC83","outputId":"83aa2625-c0d3-4bcb-cb85-a7e45c2c03ab"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":46,"metadata":{},"output_type":"execute_result"}],"source":["x > 5 or y <= 3"]},{"cell_type":"code","execution_count":45,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":13,"status":"ok","timestamp":1701923099011,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"5X6MpQn_hW3v","outputId":"4843ee8a-6067-4061-c41e-eb2756e8b85d"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":45,"metadata":{},"output_type":"execute_result"}],"source":["not(x > 2 and y > 1)"]},{"cell_type":"markdown","metadata":{"id":"qp2_1rJKO5r4"},"source":["## **Control Flow**"]},{"cell_type":"markdown","metadata":{"id":"rdEfigh5PB3Z"},"source":["1. **if, elif, else - Conditional Statements**\n","    \n","    These are known as conditional statements which are used to execute a sequence of code based on the given boolean values.\n","    \n","    - **`if` Statements**\n","        \n","        it evaluates whether the given expression is evaluated as **`True`**, then the code is executed.\n","    - **`else` Statements**\n","    \n","    Adding an **`else`** statement after an **`if`** statement allows for another set of code to be ran if the **`if`** statement evaluates the expression to be **`False`**.\n","    - **`elif` Statements**\n","    \n","    An **`elif`** statement, which is short for *else if*, can be added between an **`if`** statement and an **`else`** statement to evaluate for another condition. The code under the **`elif`** statement will only execute if the preceding **`if`** statement evaluates to be **`False`**."]},{"cell_type":"code","execution_count":47,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":704,"status":"ok","timestamp":1701923121137,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"YP8gsaw7PBi1","outputId":"347522fa-1c61-4969-fe35-7fdd2242fb73"},"outputs":[{"name":"stdout","output_type":"stream","text":["You pass the course! Talk to your instructor.\n"]}],"source":["score = 70\n","\n","if score >= 80:\n","   print('You pass the course with flying colors!')\n","\n","elif score > 65:\n","   print('You pass the course! Talk to your instructor.')\n","\n","else:\n","   print('You do not pass the course!')"]},{"cell_type":"markdown","metadata":{"id":"5VE2PYk8Q9AB"},"source":["2. **Loops**\n","    \n","    A *loop* is used to execute code repeatedly in Python.\n","    \n","    - **`for` loops**\n","        \n","        The **`for`** loop is used to iterate over items and execute code on each item. It has two keywords, **`for`** and **`in`**, which are used to describe the element and the object that is being iterated over, respectively. The indentation after **`:`** starts the body of the loop.\n","    - **`for` loops with `range()`**\n","    \n","    The **`range()`** function can be used with the **`for`** loop to execute a block of code multiple times.\n","    - **Nested `for` loops**\n","    \n","    A **`for`** loop can have *nested* **`for`** loops. This is particularly useful if the items you are iterating over contain subitems.\n","\n","  - **`while` loops**\n","    \n","    The **`while`** loop is used to execute code while its condition evaluates to be **`True`**."]},{"cell_type":"code","execution_count":48,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":553,"status":"ok","timestamp":1701923125138,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"fLaddozhRFi-","outputId":"3d4421d1-8ad4-439f-c34d-f9a7b4ea255a"},"outputs":[{"name":"stdout","output_type":"stream","text":["2\n","3\n","4\n","5\n","6\n"]}],"source":["# for loop\n","nums = [1, 2, 3, 4, 5]\n","\n","for num in nums:\n","  print(num + 1)"]},{"cell_type":"code","execution_count":49,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":518,"status":"ok","timestamp":1701923125649,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"lOOmK9U2RUPv","outputId":"2d0fa16d-94e0-4a9f-cd51-677bcd47d7c6"},"outputs":[{"name":"stdout","output_type":"stream","text":["0\n","1\n","2\n"]}],"source":["#for loop with range()\n","for i in range(3):\n","  print(i)\n","#The code below iterates between numbers 0 to 2 and prints each number"]},{"cell_type":"code","execution_count":50,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923125650,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"SgDsV0VHRZs-","outputId":"21f83bec-a2df-4ed1-99d6-48ebabdd36cd"},"outputs":[{"name":"stdout","output_type":"stream","text":["Jody\n","Abe\n","Abhishek\n","Kim\n","Taylor\n","Jen\n"]}],"source":["#nested for loop\n","teams = [['Jody', 'Abe'], ['Abhishek', 'Kim'], ['Taylor', 'Jen']]\n","for team in teams:\n","  for name in team:\n","    print(name)\n","\n","#we have a list of lists called teams and we can use a nested for loop to print each name in the lists"]},{"cell_type":"code","execution_count":51,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":10,"status":"ok","timestamp":1701923126469,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"M0OMHqp1Rr1b","outputId":"792988a9-8a56-4498-a300-aa3e51d47b34"},"outputs":[{"name":"stdout","output_type":"stream","text":["1\n","2\n","3\n","4\n","5\n"]}],"source":["#while loop\n","i = 1\n","while i < 6:\n","  print(i)\n","  i += 1\n","# the while loop will run and print i as long as the value of i is less than 6"]},{"cell_type":"markdown","metadata":{"id":"OBgazBNNR2wq"},"source":["3. **Error Handling**\n","    \n","    In programming, error handling refers to the process of anticipating and resolving errors when they arise. Error handling allows for flexibility in the code as it executes different blocks of code based on the presence of errors.\n","    \n","    These clauses can be used together to execute different blocks of code in situations where there may be errors in the first block of code.\n","    \n","    - **`try` and `except`**\n","        \n","    The clause **`try`** attempts to execute a block of code and **`except`** executes another block of code if **`try`** fails.\n","    - **`finally`**\n","    \n","    The **`finally`** clause executes a block of code regardless of which clause, **`try`** or **`except`**, was executed. The **`finally`** clause is useful in cases where both of your **`try`** and **`except`** might fail."]},{"cell_type":"code","execution_count":52,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":517,"status":"ok","timestamp":1701923130588,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"Rg1XXNN7SAhV","outputId":"88f63970-e5f6-4818-d9fa-618e16d38e21"},"outputs":[{"name":"stdout","output_type":"stream","text":["6\n","Cannot print the sum! Your variables are not numbers.\n"]}],"source":["#error handling\n","nums = [0, 1, 2, 3]\n","\n","try:\n","   print(sum(nums))\n","\n","except:\n","   print('Cannot print the sum! Your variables are not numbers.')\n","# success because the nums is a list of integers\n","\n","nums = ['x', 'y', 'z']\n","\n","try:\n","   print(sum(nums))\n","\n","except:\n","   print('Cannot print the sum! Your variables are not numbers.')\n","#fail because the list nums has strings -> the code under except will be executed"]},{"cell_type":"code","execution_count":53,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":364,"status":"ok","timestamp":1701923135874,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"J7engNaSSFts","outputId":"76895ebf-a821-4b52-b0b5-ff47f052514b"},"outputs":[{"name":"stdout","output_type":"stream","text":["Cannot print the sum! Your variables are not numbers.\n","Hope you got the result you want!\n"]}],"source":["#finally\n","nums = ['x', 'y', 'z']\n","\n","try:\n","   print(sum(nums))\n","\n","except:\n","   print('Cannot print the sum! Your variables are not numbers.')\n","\n","finally:\n","   print('Hope you got the result you want!')"]},{"cell_type":"markdown","metadata":{"id":"vyNLS67p9BXo"},"source":["## **Data structures**\n","* Most code requires more complex structures built out of basic data types\n","* Python provides built-in support for many common structures\n","    * Many additional structures can be found in the [collections](https://docs.python.org/3/library/collections.html) module"]},{"cell_type":"markdown","metadata":{"id":"kICwwHyL9BXo"},"source":["#### Lists\n","* An ordered, heterogeneous collection of objects\n","* List elements can be accessed by position\n","* The syntax for creating a list is square brackets --> list = []\n","    * Technically you can also declare a list like this: list = list() --> but the square brackets method is more common"]},{"cell_type":"code","execution_count":54,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":35},"executionInfo":{"elapsed":449,"status":"ok","timestamp":1701923146268,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"iErnrOer9BXo","outputId":"3bba127e-1157-4442-94dc-44e6a82988d8"},"outputs":[{"data":{"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"},"text/plain":["'abcd'"]},"execution_count":54,"metadata":{},"output_type":"execute_result"}],"source":["random_stuff = [\"1\",3,\"some gibirish 4\",\"abcd\",[12323,\"23\"],3434]\n","random_stuff[3]"]},{"cell_type":"code","execution_count":55,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923146943,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"dcXTHpOM9BXo","outputId":"8ca6e241-5613-41b2-f466-e06f3e82c7a7"},"outputs":[{"data":{"text/plain":["6"]},"execution_count":55,"metadata":{},"output_type":"execute_result"}],"source":["len(random_stuff)"]},{"cell_type":"code","execution_count":56,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":14,"status":"ok","timestamp":1701923147540,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"uDkqjORp9BXo","outputId":"ea0ae899-d990-4306-db0c-3d1fa8ed166b"},"outputs":[{"data":{"text/plain":["[3, 'abcd', 3434]"]},"execution_count":56,"metadata":{},"output_type":"execute_result"}],"source":["# We can also slice lists\n","random_stuff[1:6:2]"]},{"cell_type":"code","execution_count":57,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":8,"status":"ok","timestamp":1701923147540,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"MpJpol4U9BXo","outputId":"7561c645-c84f-4a41-8c72-88d348538c63"},"outputs":[{"data":{"text/plain":["['1', 3, 'some gibirish 4', 'abcd', [12323, '23'], 3434, 'added element']"]},"execution_count":57,"metadata":{},"output_type":"execute_result"}],"source":["# Append an element\n","random_stuff.append(\"added element\")\n","random_stuff"]},{"cell_type":"code","execution_count":58,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701923148056,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"NfbLvJ-EbvpQ","outputId":"8957fb8f-3a5a-45a8-dd5b-e0b3a03e919a"},"outputs":[{"data":{"text/plain":["['1',\n"," 3,\n"," 'some gibirish 4',\n"," 'abcd',\n"," [12323, '23'],\n"," 3434,\n"," 'added element',\n"," 1,\n"," 2,\n"," 3]"]},"execution_count":58,"metadata":{},"output_type":"execute_result"}],"source":["#extend lists\n","random_stuff.extend([1,2,3])\n","random_stuff"]},{"cell_type":"code","execution_count":59,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701923149560,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"PjYV8zZLbvpQ","outputId":"e2e88c7b-5f09-486e-825d-ba793c584575"},"outputs":[{"data":{"text/plain":["[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]"]},"execution_count":59,"metadata":{},"output_type":"execute_result"}],"source":["#Another format to define lists\n","squares=[i**2 for i in range(11)]\n","squares"]},{"cell_type":"markdown","metadata":{"id":"QZ9D-QwV9BXo"},"source":["#### Tuples\n","* Very similar to lists\n","* Key difference: tuples are *immutable*\n","    * They can't be modified once they're created\n","* Syntax for declaring a tuple is with parentheses --> my_tuple = ()"]},{"cell_type":"code","execution_count":60,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":483,"status":"ok","timestamp":1701923157964,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"hm0R-f9R9BXp","outputId":"02a8e6c2-f0b7-4a2a-8371-c0e02d95f99f"},"outputs":[{"data":{"text/plain":["1"]},"execution_count":60,"metadata":{},"output_type":"execute_result"}],"source":["random_tuple = (1,2,3,4,5,6,[7])\n","random_tuple[0]"]},{"cell_type":"code","execution_count":61,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":176},"executionInfo":{"elapsed":10,"status":"error","timestamp":1701923158498,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"1Il8EUqtbvpQ","outputId":"5d7b74c0-f8e5-4cc2-f30d-8d09efdc00a5"},"outputs":[{"ename":"TypeError","evalue":"ignored","output_type":"error","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)","\u001b[0;32m<ipython-input-61-f9d051e6746f>\u001b[0m in \u001b[0;36m<cell line: 1>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mrandom_tuple\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment"]}],"source":["random_tuple[0]=3"]},{"cell_type":"markdown","metadata":{"id":"MXI6Ing79BXp"},"source":["#### Dictionaries (dict)\n","* Unordered collection of key-to-value pairs\n","* dict elements can be accessed by key, but *not* by position\n","* Syntax for creating a dictionary is curly brackets --> my_dictionary = {}\n","    * you could declare it like this: my_dictionary = dict() --> but again, the curly brackets method is more common"]},{"cell_type":"code","execution_count":62,"metadata":{"executionInfo":{"elapsed":597,"status":"ok","timestamp":1701923183753,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"0z9vytd-9BXp"},"outputs":[],"source":["# A dictionary is an unordered mapping from keys to values\n","fruit_prices = {\n","    'apple': 0.65,\n","    'mango': 1.50,\n","    'strawberry': '$3/lb',\n","    'durian': 'unavailable',\n","    # 123:123,\n","}"]},{"cell_type":"code","execution_count":63,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":15,"status":"ok","timestamp":1701923184437,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"IQeevf6u9BXp","outputId":"1dc1a0f4-f011-4fe4-c181-e09f9b5dbc84"},"outputs":[{"data":{"text/plain":["1.5"]},"execution_count":63,"metadata":{},"output_type":"execute_result"}],"source":["# What's the price of a mango?\n","fruit_prices[\"mango\"]"]},{"cell_type":"code","execution_count":64,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":13,"status":"ok","timestamp":1701923184438,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"qJXCAk-s9BXp","outputId":"d62ac0cf-cb69-4ac8-ae45-c524173d5018"},"outputs":[{"data":{"text/plain":["{'apple': 0.65,\n"," 'mango': 1.5,\n"," 'strawberry': '$3/lb',\n"," 'durian': 'unavailable',\n"," 'pear': 0.25}"]},"execution_count":64,"metadata":{},"output_type":"execute_result"}],"source":["# Add a new entry for pears\n","fruit_prices[\"pear\"]=0.25\n","fruit_prices"]},{"cell_type":"markdown","metadata":{"id":"BjCTtQrm9BXp"},"source":["## **Everything is an object in Python**\n","* All of these 'data types' are actually just objects in Python\n","* *Everything* is an object in Python!\n","* The operations you can perform with a variable depend on the object's definition\n","* E.g., the multiplication operator * is defined for some objects but not others"]},{"cell_type":"code","execution_count":65,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":538,"status":"ok","timestamp":1701923188933,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"jqCC5XGs9BXp","outputId":"94cd959c-4b73-4466-a882-8ea33280eeb3"},"outputs":[{"data":{"text/plain":["6"]},"execution_count":65,"metadata":{},"output_type":"execute_result"}],"source":["# Multiply an int by 2\n","3*2"]},{"cell_type":"code","execution_count":66,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":15,"status":"ok","timestamp":1701923189553,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"KZJsa00E9BXp","outputId":"a2c71fe7-4bac-4f38-acc3-305545bd62f3"},"outputs":[{"data":{"text/plain":["6.28"]},"execution_count":66,"metadata":{},"output_type":"execute_result"}],"source":["# Multiply a float by 2\n","almost_pi*2"]},{"cell_type":"code","execution_count":67,"metadata":{"colab":{"base_uri":"https://localhost:8080/","height":35},"executionInfo":{"elapsed":14,"status":"ok","timestamp":1701923189554,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"QSsnJQrL9BXp","outputId":"04454f1a-5cc8-4046-a612-1e4d5f65916b"},"outputs":[{"data":{"application/vnd.google.colaboratory.intrinsic+json":{"type":"string"},"text/plain":["'abcabcabc'"]},"execution_count":67,"metadata":{},"output_type":"execute_result"}],"source":["# What about a string?\n","\"abc\"*3"]},{"cell_type":"code","execution_count":68,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1701923190074,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"CV2hkm3b9BXp","outputId":"d260c9e8-7a16-4eee-ae8a-b0321970210c"},"outputs":[{"data":{"text/plain":["[1, 2, 3, 1, 2, 3, 1, 2, 3]"]},"execution_count":68,"metadata":{},"output_type":"execute_result"}],"source":["# A list?\n","[1,2,3]*3"]},{"cell_type":"markdown","metadata":{"id":"MRZD511P9BXw"},"source":["\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","\n","## **Functions**\n","* A block of code that only runs when explicitly called\n","* Can accept arguments (or parameters) that alter its behavior\n","* Can accept any number/type of inputs, but always return a single object\n","    * Note: functions can return tuples (may *look like* multiple objects)"]},{"cell_type":"code","execution_count":69,"metadata":{"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923195209,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"Aw_MLDfD9BXw"},"outputs":[],"source":["# We'll need the random module for this\n","import random\n","\n","def add_noise(x, mu, sd):\n","    ''' Adds gaussian noise to the input.\n","\n","    Parameters:\n","        x (number): The number to add noise to\n","        mu (float): The mean of the gaussian noise distribution\n","        sd (float): The standard deviation of the noise distribution\n","\n","    Returns: A float.\n","    '''\n","    noise = random.normalvariate(mu, sd)\n","    return (x + noise)"]},{"cell_type":"code","execution_count":70,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701923195689,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"Qh7x-gY_XOIz","outputId":"00d6e34c-a408-4916-9820-c2de14bcc80f"},"outputs":[{"data":{"text/plain":["(4.243197300725699, 2.626658076492884, 3.3213030888752333)"]},"execution_count":70,"metadata":{},"output_type":"execute_result"}],"source":["# Let's try calling it...\n","add_noise(5,0,2),add_noise(5,0,2),add_noise(5,0,2)"]},{"cell_type":"markdown","metadata":{"id":"ZnWfvCBR9BXw"},"source":["### Positional vs. keyword arguments\n","* Positional arguments are defined by position and *must* be passed\n","    * Arguments in the function signature are filled in order\n","* Keyword arguments have a default value\n","    * Arguments can be passed in arbitrary order (after any positional arguments)"]},{"cell_type":"code","execution_count":71,"metadata":{"executionInfo":{"elapsed":4,"status":"ok","timestamp":1701923197046,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"LOtMNqc79BXw"},"outputs":[],"source":["def add_noise_with_defaults(x, mu=0, sd=1):\n","    ''' Adds gaussian noise to the input.\n","\n","    Parameters:\n","        x (number): The number to add noise to\n","        mu (float): The mean of the gaussian noise distribution\n","        sd (float): The standard deviation of the noise distribution\n","\n","    Returns: A float.\n","    '''\n","    noise = random.normalvariate(mu, sd)\n","    return x + noise"]},{"cell_type":"code","execution_count":75,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":914,"status":"ok","timestamp":1701923243817,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"lAIEdpgG9BXx","outputId":"2f68bab0-a523-4343-afcd-231a58d6082b"},"outputs":[{"data":{"text/plain":["6.0"]},"execution_count":75,"metadata":{},"output_type":"execute_result"}],"source":["# Let's call it again\n","add_noise(5,0,2)\n","add_noise(5,sd=0,mu=2)\n","add_noise(sd=0,x=2, mu=4)"]},{"cell_type":"code","execution_count":76,"metadata":{"executionInfo":{"elapsed":469,"status":"ok","timestamp":1701923250542,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"W9Q7qeUfWu2U"},"outputs":[],"source":["def sum_args(*args):\n","  print(args[0] + args[1])"]},{"cell_type":"code","execution_count":77,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":6,"status":"ok","timestamp":1701923251780,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"x_tlBSRsXCnV","outputId":"fe7c0bda-b102-47ac-d0a0-dbeaddfd1f6c"},"outputs":[{"name":"stdout","output_type":"stream","text":["5\n"]}],"source":["sum_args(1, 4, 5, 7)"]},{"cell_type":"markdown","metadata":{"id":"xGLHhkuhyS38"},"source":["### Most used built-in functions"]},{"cell_type":"markdown","metadata":{"id":"5IgJRp8jykOY"},"source":["- **`len()`** - This function returns the length of an object, such as a string or a list.\n","- **`int()`** - This function converts a string or a floating-point number to an integer.\n","- **`float()`** - This function converts a string or an integer to a floating-point number.  \n","-**`str()`** - This function converts any object to a string.\n","-**`sum()`** - This function calculates the sum of a list of numbers.\n","sorted() - This function returns a sorted list.\n","-**`max()`** - This function returns the largest item in an iterable or the\n","largest of two or more arguments.\n","-**`min()`** - This function returns the smallest item in an iterable or the\n","smallest of two or more arguments.\n"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"vmB46XyCyZzR"},"outputs":[],"source":["len(\"Hello, World!\") #returns 13\n","int(123.5)  #returns 123\n","float(\"3.14\")  #returns 3.14\n","str(123)  #returns \"123\"\n","sum([1, 2, 3, 4, 5])  #returns 15\n","sorted([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])  #returns [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]\n","max([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])  #returns 9\n","min([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])  #returns 1"]},{"cell_type":"markdown","metadata":{"id":"3ZkK0L5V9BXx"},"source":["## **Classes**\n","* A template for a particular kind of object\n","* A class defines the variables an object contains and what it can do with them\n","* To illustrate, let's define a `Circle` class...\n","* Note: object-oriented programming can be a bit hard to understand at first"]},{"cell_type":"markdown","metadata":{"id":"5wXMM7TUbvpV"},"source":["### Magic methods\n","* Methods padded with `__` have a variety of special functions in Python\n","* E.g., `__init__` and/or `__new__` are called when an object is initialized\n","* All operators in Python are actually just cleverly-disguised method calls\n","* E.g., the code `age_in_years * 2` is actually equivalent to `age_in_years.__mul__(2)`\n","* Any object that implements the `__mul__` method can use the `*` operator"]},{"cell_type":"code","execution_count":78,"metadata":{"executionInfo":{"elapsed":407,"status":"ok","timestamp":1701923271567,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"JIfQYyhP9BXx"},"outputs":[],"source":["# We need pi!\n","import math\n","\n","# Write a Circle class that takes a radius argument at initialization\n","# and has area() and copy() instance methods that return the circle's\n","# area and a copy of the circle, respectively.\n","class Circle:\n","    def __init__(self,r=1,x=0,y=0):#constructor\n","        self.r=r\n","        self.x=x\n","        self.y=y\n","\n","    def area(self):\n","        return self.r**2*math.pi\n","\n","    def copy(self):\n","        return Circle(r=self.r,x=self.x,y=self.y)\n","\n","    def __call__(self):#when defined, any instance can be called\n","        return self.area()\n","\n"]},{"cell_type":"code","execution_count":79,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923272098,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"B15QSBfC9BXx","outputId":"582fa825-5fb2-4bb0-c6ed-9d35d586c642"},"outputs":[{"data":{"text/plain":["(28.274333882308138, 28.274333882308138)"]},"execution_count":79,"metadata":{},"output_type":"execute_result"}],"source":["# Now let's make use of our class. First, initialize a new Circle.\n","circle=Circle(x=3,r=3)\n","circle.area(),circle()"]},{"cell_type":"code","execution_count":80,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923272526,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"gANlbEWn9BXx","outputId":"deeb1b5f-4b80-4100-bbbd-a03ffc5d00d6"},"outputs":[{"data":{"text/plain":["3"]},"execution_count":80,"metadata":{},"output_type":"execute_result"}],"source":["circle.r"]},{"cell_type":"markdown","metadata":{"id":"tz37m3jcb5DG"},"source":["### Constructors and Destructors"]},{"cell_type":"markdown","metadata":{"id":"YxRDLlobh63S"},"source":["**Constructors** are functions that are called when an object of a class is created and destructors are called to delete an object.\n","- Constructors are special functions that are executed when an object is instantiated. In Python, the `__init__()` function is used as the constructor and is called when creating an object.\n","\n","**`init()`**\n","\n","It is common practice for classes to contain Python’s built-in `__init__() ` method as the constructor."]},{"cell_type":"code","execution_count":81,"metadata":{"executionInfo":{"elapsed":2,"status":"ok","timestamp":1701923274654,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"beifoSMsjJ8w"},"outputs":[],"source":["class Circle:\n","    def __init__(self,r=1,x=0,y=0):#constructor\n","        self.r=r\n","        self.x=x\n","        self.y=y"]},{"cell_type":"markdown","metadata":{"id":"ZTZ5Iou9jEdP"},"source":["**Instance Variables**\n","\n","The self parameter in the `__init__()` method refers to the current instance and the instance variable course allows for input to assign a value. We can create a class instance by calling the class and inputting the value for course."]},{"cell_type":"code","execution_count":82,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1701923275211,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"3MqOQ5HMjK3_","outputId":"38312a81-2524-462d-f22b-aa388da7fb3f"},"outputs":[{"name":"stdout","output_type":"stream","text":["2\n"]}],"source":["class Circle:\n","    def __init__(self,r=1,x=0,y=0):#constructor\n","        self.r=r\n","        self.x=x\n","        self.y=y\n","\n","first = Circle(2, 1, 1)\n","print(first.r)\n"]},{"cell_type":"markdown","metadata":{"id":"AYBmO-8MjSoQ"},"source":["**Destructors**\n","\n","Destructors are special functions that are called when an object gets deleted. In Python, the __del__() method is commonly used as the destructor and is called when an object is deleted.\n","\n","**`del()`**\n","\n","Python’s built-in __del__() method represents the destructor in a class."]},{"cell_type":"code","execution_count":83,"metadata":{"executionInfo":{"elapsed":19,"status":"ok","timestamp":1701923276392,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"-jyPdXuQjj5w"},"outputs":[],"source":["class Circle:\n","    def __init__(self,r=1,x=0,y=0):#constructor\n","        self.r=r\n","        self.x=x\n","        self.y=y\n","\n","    def __del__(self):\n","       print('You successfully deleted your circle')"]},{"cell_type":"markdown","metadata":{"id":"IOBas1tAjqdg"},"source":["The self parameter in the `__del__()` method refers to the current object. Triggering this method by deleting the object will execute the `print()` statement. So, if we use del to delete the sched object as such:"]},{"cell_type":"code","execution_count":84,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":10,"status":"ok","timestamp":1701923278080,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"LgrOLDAnkRjl","outputId":"882a5d05-8b02-49a5-fe14-6a738008fec4"},"outputs":[{"name":"stdout","output_type":"stream","text":["You successfully deleted your circle\n"]}],"source":["sched = Circle(2)\n","del sched"]},{"cell_type":"markdown","metadata":{"id":"3d4e2roojQhL"},"source":["\n","\n","```\n","# This is formatted as code\n","```\n","\n","###Is Operator:\n","return True is varialbes are pointing toward the same data adress (similar to == in jave)\n","Note: equal operation do **NOT** clone the variable, it uses the same variable"]},{"cell_type":"code","execution_count":85,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1701923279794,"user":{"displayName":"Ghina Daoud","userId":"07032821316608972165"},"user_tz":-120},"id":"SGh8RZpd9BXx","outputId":"2ae1497d-f5b4-4eb7-cc1b-ea9f8b79f22f"},"outputs":[{"data":{"text/plain":["True"]},"execution_count":85,"metadata":{},"output_type":"execute_result"}],"source":["a=Circle()\n","b=a\n","b is a"]},{"cell_type":"markdown","metadata":{"id":"EODmBSaBP_gJ"},"source":["## File I/O"]},{"cell_type":"markdown","metadata":{"id":"2EfLfI-wQGgo"},"source":["\n","*   Handling files in Python\n","*   Reading, writing, and appending\n","\n","Unlike lists which are stored on volatile memory,\n","files are stored on drives We will focus on text files, i.e., files containing characters\n"]},{"cell_type":"markdown","metadata":{"id":"FUQkdjB5Q7o-"},"source":["### **Reading a file in a one shot:** read method\n"]},{"cell_type":"code","execution_count":null,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":693,"status":"ok","timestamp":1701855123798,"user":{"displayName":"Dana Dagher","userId":"12705149731390319008"},"user_tz":-120},"id":"UGjbLKonQGUZ","outputId":"0a8fa1c0-29cf-4615-f8b5-212723f6f74d"},"outputs":[{"name":"stdout","output_type":"stream","text":["AI Community\n","\n","Wednesday\n","\n","6_12_2023\n"]}],"source":["file_name = \"ai_text.txt\"\n","nameHandle = open(file_name,'r')\n","content = nameHandle.read()\n","nameHandle.close()\n","print(content)\n"]},{"cell_type":"markdown","metadata":{"id":"1tDVKlQ5VQLQ"},"source":["### **Writing to a file:** write method"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"M1EobsGhQH1v"},"outputs":[],"source":["nameHandle = open(file_name,'w')\n","nameHandle.write(\" Hello\")\n","nameHandle.write(\"world\\n\")\n","nameHandle.write(\"it's raining\\n\")\n","nameHandle.close()"]},{"cell_type":"markdown","metadata":{"id":"mxO42WbXXo0s"},"source":["### **Append mode:**\n","1. If we open an exiting file in the ‘w’ mode, its content will be disregarded\n","2. What if we want to write to an existing file and instead of\n","overwriting it we want to append new strings?"]},{"cell_type":"code","execution_count":null,"metadata":{"id":"XTtMcbOVQIBF"},"outputs":[],"source":["namehandle = open(file_name,'a')\n","namehandle.write(\"AI COMMUNITY \\n\")\n","namehandle.write(\"WEDNESDAY  6_12_2003\")\n","namehandle.close()"]}],"metadata":{"colab":{"provenance":[]},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
