diff --git a/lab-python-flow-control.ipynb b/lab-python-flow-control.ipynb
index f4c7391..e27325b 100644
--- a/lab-python-flow-control.ipynb
+++ b/lab-python-flow-control.ipynb
@@ -2,40 +2,1762 @@
"cells": [
{
"cell_type": "markdown",
- "id": "d3bfc191-8885-42ee-b0a0-bbab867c6f9f",
+ "id": "9fb43870",
"metadata": {
+ "toc": true
+ },
+ "source": [
+ "
Table of Contents
\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b3c3bd31-50d5-41d7-9912-ed89e178798d",
+ "metadata": {},
+ "source": [
+ "# Flow control"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "315c5a0b-7287-41cb-99cb-a13f2fe0b86a",
+ "metadata": {},
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e63d1d68-ddd5-48ed-8510-e98c97fa9bd8",
+ "metadata": {},
+ "source": [
+ "## Conditional Statements: `if`, `elif`, `else`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d6520a34-25f3-4d11-91b9-58d9791afb3c",
+ "metadata": {},
+ "source": [
+ "Conditional statements in Python (if, elif, else) help control program flow based on conditions.\n",
+ "\n",
+ "- These conditional statements allow us to execute specific blocks of code only when the conditions are met.\n",
+ "- To check conditions, we make use of comparison operators returning True or False."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cf1e2f29-240f-4dfc-b78d-b489825b2ac4",
+ "metadata": {},
+ "source": [
+ "```python\n",
+ "if condition1:\n",
+ " # code to execute if condition1 is true\n",
+ "elif condition2:\n",
+ " # code to execute if condition2 is true\n",
+ "elif condition3:\n",
+ " # code to execute if condition3 is true\n",
+ "# ...more elif statements can be added if needed\n",
+ "else:\n",
+ " # code to execute if all conditions are false\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c4c189cb-34de-4382-acb2-03dcc4b2b3c1",
+ "metadata": {},
+ "source": [
+ "The `if` statement executes a code block if a condition is true. \n",
+ "\n",
+ "`elif` statement (optional) checks additional conditions after the `if` statement (in case the `if` condition is not met).\n",
+ "\n",
+ "`else` statement (optional) provides a default code block when preceding conditions are false. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e75be129-d0ee-42c9-9024-b908c374ed12",
+ "metadata": {},
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ea1ea251-3c54-42a3-9187-fe992644ec01",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "a = 10\n",
+ "b = 11\n",
+ "\n",
+ "if a > b: # Here we are trying to find if a is greater than b\n",
+ " print('a is greater')\n",
+ " print('Value of a is',a) \n",
+ " print('And value of b is',b)\n",
+ "elif a < b: # Here we are trying to find if b is greater than a\n",
+ " print('b is greater')\n",
+ " print('Value of a is', a)\n",
+ " print('And value of b is',b)\n",
+ "else: # If none of the above are True, then we execute the else statement\n",
+ " print('a and b are equal')\n",
+ "print(\"Done!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f87152a5-e900-4cf8-b3ea-2ade0b2c2ecf",
+ "metadata": {},
+ "source": [
+ "Pay attention to the colon `:` after the condition or `else`, as this marks the starting point of the code to be executed. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6feb2dcc-df1a-4abb-b0d4-29afa4a7942f",
+ "metadata": {},
+ "source": [
+ "In the previous code, the indentation of the `print()` statements indicates their association with specific conditions. Indentation is automatically applied by Jupyter every time you type `:`. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "1759c760-bf01-4000-ac6f-c359f5666b4d",
+ "metadata": {},
+ "source": [
+ "The last `print(\"Done!\")` will be executed regardless of the `a > b` or `a < b` condition because it is not *indented*."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "dd05a7d1-9562-4cdd-a77b-8adc05beaa29",
+ "metadata": {},
+ "source": [
+ "### Multiple Conditions with Logical Operators"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "edbee6f0-ed1f-4c58-b1ae-6531187affeb",
+ "metadata": {},
+ "source": [
+ "Logical operators in Python combine conditions in conditional statements:\n",
+ "\n",
+ "- `and` returns True if both conditions are true, otherwise False.\n",
+ "- `or` returns True if at least one condition is true, otherwise False.\n",
+ "- `not` negates the condition's value: True becomes False and vice versa."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "953c6cea-7a33-4c7e-955d-143f985e4c11",
+ "metadata": {},
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9f532b51-d190-454a-bb16-e1aa2804f7d7",
+ "metadata": {},
+ "source": [
+ "Let's look at an example to understand how multiple conditions with logical operators can be implemented in Python:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "7e183deb-a673-4978-9e66-2003d00f51e9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "number = int(input(\"Enter a number: \")) # we prompt the user to enter a number, which we store in the number variable\n",
+ "\n",
+ "if number > 0 and number % 2 == 0: # number > 0 checks if the number is positive, and number % 2 == 0 checks if it is even\n",
+ " # if both conditions are true, the following print will be executed\n",
+ " print(\"The number is positive and even.\")\n",
+ "elif number < 0 or number % 2 != 0: # If at least one of these conditions is true, the code block under the elif statement will execute\n",
+ " print(\"The number is negative or odd.\")\n",
+ "else: # if none of the conditions in the if and elif statements are true, the code block under the else statement will execute\n",
+ " print(\"The number is zero.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2ca45866-3c25-408d-a2bc-7fa46b4ba6ee",
+ "metadata": {},
+ "source": [
+ "### Nested Conditional Statements "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "faf21d89-1667-40b5-9d27-0521540eb40c",
+ "metadata": {},
+ "source": [
+ "A nested conditional statement is a conditional statement (if, elif, or else) that is placed inside another conditional statement.\n",
+ "\n",
+ "The structure of nested conditional statements is as follows:"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6b304c87-4858-4829-a706-794922819041",
+ "metadata": {},
+ "source": [
+ "```python\n",
+ "if condition1:\n",
+ " # code block for condition1\n",
+ " if condition2:\n",
+ " # code block for condition2\n",
+ " elif condition3:\n",
+ " # code block for condition3\n",
+ " else:\n",
+ " # code block if condition2 and condition3 are false\n",
+ "else:\n",
+ " # code block if condition1 is false\n",
+ "\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5e624f98-4c7d-49e2-9e2b-37668cea167b",
+ "metadata": {},
+ "source": [
+ "Let's look at an example to understand how nested conditional statements can be implemented in Python:\n",
+ "\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "31201d46-7cef-40ea-b05d-4ed662f9451b",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter a number: 10\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "The number is positive.\n",
+ "The number is even.\n"
+ ]
+ }
+ ],
+ "source": [
+ "number = int(input(\"Enter a number: \"))\n",
+ "\n",
+ "if number > 0: # checks if number is greater than 0. If it is true, the code block under the outer if statement is executed\n",
+ " print(\"The number is positive.\")\n",
+ " \n",
+ " if number % 2 == 0: # if the number is even, then the print below is executed\n",
+ " print(\"The number is even.\")\n",
+ " else: # if the number is odd, then the print below is executed\n",
+ " print(\"The number is odd.\")\n",
+ " \n",
+ "else: #if the number was not greater than 0, only the print below is executed\n",
+ " print(\"The number is either zero or negative.\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "afbda807-d3e4-41af-a2ef-4f5bed8d160e",
+ "metadata": {
+ "id": "KrahGtLGD6ON",
"tags": []
},
"source": [
- "# Lab | Flow Control"
+ "## Iterations "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cfcb411d-7b41-4780-9184-08ebfd259435",
+ "metadata": {},
+ "source": [
+ "Iterations are a fundamental concept in programming that allow us to repeat a block of code multiple times. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "07684106-cf82-4c64-b68d-ef2efa4271fa",
+ "metadata": {},
+ "source": [
+ "In Python, there are two primary ways to perform **loops**: using **`for` loops** and **`while` loops**."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c9d378d5-cb17-4bed-b74e-e81791ef44ac",
+ "metadata": {},
+ "source": [
+ "### For Loop\n",
+ "\n",
+ "A `for` loop is used to **iterate over a sequence** (such as a list, tuple, or string) or any iterable object. It **executes a block of code for each item** in the sequence.\n",
+ "```python\n",
+ "for item in sequence:\n",
+ " # Code to be executed for each item\n",
+ "```\n",
+ "- `for` keyword: Initiates the for loop.\n",
+ "- `item`: Represents the variable holding the current item in each iteration, assigned values from the sequence.\n",
+ "- `in` operator: Specifies the sequence or collection to iterate over.\n",
+ "- `sequence`: Refers to the iterable object being looped through.\n",
+ "- `:` colon: Marks the start of the loop block, with subsequent lines indented consistently.\n",
+ "- `Code to be executed`: Contains the statements within the loop block, executed for each item in the sequence, respecting the indentation and order."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "cc167e35-ea58-4277-9e07-b83bde3cb938",
+ "metadata": {},
+ "source": [
+ "Let's look at some examples to understand how the `for` loop works. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4189a3a1-b203-4a5f-a332-e01ca6335dbd",
+ "metadata": {},
+ "source": [
+ "####Ā Iterating through a list"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "33dcbf69-2609-4f20-b055-d6c1b9e433b0",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "apple\n",
+ "hey!\n",
+ "banana\n",
+ "hey!\n",
+ "orange\n",
+ "hey!\n",
+ "This line is outside the loop so it is only executed once\n"
+ ]
+ }
+ ],
+ "source": [
+ "fruits = [\"apple\", \"banana\", \"orange\"]\n",
+ "\n",
+ "for fruit in fruits:\n",
+ " print(fruit) # This is executed 3 times since there are 3 elements in the fruits list\n",
+ " print(\"hey!\") # This is also inside the loop and it is executed 3 times, each time after the previous line is executed\n",
+ " \n",
+ "print(\"This line is outside the loop so it is only executed once\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "11699526-85b6-450b-9972-93aa240f514f",
+ "metadata": {},
+ "source": [
+ "In this example, the variable fruit takes on each item in the fruits list, and the prints statements are executed for each item.\n",
+ "\n",
+ "The loop will iterate through all items in the sequence, executing the statement block once for each item."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f43ba596-3adf-4bdb-aada-a0f63e7ab799",
+ "metadata": {},
+ "source": [
+ "Code blocks that have the same indentation level are executed together. This is true not only for conditional statements like if, elif, and else, but also for loops and other structures."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0ad97823-72a2-4bc9-958a-bad76704ec03",
+ "metadata": {},
+ "source": [
+ "####Ā Iterating with the range() function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d657940e-34c4-444f-9b53-7f03a2a1a2e4",
+ "metadata": {},
+ "source": [
+ "To print numbers from 1 to 5 using `range()`, use:\n",
+ "\n",
+ "- `range(stop)`: Generates numbers from 0 to (stop-1).\n",
+ "- `range(start, stop)`: Generates numbers from start to (stop-1).\n",
+ "- `range(start, stop, step)`: Generates numbers from start to (stop-1) with a specified step."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "f8aeda15-aea4-4c95-a4a1-aadd5bee90c5",
+ "metadata": {
+ "id": "qcU1NWarD6OY",
+ "outputId": "69003652-5770-4e33-e101-b973815078fe"
+ },
+ "outputs": [],
+ "source": [
+ "# \"i\" is the variable here. It takes on values from the range() function from 0 to 9, iteratively\n",
+ "# By default, the values are generated starting with 0 \n",
+ "for i in range(10): \n",
+ " print(i)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "80a95bc1-deec-4da9-b082-f68eb5f4b997",
+ "metadata": {},
+ "source": [
+ "#### Combining loops with conditional statements"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "bc931d61-f4ef-4849-a238-142fc302f61c",
+ "metadata": {},
+ "source": [
+ "You can **combine for loops with conditional statements (if-else)** to perform certain actions based on specific conditions. \n",
+ "\n",
+ "Here's an example that prints only the even numbers from 1 to 10:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "0393ca5d-4421-4ead-acf5-7cc4f3ab136e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2\n",
+ "4\n",
+ "6\n",
+ "8\n",
+ "10\n"
+ ]
+ }
+ ],
+ "source": [
+ "for number in range(1, 11):\n",
+ " if number % 2 == 0:\n",
+ " print(number)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6bf9a0d7-910d-4275-81e7-456349759d96",
+ "metadata": {
+ "id": "d8IHtPpKD6OZ"
+ },
+ "source": [
+ "Pay attention to the flow of the code and the indentation. `if` condition is executed 10 times, but \"number\" is only printed when the condition is met because it is contained inside the `if` statement."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "df7db3a9-0c88-4558-b341-31efccbf8949",
+ "metadata": {
+ "id": "m5U0Px-2D6Og"
+ },
+ "source": [
+ "#### Iterating on dictionaries\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "99ee0c22-375c-4467-b909-40440258f494",
+ "metadata": {},
+ "source": [
+ "By applying the `.keys()` method on a dictionary, we can obtain an iterable object that can be used in a `for` loop to iterate over all the keys of the dictionary, one by one."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "9c984d04-1838-486f-8030-8e61db663032",
+ "metadata": {
+ "id": "G2SyxXhxD6Oh",
+ "outputId": "57b01699-9206-472a-d7bd-e4d7a6f912bf"
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "name\n",
+ "age\n",
+ "city\n"
+ ]
+ }
+ ],
+ "source": [
+ "my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}\n",
+ "\n",
+ "# Iterating over the keys using a for loop\n",
+ "for key in my_dict.keys():\n",
+ " # Accessing each key\n",
+ " print(key)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "22aa6a68-cfb4-41d7-a803-fd3a6f6c0d85",
+ "metadata": {
+ "id": "WtceUnfID6Oh"
+ },
+ "source": [
+ "By applying the `.values()` method on a dictionary, we can obtain an iterable object that can be used in a for `loop` to iterate over all the values of the dictionary, one by one."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "d5cbe596-d70c-4e87-9105-8f9dff12a053",
+ "metadata": {
+ "id": "QmemmBirD6Oh"
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "John\n",
+ "25\n",
+ "New York\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Iterating over the values using a for loop\n",
+ "for value in my_dict.values():\n",
+ " # Accessing each value\n",
+ " print(value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0ea82012-d9d9-4004-9a2f-6834df782522",
+ "metadata": {},
+ "source": [
+ "By applying the `.items()` method on a dictionary, we can obtain an iterable object that contains all the key-value pairs in the dictionary. This iterable can be used in a `for` loop to iterate over each key-value pair."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "id": "98d7fe56-7f77-4010-a1c8-2f83c409b234",
+ "metadata": {
+ "id": "TGbVZ5UHD6Oi",
+ "outputId": "2b27b9eb-e6f5-4b5a-b489-b3666a45c836",
+ "scrolled": true
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "For name the value is: John\n",
+ "For age the value is: 25\n",
+ "For city the value is: New York\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Iterating over the key-value pairs using a for loop\n",
+ "for key, value in my_dict.items():\n",
+ " # Accessing each key-value pair\n",
+ " print(\"For \", key, \" the value is: \", value)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e292f24d-696f-4b4c-8fa3-3a83cb65de57",
+ "metadata": {},
+ "source": [
+ "In this case, the `.items()` method returns an iterable of tuples, where each tuple represents a key-value pair from the dictionary `my_dict`. The `for` loop then iterates over each tuple, and within the loop, you can access both the key and the corresponding value and perform operations or work with them as needed."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6d85aee8-b41c-4537-b8e2-8d932e639b07",
+ "metadata": {},
+ "source": [
+ "#### Nested for loops"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8e8b17b2-58e2-4597-8f58-468ef449d324",
+ "metadata": {},
+ "source": [
+ "By nesting one loop inside another, we can achieve more complex iterations. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4a556c09-2393-480b-bc31-2d40babab395",
+ "metadata": {},
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "1b82b0aa-ce6c-4a09-9f62-70ac944387a6",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "for i in range(1,10):\n",
+ " for j in range(10,12):\n",
+ " print(i,j)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5e82c963-890d-4d8d-9d6b-da2b4b4a64ec",
+ "metadata": {},
+ "source": [
+ "Variable `i` will iterate in range(1,10), which means `i` will be 1, 2..,9.\n",
+ "\n",
+ "For each `i`, it will iterate with `j` in range (10,12), which means `j` will be 10,11. \n",
+ "\n",
+ "For each combination of `i` and `j`, it will print both of them."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b217df54-ac1a-4a43-b46a-f33cabb05292",
+ "metadata": {
+ "id": "uYpFsglHD6Ob"
+ },
+ "source": [
+ "-----------------------------"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ae5a3d55-b63e-409b-99e2-7189f28bf0e0",
+ "metadata": {},
+ "source": [
+ "### While Loop\n",
+ "\n",
+ "A `while` loop repeatedly **executes a block of code as long as a given condition is true**. It keeps iterating until the condition becomes false."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "195b9d1b-5ea0-40ab-ae6e-a60e7f79eb05",
+ "metadata": {},
+ "source": [
+ "```python\n",
+ "while condition:\n",
+ " # Code to be executed\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c00de839-f337-4902-9ce3-69a2f886fbdb",
+ "metadata": {
+ "id": "tQWD_j80D6Ok"
+ },
+ "source": [
+ "where:\n",
+ "- `condition`: A logical condition in Python that evaluates to either True or False. It determines whether the block of code inside the loop is executed or not.\n",
+ "- `code to be executed`: The indented block of code that runs as long as the condition is True."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "878f5b0f-5634-4cd5-9865-dd8c34d0f63f",
+ "metadata": {
+ "id": "5RiXFnq4D6Oj"
+ },
+ "source": [
+ "When the condition of the while loop becomes false, the code inside the loop stops executing, and the program proceeds with the code after the while loop. **Ensure the condition eventually changes to false to avoid infinite loops.**\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "934bcef8-f921-4dac-8821-c63e20ed625f",
+ "metadata": {},
+ "source": [
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "id": "0fb09509-0ad4-4480-91ca-00cf785ff8b5",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Count: 0\n",
+ "Count: 1\n",
+ "Count: 2\n",
+ "Count: 3\n",
+ "Count: 4\n"
+ ]
+ }
+ ],
+ "source": [
+ "count = 0\n",
+ "while count < 5: # The while loop checks if count is less than 5. If it is, the block of code inside the loop is executed\n",
+ " print(\"Count:\", count)\n",
+ " count += 1 # The value of count is updated based on how many times we want the loop to run or the specific conditions we want to apply."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d570b04b-a05f-4631-9351-2f82412721e0",
+ "metadata": {
+ "id": "C1WrfMEZD6Ok"
+ },
+ "source": [
+ "**Beware** that we need to change the value of the variable `count` inside the while loop. Otherwise the loop will never end as `count<5` will always be true. "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "e99bdea8-b77a-40e4-8861-6fdfc6aca0e5",
+ "metadata": {},
+ "source": [
+ "### For vs While loops"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "701668d3-bd82-4e16-8df4-a09467c07dac",
+ "metadata": {},
+ "source": [
+ "āUnderstanding when to use a `for` loop versus a `while` loop is important. Here's a simple guideline:\n",
+ "\n",
+ "`For` Loop: Use a `for` loop **when you know the number of repetitions**, regardless of how many. For example, if you need to repeat a task 10 times, use a `for` loop.\n",
+ "\n",
+ "`While` Loop: Use a `while` loop when **the number of repetitions is not fixed and depends on a condition**. For example, if you need to keep repeating a task until a specific condition is met, use a `while` loop."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "6982236a-2153-4eb1-a263-6100814d558f",
+ "metadata": {},
+ "source": [
+ "Let's consider a few examples to illustrate this distinction:\n",
+ "\n",
+ "- For a punishment that requires writing a sentence 500 times, you know the exact number of repetitions in advance (500). Hence, you should use a `for` loop.\n",
+ "- However, when studying for an exam, the duration is uncertain. You will continue studying until you feel confident in mastering the lesson. In this case, you don't know the exact number of repetitions in advance, but you have a condition for stopping (mastering the lesson). Therefore, a `while` loop is more appropriate."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a7c6db4d-93df-4933-8793-f7e5122c29fe",
+ "metadata": {},
+ "source": [
+ "### š” Check for understanding"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "783db07d-0466-418f-9918-4632feff9940",
+ "metadata": {
+ "lang": "en"
+ },
+ "source": [
+ "Write a program that prompts the user to enter a series of numbers. The program should store these numbers in a list and then determine whether each number is even or odd. Finally, display the results to the user."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "id": "32009ffd-33c2-4475-ad7d-38c4b5350a43",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter a series of numbers separated by spaces: 3\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "3 is odd\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Prompt the user to enter numbers separated by spaces\n",
+ "numbers_input = input(\"Enter a series of numbers separated by spaces: \")\n",
+ "\n",
+ "# Convert the string input into a list of integers\n",
+ "numbers = [int(num) for num in numbers_input.split()]\n",
+ "\n",
+ "# Determine if each number is even or odd\n",
+ "for n in numbers:\n",
+ " if n % 2 == 0:\n",
+ " print(f\"{n} is even\")\n",
+ " else:\n",
+ " print(f\"{n} is odd\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4e490ead-ce79-42be-a70f-5a8d71a6fb20",
+ "metadata": {},
+ "source": [
+ "##### \n",
+ "Prompt the user to enter numbers separated by spaces\n",
+ "numbers_input = input(\"Enter a series of numbers separated by spaces: \")\n",
+ "\n",
+ "# Convert the string input into a list of integers\n",
+ "numbers = [int(num) for num in numbers_input.split()]\n",
+ "\n",
+ "# Determine if each number is even or odd\n",
+ "for n in numbers:\n",
+ " if n % 2 == 0:\n",
+ " print(f\"{n} is even\")\n",
+ " else:\n",
+ " print(f\"{n} is odd\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "86d4fd1c-78c2-4836-80da-433706d468ed",
+ "metadata": {},
+ "source": [
+ "**Please refer to the following hint only if you have attempted the Check for Understanding and are still confused. Do not read it before giving it a try.**:\n",
+ "\n",
+ "Here's a step-by-step guide:\n",
+ "\n",
+ "1. Create an empty list to store the numbers.\n",
+ "2. Use a loop to prompt the user to enter numbers. Inside the loop, use the `input()` function to get a number from the user and convert it to an integer using the `int()` function.\n",
+ "3. Append each number to the list.\n",
+ "4. Iterate over each number in the list using a loop. Inside the loop, use an if-else statement to check if the number is even or odd.\n",
+ "5. Display a message to the user indicating whether each number is even or odd."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "34a33b41-43f9-4a84-9569-2a13860b0a4b",
+ "metadata": {},
+ "source": [
+ "## Summary\n",
+ "\n",
+ "Flow control in Python includes:\n",
+ "\n",
+ "- `if`, `elif`, and `else` statements for conditional execution:\n",
+ " - `if` is used to check a condition and execute a block of code if it's true.\n",
+ " - `elif` (else if) allows you to check additional conditions after the initial `if` statement.\n",
+ " - `else` provides a default block of code to execute if none of the previous conditions are true.\n",
+ "\n",
+ "- `for` loops for iterating over a sequence:\n",
+ " - `for` loops execute a block of code for each item in a sequence or iterable object.\n",
+ " - The current item is assigned to a variable in each iteration.\n",
+ "\n",
+ "- `while` loops for repeated execution:\n",
+ " - `while` loops repeatedly execute a block of code as long as a condition is true.\n",
+ " - They keep iterating as long as the condition remains true.\n",
+ "\n",
+ "- Nesting flow control constructs:\n",
+ " - Nesting refers to using one flow control construct within another."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "89dd8b5e-fe13-4149-a9b1-db7917ad2fa7",
+ "metadata": {},
+ "source": [
+ "# Extra: More examples with flow control"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b5cbe2c6-8603-431b-be3e-16d3390e4845",
+ "metadata": {},
+ "source": [
+ "## If-elif-else"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "41994b18-3e2b-4f26-9bf6-efc708a8a67d",
+ "metadata": {},
+ "source": [
+ "Let's see another example where we prompt the user to enter their age, and based on the input, we provide different messages:\n",
+ "\n",
+ "- If the age is 18 or above, it prints \"You can buy a beer.\"\n",
+ "- If the age is between 16 and 18 (not including 18), it prints \"You can drive, but you can't buy.\"\n",
+ "- For any other age, it prints \"You can't, sorry! Grow up!\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "id": "5ae1433b-bc60-409c-934b-ac43aa7bdcb8",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter your age 33\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "You can buy a beer\n"
+ ]
+ }
+ ],
+ "source": [
+ "age = int(input(\"Enter your age \"))\n",
+ "\n",
+ "if age >= 18:\n",
+ " print(\"You can buy a beer\")\n",
+ "elif 16<=age<18:\n",
+ " # if you are between 16 and 18(not yet 18) cant buy, but can drive\n",
+ " print(\"You can drive, but you cant buy\")\n",
+ "else:\n",
+ " print(\"You can't, sorry! Grow up!\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "006b214a-9b53-4e0e-84c2-b3fcab24c0a3",
+ "metadata": {},
+ "source": [
+ "## For "
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "715894bc-3ccd-4bcc-9a92-b19efb7909e4",
+ "metadata": {},
+ "source": [
+ "###Ā Iterating through a string"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "354d2053-e0cd-4726-9dde-8960e4aaf365",
+ "metadata": {},
+ "source": [
+ "You can also use a for loop with strings. In the following example, we iterate over each character in a string and print them individually:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "id": "9aaec1b7-bc87-4402-8890-842307057410",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "H\n",
+ "e\n",
+ "l\n",
+ "l\n",
+ "o\n",
+ ",\n",
+ " \n",
+ "W\n",
+ "o\n",
+ "r\n",
+ "l\n",
+ "d\n",
+ "!\n"
+ ]
+ }
+ ],
+ "source": [
+ "message = \"Hello, World!\"\n",
+ "\n",
+ "for char in message:\n",
+ " print(char)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a3ed013f-a5b6-4a41-b583-3becb4a1b549",
+ "metadata": {},
+ "source": [
+ "### Incrementing a variable with a loop"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "743febdc-f4b9-45dc-849b-ca8dcefde732",
+ "metadata": {},
+ "source": [
+ "In the next example, we'll demonstrate how to use a for loop to increment a variable by a constant value at each iteration. We'll start with an initial value of `a` and increase it by a fixed amount in each iteration of the loop. After each iteration, we'll print the value of `a`. Finally, we'll print the final value of `a` once the for loop completes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "id": "4b0a840f-b948-4444-805b-d4d678f313ee",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "5\n",
+ "10\n",
+ "15\n",
+ "20\n",
+ "25\n",
+ "Final value of 'a': 25\n"
+ ]
+ }
+ ],
+ "source": [
+ "a = 0 # Initial value of 'a'\n",
+ "increment = 5 # Constant value to increment 'a' by\n",
+ "\n",
+ "for i in range(5): # Iterate 5 times\n",
+ " a += increment # Increment 'a' by 'increment' value\n",
+ " print(a) # Print the value of 'a' at each iteration\n",
+ "\n",
+ "print(\"Final value of 'a':\", a) # Print the final value of 'a' after the for loop"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "02ff616c-2718-416e-94f0-6e78aea57593",
+ "metadata": {},
+ "source": [
+ "### Create an empty list and populate it"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "22567e28-03f0-4261-9464-95dedf2aceaa",
+ "metadata": {},
+ "source": [
+ "In the following example, we'll demonstrate how to create an empty list and populate it with elements using iterations.\n",
+ "\n",
+ "Problem Statement: We have a list containing some integer elements, and we want to create a new list that consists of the squares of each element from the original list.\n",
+ "\n",
+ "To solve this problem, we can use the `append()` function, which specifically works with lists. It allows us to add elements of any kind to the end of a given list."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "id": "9c321a09-181f-48ac-a7eb-cd94b4bd89f9",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Original List: [2, 4, 6, 8, 10]\n",
+ "Squared List: [4, 16, 36, 64, 100]\n"
+ ]
+ }
+ ],
+ "source": [
+ "original_list = [2, 4, 6, 8, 10] # Given list with integer elements\n",
+ "squared_list = [] # Empty list to store the squares\n",
+ "\n",
+ "for element in original_list: # Iterate through each element in the original list\n",
+ " squared_list.append(element ** 2) # Append the square of the element to the squared list\n",
+ "\n",
+ "print(\"Original List:\", original_list)\n",
+ "print(\"Squared List:\", squared_list)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8d8ac298-4490-4e1e-86bc-a01a7ea477c6",
+ "metadata": {},
+ "source": [
+ "## While"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "28be3843-548c-4e6a-8f03-1515cfdc726b",
+ "metadata": {},
+ "source": [
+ "Let's see another example where we iterate over the characters of a string."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "id": "924bc99f-72ef-4ee3-8e81-cee30f4ee1a8",
+ "metadata": {
+ "id": "boDQe79cD6Ok",
+ "outputId": "fa5feddf-13d3-4499-a35d-e73949fe8498"
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "I\n",
+ "r\n",
+ "o\n",
+ "n\n",
+ "h\n",
+ "a\n",
+ "c\n",
+ "k\n"
+ ]
+ }
+ ],
+ "source": [
+ "word = \"Ironhack\"\n",
+ "i = 0\n",
+ "while i < len(word): # The `len()` function returns how many elements (letters or blank spaces) the string has.\n",
+ " print(word[i])\n",
+ " i=i+1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b1396334-26fc-4d2a-b65d-189cecf233f9",
+ "metadata": {},
+ "source": [
+ "We can do the same using a `for` loop:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "id": "c5e0192d-7356-4ec7-a210-8fd2eee76a63",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "I\n",
+ "r\n",
+ "o\n",
+ "n\n",
+ "h\n",
+ "a\n",
+ "c\n",
+ "k\n"
+ ]
+ }
+ ],
+ "source": [
+ "word = \"Ironhack\"\n",
+ "for i in range(len(word)):\n",
+ " print(word[i])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "5aef9823-dba7-442e-ba3e-d194200232da",
+ "metadata": {},
+ "source": [
+ "Example: Let's create a program that asks the user for a password and keeps prompting them until they enter the correct password."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "id": "7405688d-32b9-4e3d-b500-2f1b8d783fe4",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: 291993\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: Arden@2022\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: 0\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: Password123\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: pssword123\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: \"password123\"\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Incorrect password. Try again.\n"
+ ]
+ },
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter the password: password123\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Login successful!\n"
+ ]
+ }
+ ],
+ "source": [
+ "# Set the correct password\n",
+ "correct_password = \"password123\"\n",
+ "\n",
+ "# Ask the user for input\n",
+ "password = input(\"Enter the password: \")\n",
+ "\n",
+ "# Create a while loop\n",
+ "while password != correct_password:\n",
+ " print(\"Incorrect password. Try again.\")\n",
+ " password = input(\"Enter the password: \")\n",
+ "\n",
+ "# Code after the while loop\n",
+ "print(\"Login successful!\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "c5011df3-720a-4d15-8054-a7bb3eb0bb54",
+ "metadata": {},
+ "source": [
+ "Lets look at an example of code that prints a number from 0 until n where n is a number asked with input using a while"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "id": "d13c504a-836a-45e9-ab0f-453a72922e22",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter your number! 5\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "0\n",
+ "1\n",
+ "2\n",
+ "3\n",
+ "4\n",
+ "5\n"
+ ]
+ }
+ ],
+ "source": [
+ "# code that prints a number from 0 until n\n",
+ "# where n is a number asked with input. use a while\n",
+ "n = int(input(\"Enter your number! \"))\n",
+ "count = 0\n",
+ "while count<=n:\n",
+ " print(count)\n",
+ " count += 1\n",
+ " # add 1 to something"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "a3d66798-34ab-43b7-8e39-989b816d644b",
+ "metadata": {},
+ "source": [
+ "## Nesting"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b6bcf317-7926-4605-8a2b-55113545a43d",
+ "metadata": {},
+ "source": [
+ "Here are some examples to help you understand how nesting works."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 28,
+ "id": "ef6b360f-bb3d-4d32-aec2-f3b498eddf94",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdin",
+ "output_type": "stream",
+ "text": [
+ "Enter a number: 2\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2 is even\n"
+ ]
+ }
+ ],
+ "source": [
+ "number = int(input(\"Enter a number: \"))\n",
+ "\n",
+ "if number % 2 == 0:\n",
+ " print(f\"{number} is even\")\n",
+ "else:\n",
+ " print(f\"{number} is odd\")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "44f5d4be-7b8f-45c2-b5ca-ee89dafd81ad",
+ "metadata": {},
+ "source": [
+ "Variable `x` will iterate in range(10), which means x will be 0, 1, 2..,9.\n",
+ "\n",
+ "For each `x`: \n",
+ "- I print \"Hello x is\" and value of x (0,1,2..,9)\n",
+ "- Set i = 0\n",
+ "- Print \"i is\" and value of `i`. It wil always print `i is 0` because I have `i=0` and `print` before and outside the while.\n",
+ "- Execute `while` while condition is met. Since `i` is 0, until `i` is >= 3.\n",
+ " - I print \"inside while\" and `i` value (0,1,2)\n",
+ " - If `i` is even, I print even. \n",
+ " - I add 1 to `i`. So `i`will be 0, 1, 2, 3 (when it takes value of 3, while will stop executing).\n",
+ "\n",
+ "- I print \"outside while\" and value of x (0,1,2...,9), same value as the first print in this list"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "id": "9383e1b3-89aa-428e-9a4a-15fc322106ee",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "hello, x is 0\n",
+ "i is 0\n",
+ "inside while 0\n",
+ "even\n",
+ "inside while 1\n",
+ "inside while 2\n",
+ "even\n",
+ "outside while 0\n",
+ "hello, x is 1\n",
+ "i is 3\n",
+ "outside while 1\n",
+ "hello, x is 2\n",
+ "i is 3\n",
+ "outside while 2\n",
+ "hello, x is 3\n",
+ "i is 3\n",
+ "outside while 3\n",
+ "hello, x is 4\n",
+ "i is 3\n",
+ "outside while 4\n",
+ "hello, x is 5\n",
+ "i is 3\n",
+ "outside while 5\n",
+ "hello, x is 6\n",
+ "i is 3\n",
+ "outside while 6\n",
+ "hello, x is 7\n",
+ "i is 3\n",
+ "outside while 7\n",
+ "hello, x is 8\n",
+ "i is 3\n",
+ "outside while 8\n",
+ "hello, x is 9\n",
+ "i is 3\n",
+ "outside while 9\n"
+ ]
+ }
+ ],
+ "source": [
+ "i=0 #changed this from its previous position after the print(\"hello\")\n",
+ "for x in range(10):\n",
+ " print(\"hello, x is\",x)\n",
+ " print(\"i is \",i)\n",
+ " while i<3:\n",
+ " print(\"inside while\",i)\n",
+ " if i%2==0:\n",
+ " print('even')\n",
+ " i+=1\n",
+ " print(\"outside while\",x)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "91ae867c-0061-4377-81b1-5a352d128c41",
+ "metadata": {},
+ "source": [
+ "`i` is set to 0. **This is the difference with the example above, which changes things**.\n",
+ "\n",
+ "Variable `x` will iterate in range(10), which means x will be 0, 1, 2..,9.\n",
+ "\n",
+ "For each `x`: \n",
+ "- I print \"Hello x is\" and value of x (0,1,2..,9)\n",
+ "- Print \"i is\" and value of `i`. \n",
+ " - First time it will print `i is 0`\n",
+ " - Next times it will print `i is 3` since i don't reset `i`value inside the `for` loop, and its last value at the end of first and only execution of `while` is 3.\n",
+ "- Execute `while` while condition is met. Since `i` is 0, until `i` is >= 3.\n",
+ " - I print \"inside while\" and `i` value (0,1,2)\n",
+ " - If `i` is even, I print even. \n",
+ " - I add 1 to `i`. So `i`will be 0, 1, 2, 3 (when it takes value of 3, while will stop executing).\n",
+ " - **Important** since i don't reset `i` value, the `while`will only execute when x=0, and one time. For x=1 and forward, `i` is 3 so while loop condition is not met.\n",
+ "- I print \"outside while\" and value of x (0,1,2...,9), same value as the first print in this list"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "id": "8e19ff0d-0a20-44b0-bbd8-60d15e8baea9",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "i is 0\n",
+ "j is 5\n",
+ "j is 4\n",
+ "j is 3\n",
+ "j is 2\n",
+ "j is 1\n",
+ "i is 1\n",
+ "i is 2\n"
+ ]
+ }
+ ],
+ "source": [
+ "i = 0\n",
+ "j = 5\n",
+ "while i<3:\n",
+ " print(\"i is\",i)\n",
+ " i+=1\n",
+ " while j>0: #this only executes when i=0, because im not setting\n",
+ " #j back to 5 inside the first while loop\n",
+ " print(\"j is\",j)\n",
+ " j-=1"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "b7aaa4ef-55a1-45a8-b130-37f02b5404ff",
+ "metadata": {},
+ "source": [
+ "- Set i=0\n",
+ "- Set j=5\n",
+ "- Outer loop `while`. Execute `while` while condition is met. Since `i` is 0, until `i` is >= 3.\n",
+ " - I print \"i is\" and `i` value (0,1,2)\n",
+ " - I add 1 to `i`. So `i`will be 0, 1, 2, 3 (when it takes value of 3, outer loop while will stop executing).\n",
+ " - Inner loop `while`. Execute `while` while condition is met. Since `j` is 5, while `j` is > 0.\n",
+ " - Print `j` is and value of `j`. \n",
+ " - Take 1 from `j`. (So `j` will be 5,4,3,2,1,0, in each execution of while).\n",
+ " - **Important** since i don't reset `j` value, the `while`will only execute when i=0, and one time. For i=1 and forward, `j` is 0 so while loop condition is not met.\n",
+ " \n",
+ " \n",
+ "In other words, what will happen will be:\n",
+ "- i=0\n",
+ "- j=5\n",
+ "- i<3? yes (i is 0)\n",
+ " - print i is 0\n",
+ " - i = 1\n",
+ " - j is > 0?\n",
+ " - print j is 5\n",
+ " - j = 4\n",
+ " - j is > 0?\n",
+ " - print j is 4\n",
+ " - j = 3\n",
+ " - j is > 0?\n",
+ " - print j is 3\n",
+ " - j = 2\n",
+ " - j is > 0?\n",
+ " - print j is 2\n",
+ " - j = 1\n",
+ " - j is > 0?\n",
+ " - print j is 1\n",
+ " - j = 0\n",
+ " - j is > 0? NO.\n",
+ "- i<3? yes (i is 1)\n",
+ " - print i is 1\n",
+ " - i = 2\n",
+ " - j is > 0? NO\n",
+ "- i<3? yes (i is 2)\n",
+ " - print i is 2\n",
+ " - i = 3\n",
+ " - j is > 0? NO\n",
+ "- i<3? NO (i is 3)\n",
+ "THE END"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "330ee144-ece1-4fa6-958e-d4e74d15a9f9",
+ "metadata": {},
+ "source": [
+ "# Extra: enumerate and zip function"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3e7e82ad-54bb-4ab9-9313-4b6468d9a861",
+ "metadata": {
+ "lang": "en"
+ },
+ "source": [
+ "## Enumerate function: Iterate through lists over their index\n",
+ "\n",
+ "In Python, we can iterate through a list and access both the index and value of each element using the `enumerate()` function. It returns an iterator that generates pairs of index and value for each element in the list. By using `enumerate()`, we can easily access and work with the index and value within the loop.\n",
+ "\n",
+ "- Built in functions --> https://docs.python.org/3/library/functions.html\n",
+ "- Enumerate doc --> https://book.pythontips.com/en/latest/enumerate.html"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "id": "38fee66c-421a-4b2f-940f-1bd2f9575aa7",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Index: 0 Fruit: apple\n",
+ "Index: 1 Fruit: banana\n",
+ "Index: 2 Fruit: orange\n"
+ ]
+ }
+ ],
+ "source": [
+ "fruits = ['apple', 'banana', 'orange']\n",
+ "\n",
+ "for index, fruit in enumerate(fruits):\n",
+ " print(\"Index:\", index, \"Fruit:\", fruit)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3b7c6efd-8042-49c1-bbdf-fa885fd4d93e",
+ "metadata": {
+ "lang": "en"
+ },
+ "source": [
+ "## Zip function: Loop through two lists at the same time"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "9193408f-486e-449c-80e4-997229360574",
+ "metadata": {},
+ "source": [
+ "In Python, the `zip()` function is used to combine multiple iterables into a single iterable of tuples. Each tuple contains elements from the corresponding positions of the input iterables. It allows you to iterate over multiple lists or other iterables together and work with their corresponding elements."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "053a7a8b-c26f-481c-a50e-6664a5a9b1e9",
+ "metadata": {
+ "lang": "en"
+ },
+ "source": [
+ "The resulting iterable stops when the shortest input is exhausted. You can refer to the official [documentation](https://docs.python.org/3/library/functions.html) of `zip()` for more details on its usage and behavior.\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "id": "0f19790f-d051-49b7-9627-74b75e4e35de",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Alice is 25 years old and scored 95 on the test\n",
+ "Bob is 30 years old and scored 80 on the test\n",
+ "Charlie is 35 years old and scored 90 on the test\n"
+ ]
+ }
+ ],
+ "source": [
+ "names = ['Alice', 'Bob', 'Charlie']\n",
+ "ages = [25, 30, 35]\n",
+ "scores = [95, 80, 90]\n",
+ "\n",
+ "for name, age, score in zip(names, ages, scores):\n",
+ " print(name, 'is', age, 'years old and scored', score, 'on the test')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2f9d6ddc-8604-49d8-8b63-474d5346f6ac",
+ "metadata": {},
+ "source": [
+ "In the following example, the `names` list has three elements, the `ages` list has two elements, and the `scores` list has three elements. Since `zip()` stops when the shortest input list (`ages`) is exhausted, the iteration only proceeds for two tuples."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "id": "b7a8bbfa-fb8a-4476-a8a8-c041c573031e",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Alice is 25 years old and scored 95 on the test\n",
+ "Bob is 30 years old and scored 80 on the test\n"
+ ]
+ }
+ ],
+ "source": [
+ "names = ['Alice', 'Bob', 'Charlie']\n",
+ "ages = [25, 30]\n",
+ "scores = [95, 80, 90]\n",
+ "\n",
+ "for name, age, score in zip(names, ages, scores):\n",
+ " print(name, 'is', age, 'years old and scored', score, 'on the test')\n"
]
},
{
"cell_type": "markdown",
- "id": "3851fcd1-cf98-4653-9c89-e003b7ec9400",
+ "id": "eaca0324-22d9-4f88-9d36-64ee9cbe0fac",
"metadata": {},
"source": [
- "## Exercise: Managing Customer Orders Optimized\n",
+ "In Python, you can \"unzip\" a list of tuples using the `zip()` function in combination with the `*` operator. This operation is commonly referred to as \"unzipping\" because it separates the tuples back into individual lists.\n",
"\n",
- "In the last lab, you were starting an online store that sells various products. To ensure smooth operations, you developed a program that manages customer orders and inventory.\n",
+ "Here's an example to illustrate how to unzip a list of tuples:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 29,
+ "id": "9d5a614e-1efb-443b-9129-2d4b27230d3f",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "('Alice', 'Bob', 'Charlie')\n",
+ "(25, 30, 35)\n"
+ ]
+ }
+ ],
+ "source": [
+ "data = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]\n",
"\n",
- "You did so without using flow control. Let's go a step further and improve this code.\n",
+ "names, ages = zip(*data)\n",
"\n",
- "Follow the steps below to complete the exercise:\n",
+ "print(names)\n",
+ "print(ages)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "46fcf708-08c6-457a-a995-35a95bacb591",
+ "metadata": {},
+ "source": [
+ "In this example, the `data` list contains tuples representing names and ages. By using `zip(*data)`, we pass each tuple as separate arguments to the `zip()` function. The result is two separate tuples, one for names and one for ages.\n",
"\n",
- "1. Look at your code from the lab data structures, and improve repeated code with loops.\n",
+ "By assigning the result of `zip(*data)` to `names` and `ages`, we \"unzip\" the original list of tuples. Now, we have separate lists for names and ages, which we can print or use independently.\n",
"\n",
- "2. Instead of asking the user to input the name of three products that a customer wants to order, do the following:\n",
- " \n",
- " a. Prompt the user to enter the name of a product that a customer wants to order.\n",
- " \n",
- " b. Add the product name to the \"customer_orders\" set.\n",
- " \n",
- " c. Ask the user if they want to add another product (yes/no).\n",
- " \n",
- " d. Continue the loop until the user does not want to add another product.\n",
+ "This technique can be useful when you have a list of tuples and want to separate them into individual lists for further processing or analysis.\n",
"\n",
- "3. Instead of updating the inventory by subtracting 1 from the quantity of each product, only do it for the products that were ordered (those in \"customer_orders\")."
+ "It's important to note that when unzipping, the number of lists you unpack should match the number of elements in each tuple in the original list. If they don't match, you may encounter a `ValueError` due to the mismatch in the number of elements."
]
}
],
@@ -55,7 +1777,20 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.9.13"
+ "version": "3.13.6"
+ },
+ "toc": {
+ "base_numbering": 1,
+ "nav_menu": {},
+ "number_sections": true,
+ "sideBar": true,
+ "skip_h1_title": false,
+ "title_cell": "Table of Contents",
+ "title_sidebar": "Contents",
+ "toc_cell": true,
+ "toc_position": {},
+ "toc_section_display": true,
+ "toc_window_display": true
}
},
"nbformat": 4,