{ "cells": [ { "cell_type": "markdown", "id": "encouraging-consumption", "metadata": {}, "source": [ "\n", "\n", "\n", "

Python Programming: Loops

\n", "\n", "\n", "\n", "\n", "\n", "---\n", "\n", "## Learning Objectives\n", "*After this lesson, you will be able to:*\n", "\n", "- Use a `for` loop to iterate a list.\n", "- Use `range()` to dynamically generate loops.\n", "- Use a `while` loop to control program flow.\n", "- Use `break` to exit a loop.\n", "\n", "---\n", "\n", "## Discussion: A Small List\n", "\n", "\n", "This situation isn't so bad:\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "sweet-airline", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "red\n", "orange\n", "yellow\n", "green\n", "blue\n", "violet\n" ] } ], "source": [ "visible_colors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"violet\"]\n", "print(visible_colors[0])\n", "print(visible_colors[1])\n", "print(visible_colors[2])\n", "print(visible_colors[3])\n", "print(visible_colors[4])\n", "print(visible_colors[5])\n" ] }, { "cell_type": "markdown", "id": "polished-holocaust", "metadata": {}, "source": [ "- But what would we do if there were 1,000 items in the list to print?\n", "- One of the most powerful things that programming can do for you is automatically perform repetitive tasks.\n", "\n", "---\n", "\n", "## The `for` Loop\n", "\n", "\n", "\n", "The `for` loop always follows this form:\n", "\n" ] }, { "cell_type": "markdown", "id": "catholic-fighter", "metadata": {}, "source": [ "for item in collection:\n", "\n", " # Do something with item\n" ] }, { "cell_type": "markdown", "id": "focal-tomato", "metadata": {}, "source": [ "\n", "For example:\n", "\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "genuine-delhi", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "red\n", "orange\n", "yellow\n", "green\n", "blue\n", "violet\n" ] } ], "source": [ "visible_colors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"violet\"]\n", "\n", "for each_color in visible_colors:\n", " print(each_color)\n" ] }, { "cell_type": "markdown", "id": "interested-traveler", "metadata": {}, "source": [ "---\n", "\n", "## Knowledge Check: What will this code do?\n", "\n", "\n", "Think about what the code will do before you actually run it.\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "graduate-lancaster", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Now appearing in the Refreshment Room...\n", "Tom\n", "Now appearing in the Refreshment Room...\n", "Deborah\n", "Now appearing in the Refreshment Room...\n", "Murray\n", "Now appearing in the Refreshment Room...\n", "Axel\n", "THUNDEROUS APPLAUSE!\n" ] } ], "source": [ "for name in [\"Tom\", \"Deborah\", \"Murray\", \"Axel\"]:\n", " print(\"Now appearing in the Refreshment Room...\") # in the loop\n", " print(name) # in the loop\n", "print(\"THUNDEROUS APPLAUSE!\") # OUTSIDE the loop" ] }, { "cell_type": "markdown", "id": "prescription-seeking", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## We Do: Writing a Loop\n", "\n", "Let's write a loop to print names of guests.\n", "\n", "First, we need a list.\n", "\n", "- Make your list: Declare a variable `my_list` and assign it to a list containing the names of at least five people.\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "british-failing", "metadata": {}, "outputs": [], "source": [ "my_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]" ] }, { "cell_type": "markdown", "id": "virgin-alberta", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## We Do: Write a Loop - Making the Loop\n", "\n", "\n", "Now, we'll add the loop.\n", "\n", "- Write the first line of your `for` loop.\n", " - For the variable that holds each item, give it a name that reflects what the item is (e.g. `name` or `person`).\n", "- Inside your loop, add the code to print `\"Hello,\"` plus the name.\n", "\n" ] }, { "cell_type": "markdown", "id": "unique-campaign", "metadata": {}, "source": [ "`\"Hello, Felicia!\"\n", "\"Hello, Srinivas!\"`\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "developmental-palestinian", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Fred!\n", "Hello, Cho!\n", "Hello, Brandi!\n", "Hello, Yuna!\n", "Hello, Nanda!\n", "Hello, Denise!\n" ] } ], "source": [ "for name in my_list:\n", " # Print out a greeting in here\n", " print(f\"Hello, {name}!\")" ] }, { "cell_type": "markdown", "id": "invisible-terrorist", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## We Do: Write a loop to greet people on your list\n", "\n", "Our guests are definitely VIPs! Let's give them a lavish two-line greeting.\n", "\n", "- Inside your loop, add the code to print another sentence of greeting:\n", "\n", "`\"Hello, Srinivas!\" \n", "\"Welcome to the party!\"`\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "intensive-civilian", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Fred!\n", "Welcome to the party!\n", "Hello, Cho!\n", "Welcome to the party!\n", "Hello, Brandi!\n", "Welcome to the party!\n", "Hello, Yuna!\n", "Welcome to the party!\n", "Hello, Nanda!\n", "Welcome to the party!\n", "Hello, Denise!\n", "Welcome to the party!\n" ] } ], "source": [ "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for guest in guest_list:\n", " # Print out a greeting in here\n", " print(f\"Hello, {guest}!\")\n", " print(\"Welcome to the party!\")\n" ] }, { "cell_type": "markdown", "id": "aware-investigator", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Discussion: Where Else Could We Use a Loop?\n", "\n", "\n", "A loop prints everything in a collection of items.\n", "\n", "- `guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]`\n", "\n", "What, besides a list, could we use a loop on?\n", "\n", "*Hint: There are six in this cell!*\n", "\n", "---\n", "\n", "## Looping Strings\n", "\n", "- Lists are collections of strings and numbers (and other things).\n", "- Strings are collections of characters!" ] }, { "cell_type": "code", "execution_count": 10, "id": "laughing-status", "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": [ "my_string = \"Hello, world!\"\n", "\n", "for character in my_string:\n", " print(character)\n" ] }, { "cell_type": "markdown", "id": "excess-briefing", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## What about...Looping For a Specific Number of Iterations?\n", "\n", "\n", "We have:\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "light-solution", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Fred!\n", "Hello, Cho!\n", "Hello, Brandi!\n", "Hello, Yuna!\n", "Hello, Nanda!\n", "Hello, Denise!\n" ] } ], "source": [ "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for guest in guest_list:\n", " print(f\"Hello, {guest}!\")\n" ] }, { "cell_type": "markdown", "id": "worldwide-anniversary", "metadata": {}, "source": [ "\n", "The loop runs for every item in the list - the length of the collection. Here, it runs 6 times.\n", "\n", "What if we don't know how long `guest_list` will be?\n", "\n", "Or only want to loop some of it?\n", "\n", "---\n", "\n", "## Enter: Range\n", "\n", "\n", "`range(x)`:\n", "\n", "- Automatically generated.\n", "- A list that contains only integers.\n", "- Starts at zero.\n", "- Stops before the number you input.\n", "\n" ] }, { "cell_type": "code", "execution_count": 12, "id": "together-milton", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "range(0, 5)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# range(start, stop, step)\n", "range(5) # => [0, 1, 2, 3, 4]" ] }, { "cell_type": "code", "execution_count": 14, "id": "genuine-architecture", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0, 1, 2, 3, 4]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(5))" ] }, { "cell_type": "markdown", "id": "smoking-mercy", "metadata": {}, "source": [ "You can actually feed more parameters into `range()` to control what number it starts at and how big each step is to the next number, but we will keep it simple for now. For now it is enough to know that if you loop over `range(5)` then your loop will execute **five** times.\n", "\n", "---\n", "\n", "## Looping Over a Range\n", "\n", "Let's look at `range` in action:" ] }, { "cell_type": "code", "execution_count": 13, "id": "foreign-agent", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "[0, 1, 4, 9, 16]\n" ] } ], "source": [ "for i in range(10):\n", " print(i)\n", "\n", "squares = []\n", "\n", "for num in range(5):\n", " sqr = num ** 2\n", " squares.append(sqr)\n", "\n", "print(squares)" ] }, { "cell_type": "markdown", "id": "boolean-philippines", "metadata": {}, "source": [ "\n", "\n", "---\n", "\n", "## Looping Over a Range\n", "\n", "Looping over `names` here is really just going through the loop 4 times - at index `0`, `1`, `2`, and `3`.\n", "\n", "We can instead use `range(x)` to track the index and loop `names`: `range(4)` is `[0, 1, 2, 3]`.\n", "\n", "We can then use `len(names)`, which is 4, as our range." ] }, { "cell_type": "code", "execution_count": 15, "id": "secondary-netscape", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Flint\n", "John Cho\n", "Billy Bones\n", "Nanda Yuna\n" ] } ], "source": [ "names = [\"Flint\", \"John Cho\", \"Billy Bones\", \"Nanda Yuna\"]\n", "\n", "for index in range(len(names)):\n", " print(names[index])" ] }, { "cell_type": "markdown", "id": "attempted-bacteria", "metadata": {}, "source": [ "\n", "\n", "---\n", "\n", "## Range to Modify Collections\n", "\n", "Why would you use `range` on a list, when you could just loop the list?\n", "\n", "We can't do:\n", "\n" ] }, { "cell_type": "code", "execution_count": 16, "id": "quarterly-bubble", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Fred', 'Cho', 'Brandi', 'Yuna', 'Nanda', 'Denise']\n" ] } ], "source": [ "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for guest in guest_list:\n", " guest = \"A new name\"\n", "\n", "print(guest_list)" ] }, { "cell_type": "markdown", "id": "czech-novelty", "metadata": {}, "source": [ "\n", "But we can do:\n", "\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "interested-touch", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A new name', 'A new name', 'A new name', 'A new name', 'A new name', 'A new name']\n" ] } ], "source": [ "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for i in range(len(guest_list)):\n", " guest_list[i] = \"A new name\"\n", "\n", "print(guest_list)" ] }, { "cell_type": "markdown", "id": "configured-reproduction", "metadata": {}, "source": [ "---\n", "## Looping Over a Range\n", "\n", "Let's make the list all uppercase:\n" ] }, { "cell_type": "code", "execution_count": 18, "id": "proved-vienna", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Without range, guest_list is ['Fred', 'Cho', 'Brandi', 'Yuna', 'Nanda', 'Denise']\n", "With range, guest_list is ['FRED', 'CHO', 'BRANDI', 'YUNA', 'NANDA', 'DENISE']\n" ] } ], "source": [ "# This won't work\n", "\n", "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for guest in guest_list:\n", " guest = guest.upper() \n", "\n", "print(\"Without range, guest_list is\", guest_list)\n", "\n", "# This will!\n", "\n", "for i in range(len(guest_list)):\n", " guest_list[i] = guest_list[i].upper()\n", "\n", "print(\"With range, guest_list is\", guest_list)" ] }, { "cell_type": "markdown", "id": "vital-studio", "metadata": {}, "source": [ "You can also use the `enumerate` function to loop over both the index and list elements simultaneously." ] }, { "cell_type": "code", "execution_count": 22, "id": "nominated-stations", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['FRED', 'CHO', 'BRANDI', 'YUNA', 'NANDA', 'DENISE']" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "\n", "for i, name in enumerate(guest_list):\n", " guest_list[i] = name.upper()\n", " \n", "guest_list" ] }, { "cell_type": "markdown", "id": "personalized-interaction", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Knowledge Check: Which of the following lines is correct?\n", "\n" ] }, { "cell_type": "markdown", "id": "marine-paradise", "metadata": {}, "source": [ "`my_list = ['mon', 'tue', 'wed', 'thu', 'fri']`\n", "\n", "A: `for day in range(my_list):` \n", "\n", "B: `for day in range(len(my_list)):` \n", "\n", "C: `for day in range(my_list.length):` \n" ] }, { "cell_type": "markdown", "id": "advance-divorce", "metadata": {}, "source": [ "\n", "---\n", "\n", "## You Do: Range\n", "\n", "- Create a list of colors.\n", "- Using a `for` loop, print out the list.\n", "- Using `range`, set each item in the list to be the number of characters in the list.\n", "- Print the list." ] }, { "cell_type": "code", "execution_count": 23, "id": "invalid-candidate", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "red\n", "green\n", "blue\n", "[3, 5, 4]\n" ] } ], "source": [ "colors = [\"red\", \"green\", \"blue\"]\n", "\n", "for color in colors:\n", " print(color)\n", "\n", "for i in range(len(colors)):\n", " colors[i] = len(colors[i])\n", " \n", "print(colors)" ] }, { "cell_type": "markdown", "id": "attended-seafood", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Quick Review: For Loops and Range\n", "\n", "\n", "`for` loops:\n", "\n" ] }, { "cell_type": "code", "execution_count": 24, "id": "elementary-position", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, Fred!\n", "Hello, Cho!\n", "Hello, Brandi!\n", "Hello, Yuna!\n", "Hello, Nanda!\n", "Hello, Denise!\n", "H\n", "e\n", "l\n", "l\n", "o\n", ",\n", " \n", "w\n", "o\n", "r\n", "l\n", "d\n", "!\n", "Flint\n", "John Cho\n", "Billy Bones\n", "Nanda Yuna\n", "Flint\n", "John Cho\n", "Billy Bones\n", "Nanda Yuna\n" ] } ], "source": [ "# On a list (a collection of strings)\n", "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "for guest in guest_list:\n", " print(\"Hello, \" + guest + \"!\")\n", "\n", "# On a string (a collection of characters)\n", "my_string = \"Hello, world!\"\n", "for character in my_string:\n", " print(character)\n", "\n", "##### Range #####\n", "\n", "range(4) # => [0, 1, 2, 3]\n", "\n", "# Using Range as an Index Counter\n", "names = [\"Flint\", \"John Cho\", \"Billy Bones\", \"Nanda Yuna\"]\n", "for each_name in range(4):\n", " print(names[each_name])\n", "\n", "# OR\n", "\n", "for each_name in range(len(names)):\n", " print(names[each_name])\n", "\n", "# Using Range to Change a List:\n", "\n", "guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n", "for guest in range(len(guest_list)):\n", " guest_list[guest] = \"A new name\"" ] }, { "cell_type": "markdown", "id": "later-hands", "metadata": {}, "source": [ "\n", "---\n", "\n", "## The While Loop\n", "\n", "\n", "What about \"While the bread isn't brown, keep cooking\"?\n", "\n", "Python provides two loop types.\n", "\n", "`for`:\n", "\n", "- You just learned!\n", "- Loops over collections a finite number of times.\n", "\n", "`while`:\n", "\n", "- You're about to learn!\n", "- When your loop could run an indeterminate number of times.\n", "- Checks if something is `True` *(the bread isn't brown yet)* and runs until it's set to `False` *(now the bread is brown, so stop)*.\n", "\n", "---\n", "\n", "## While Loop Syntax\n", "\n" ] }, { "cell_type": "code", "execution_count": 25, "id": "utility-pearl", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# While is true:\n", "# Run some code\n", "# If you're done, set the to false\n", "# Otherwise, repeat.\n", "\n", "a = 0\n", "while a < 10:\n", " print(a)\n", " a += 1\n" ] }, { "cell_type": "markdown", "id": "normal-poland", "metadata": {}, "source": [ "\n", "![](https://upload.wikimedia.org/wikipedia/commons/4/43/While-loop-diagram.svg)\n", "\n", "---\n", "\n", "## While Loop: Be Careful!\n", "\n", "\n", "Don't *ever* do:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "german-profit", "metadata": {}, "outputs": [], "source": [ "# a = 0\n", "# while a < 10:\n", "# print(a)" ] }, { "cell_type": "markdown", "id": "medium-tribute", "metadata": {}, "source": [ "\n", "And don't ever do:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "liquid-butter", "metadata": {}, "outputs": [], "source": [ "# a = 0\n", "# while a < 10:\n", "# print(a)\n", "# a += 1" ] }, { "cell_type": "markdown", "id": "literary-electron", "metadata": {}, "source": [ "Your program will run forever!\n", "\n", "If your program ever doesn't leave a loop, you can interrupt or shutdown the kernel by clicking \"Kernel\" at the top and selecting on of the options.\n", "\n", "---\n", "\n", "## We Do: Filling a Glass of Water\n", "\n", "Create a new local file, `practicing_while.py`.\n", "\n", "In it, we'll create:\n", "\n", "- A variable for our current glass content.\n", "- Another variable for the total capacity of the glass.\n", "\n", "Let's start with this:\n", "\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "composite-spectacular", "metadata": {}, "outputs": [], "source": [ "glass = 0\n", "glass_capacity = 12" ] }, { "cell_type": "markdown", "id": "mental-magic", "metadata": {}, "source": [ "Can you start the `while` loop?\n", "\n", "---\n", "\n", "## We Do: Filling a Glass of Water\n", "\n", "\n", "Add the loop:\n", "\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "interstate-subcommittee", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "glass = 0\n", "glass_capacity = 12\n", "\n", "while glass < glass_capacity:\n", " glass += 1 # Here is where we add more water\n", "glass" ] }, { "cell_type": "markdown", "id": "requested-postage", "metadata": {}, "source": [ "That's it!\n", "\n", "---\n", "\n", "\n", "## Side Note: Input()\n", "\n", "Let's do something more fun.\n", "\n", "With a partner, you will write a program that:\n", "\n", "- Has a user guess a number.\n", "- Runs until the user guesses.\n", "\n", "But first, how do we have users input numbers?\n", "\n", "Using `input()`.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "paperback-japan", "metadata": {}, "outputs": [], "source": [ "user_name = input(\"Please enter your name:\")\n", "# user_name now has what the user typed\n", "print(user_name)" ] }, { "cell_type": "markdown", "id": "helpful-judge", "metadata": {}, "source": [ "Run it! What happens? Does it work?\n", "\n", "---\n", "\n", "## You Do: A Guessing Game\n", "\n", "Now, get with a partner! Let's write the the game.\n", "\n", "Decide who will be driver and who will be navigator. Add this to your existing file.\n", "\n", "- Set a variable, `answer` to `\"5\"` (yes, a string!).\n", "- Prompt the user for a guess and save it in a new variable, `guess`.\n", "- Create a `while` loop, ending when `guess` is equal to `answer`.\n", "- In the `while` loop, prompt the user for a new `guess`.\n", "- After the `while` loop, print \"You did it!\"" ] }, { "cell_type": "code", "execution_count": null, "id": "controversial-terror", "metadata": {}, "outputs": [], "source": [ "answer = \"5\"\n", "guess = input(\"Guess what number I'm thinking of (1-10): \")\n", "while guess != answer:\n", " guess = input(\"Nope, try again: \")\n", " \n", "print(\"You got it!\")" ] }, { "cell_type": "markdown", "id": "apart-prospect", "metadata": {}, "source": [ "Discuss with your partner: Why do we need to make an initial variable before the loop?\n", "\n", "---\n", "\n", "## Exiting a Loop\n", "\n", "There are times when you may want to exit a loop before the final condition has been met. Perhaps the input from another part of the program has satisfied another, separate condition that makes the rest of the loop unnecessary. Enter the `break` statement.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "external-information", "metadata": {}, "outputs": [], "source": [ "my_condition = 1\n", "\n", "while True:\n", "\n", " if my_condition == 1:\n", " # my condition is met! No need to continue on\n", " break\n", " else:\n", " my_condition = 1\n", "\n", " # note that this is within the scope of the while loop\n", " print('This doesn\\'t get run if the break is triggered!')\n" ] }, { "cell_type": "markdown", "id": "standing-camcorder", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Continuing a Loop\n", "\n", "There are times when you may want to to `continue` a loop _without running code beneath the `continue` statement_. The `continue` allows you to do just that! After the `continue` statement is triggered, the loop _continues the next iteration of the loop without executing any code beneath it on that iteration_.\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "applied-visit", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number is 1\n", "Number is 2\n", "Number is 4\n", "Number is 5\n", "Out of loop\n" ] } ], "source": [ "number = 0\n", "for number in range(5):\n", " number = number + 1\n", " if number == 3:\n", " continue\n", " print('My number is currently 3')\n", " print(f'Number is {number}')\n", "print('Out of loop')" ] }, { "cell_type": "markdown", "id": "vertical-survey", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Passing within a Loop\n", "\n", "The `pass` statement is like a placebo in a loop: it allows a loop to execute without any interruption. This example may seem odd, and we'll cover the more common use case in the next example.\n", "\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "sufficient-jaguar", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number is 1\n", "Number is 2\n", "My number is currently 3\n", "Number is 3\n", "Number is 4\n", "Number is 5\n", "Out of loop\n" ] } ], "source": [ "number = 0\n", "for number in range(5):\n", " number = number + 1\n", " if number == 3:\n", " pass\n", " print('My number is currently 3')\n", " print(f'Number is {number}')\n", "print('Out of loop')" ] }, { "cell_type": "markdown", "id": "adjusted-chassis", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Passing within a Function or Class\n", "\n", "The most common use case for `pass` is to act as a placeholder for a function that has yet to be written. Developers will often do this if they're creating the architecture for a program but haven't gotten to actually building the logic yet.\n", "\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "outside-metabolism", "metadata": {}, "outputs": [], "source": [ "def my_empty_function():\n", " pass\n", "\n", "my_empty_function()" ] }, { "cell_type": "markdown", "id": "sexual-handbook", "metadata": {}, "source": [ "\n", "What happens if we _don't_ put the `pass` statement in the code and attempt to execute the function definition?\n", "\n", "---\n", "\n", "## Throwing Exceptions within a Function or Class\n", "\n", "Note that the previous example will allow the function to be called, but the function won't do anything. If the programmer wishes to alert the user, they may also use `raise` to interrupt the program execution. The following is common to see in larger applications that are in the process of being built by a dev team:\n", "\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "suspected-spiritual", "metadata": {}, "outputs": [ { "ename": "NotImplementedError", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNotImplementedError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mraise\u001b[0m \u001b[0mNotImplementedError\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mmy_empty_function\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m\u001b[0m in \u001b[0;36mmy_empty_function\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0mmy_empty_function\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mNotImplementedError\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[0mmy_empty_function\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNotImplementedError\u001b[0m: " ] } ], "source": [ "def my_empty_function():\n", " raise NotImplementedError\n", " \n", "my_empty_function()" ] }, { "cell_type": "markdown", "id": "optimum-activity", "metadata": {}, "source": [ "\n", "What happens when we call this function? _Hint: look at the type of error that is returned!_\n", "\n", "---\n", "\n", "## Summary + Q&A\n", "\n", "Loops:\n", "\n", "- Common, powerful control structures that let us efficiently deal with repetitive tasks.\n", "\n", "`for` loops:\n", "\n", "- Used to iterate a set number of times over a collection (e.g. list, string, or using `range`).\n", "- `range` use indices, not duplicates, so it lets you modify the collection.\n", "\n", "`while` loops:\n", "\n", "- Run until a condition is false.\n", "- Used when you don't know how many times you need to iterate.\n", "\n", "That was a tough lesson! Any questions?\n", "\n", "---\n", "\n", "## Additional Reading\n", "\n", "- [Learn Python Programming: Loops Video](https://www.youtube.com/watch?v=JkQ0Xeg8LRI)\n", "- [Python: For Loop](https://wiki.python.org/moin/ForLoop)\n", "- [Python: Loops](https://www.tutorialspoint.com/python/python_loops.htm)" ] } ], "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.7.6" } }, "nbformat": 4, "nbformat_minor": 5 }