{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "# For Loops (5 min / 5 min exercises)\n", "\n", "This topic can be challenging, however, we already know the basics. Let's work together and get ready for Assignment 1.\n", "\n", "#### Learning objectives\n", "By the end of this notebook you will be able to:\n", "+ Explain what `for` loops are normally used for.\n", "+ Trace the execution of a simple loop and correctly state the values of variables in each iteration." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Before we start**: One of the essential data structures in Python is a **List**, which is a data type that stores many values in a single variable. For instance: " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.234, 0.434, 0.55, 0.423]\n" ] } ], "source": [ "temperature = [0.234, 0.434, 0.55, 0.423]\n", "print(temperature)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the next tutorial we'll learn more about **List** data type." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Alice', 'Xiaojing', 'Julio', 'Victoria', 'Maria', 'Turgay']\n" ] } ], "source": [ "## Let's create a List with my students\n", "my_students = [\"Alice\", \"Xiaojing\", \"Julio\", \"Victoria\", \"Maria\", \"Turgay\"]\n", "print(my_students)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Alice', 'Xiaojing', 'Julio', 'Victoria', 'Maria', 'Turgay']\n" ] } ], "source": [ "## Let's say I'm teaching a tutorial, and I want to save the names of all of my students\n", "\n", "## One way is to create a variable for each one, and save one name per variable\n", "\n", "student_1 = \"Alice\"\n", "student_2 = \"Xiaojing\"\n", "student_3 = \"Julio\"\n", "\n", "## This works ok... but it makes more sense to keep a single list!\n", "\n", "my_students = [\"Alice\", \"Xiaojing\", \"Julio\", \"Victoria\", \"Maria\", \"Turgay\"]\n", "print(my_students)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Elements* within a list can be accessed by their *index number*\n", "\n", "*Index numbers* start at index 0, meaning that the first element in the list is at element 0" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Xiaojing'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_students[0] ## You access elements of a list using this notation\n", "my_students[1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, a **for loop** is one of the most fundamental operations to learn properly how to code and automate things, but can be tricky to learn for the first time. Python has several ways of performing loops." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **1. A _for loop_ executes commands once for each element (value) in a List**:\n", "\n", "+ A _for loop_ tells Python to execute some statements once for each value in a list, a character string, or some other collection." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "# for each element in the list, do these operations\n", "for number in [1,2,3,4]:\n", " print(number)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **2. An essential _for_ loop is made up of a _List_, a _loop variable_, and a _body_:**\n", "\n", "+ The **_list_**, `[1,3,5]`, is what the loop is being run on.\n", "+ The **_body_**, `print(number)`, specifies what to do for each element in the list.\n", "+ The **_loop variable_**, `number`, is what changes for each _iteration_ of the loop (i.e., the current element)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **3. Indentation matters!**\n", "The first line of the _for_ loop must end with a colon `:`, and the body must be indented:\n", "\n", "+ The colon at the end of the first line signals the start of a _block_ of statements.\n", "+ Python uses indentation rather `{}` or `begin/end` to show _nesting_:\n", " + Any consistent indentation legal, but almost everyone uses **four** spaces. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **4. Loop variable can be called anything**:\n", "+ As with all variables, loop variables are:\n", " * Created on demand.\n", " * Meaningless: their names can be anything at all." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **5. Use `range` to iterate over a sequence of numbers**:\n", "+ The built-in function `range` produces a sequence of numbers.\n", " + _Not a list_: the number are produced on demand to make looping over large ranges more efficient.\n", "+ `range(N)` is the numbers 0 ... _N-1_." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "## We use a function to automatically create a list of numbers, starting at 0,\n", "## and ending at 19\n", "my_numbers = list(range(0,20))\n", "\n", "my_numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "EXERCISES - 5 min" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* _1. Make a `list` with [member states of the Association of SouthEast Asian Nations](https://en.wikipedia.org/wiki/ASEAN)._\n", "\n", "for instance:\n", "\n", "```python\n", "ASEAN_countries = [\"\", \"\", \"\", \"\"]\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ _2. Use for loop to print each element (country) of your `list` with the ASEAN memebers states_\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* _3. What does the following for loop do?_\n", "\n", "```python\n", "\n", "my_numbers = list(range(0,20))\n", "\n", "for number in my_numbers:\n", " if number == 5:\n", " print(\"Hey, I love 5!\")\n", " else:\n", " print(number)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* _4. Read the code below and try to identify what the errors are without running it.\n", " Run the code, and read the error message. What type of error is it?\n", " Fix the error._\n", "```python\n", "brics = ['Brazil', 'Russia', 'China', 'South Africa']\n", "print('the least populated country within BRICS is', brics[4])\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "+ *5. Create a list with the names of your break out room and write a loop function that prints each name of your list. For instance*:\n", "\n", "```python\n", "my_students = []\n", "for ___ in my_students:\n", " print()\n", "```" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 4 }