You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
1100 lines
27 KiB
1100 lines
27 KiB
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "structural-attribute",
|
|
"metadata": {},
|
|
"source": [
|
|
"<!--\n",
|
|
"title: Python Programming: Loops\n",
|
|
"type: lesson\n",
|
|
"duration: \"01:00\"\n",
|
|
"creator: Susi Remondi\n",
|
|
"-->\n",
|
|
"\n",
|
|
"<h1>Python Programming: Loops</h1>\n",
|
|
"\n",
|
|
"\n",
|
|
"<!--\n",
|
|
"\n",
|
|
"## Overview\n",
|
|
"This lesson introduces students to the concept of creating `for` and `while` loops. It begins with `for`, covering lists and strings, then goes into using `range` to modify a list. It then dives into `while` loops.\n",
|
|
"\n",
|
|
"## Learning Objectives\n",
|
|
"In this lesson, students will:\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",
|
|
"\n",
|
|
"## Duration\n",
|
|
"60 minutes\n",
|
|
"\n",
|
|
"### Note on timing:\n",
|
|
"Loops are crucial to programming. If students are struggling, extend the amount of time here. You can generate exercises by giving sample scenarios. Fizzbuzz is a great problem to give them, if you have time!\n",
|
|
"\n",
|
|
"\n",
|
|
"## Suggested Agenda\n",
|
|
"\n",
|
|
"| Time | Activity |\n",
|
|
"| --- | --- |\n",
|
|
"| 0:00 - 0:03 | Welcome |\n",
|
|
"| 0:00 - 0:33 | `For` Loops |\n",
|
|
"| 0:33 - 0:50 | `While` Loops |\n",
|
|
"| 0:50 - 1:00 | Summary |\n",
|
|
"\n",
|
|
"## In Class: Materials\n",
|
|
"- Projector\n",
|
|
"- Internet connection\n",
|
|
"- Python3\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": null,
|
|
"id": "governing-earthquake",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "alternate-defeat",
|
|
"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",
|
|
"**Talking Points**:\n",
|
|
"\"A common and extremely useful type of loop is the `for` loop. `for` loops appear in several computer programming languages and get their name from the fact that they loop (or iterate) **for** a specific number of times: once **for** each item in a list.\"\n",
|
|
"\n",
|
|
"\"The `for` loop is perfect for when you have a specific collection of items — each of which must be processed once — or for when you know that you must execute a set of instructions a specific number of times. Those are the use cases for which it was designed.\"\n",
|
|
"\n",
|
|
"\"This is our template. When we write a `for` loop we do the following:\n",
|
|
"* We replace `item` with a meaningful name for the items in the collection.\n",
|
|
" * We use this name as the name of the item within our loop.\n",
|
|
"* We replace `collection` with the name of our list (or other collection).\n",
|
|
"* Indented inside the loop, we write the code to be run for each item.\n",
|
|
"* Python will start with the first item and automatically stop after it loops with the last item.\"\n",
|
|
"-->\n",
|
|
"\n",
|
|
"The `for` loop always follows this form:\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "nominated-property",
|
|
"metadata": {},
|
|
"source": [
|
|
"for item in collection:\n",
|
|
"\n",
|
|
" # Do something with item\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "breathing-reply",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"For example:\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "average-retro",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"visible_colors = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"violet\"]\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "hollow-thread",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"\n",
|
|
"## Knowledge Check: What will this code do?\n",
|
|
"\n",
|
|
"\n",
|
|
"Think about what the code will do before you actually run it."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "cutting-pipeline",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "modern-kansas",
|
|
"metadata": {},
|
|
"source": [
|
|
"\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": null,
|
|
"id": "infinite-professor",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "proprietary-deficit",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"</aside>\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."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "instrumental-fairy",
|
|
"metadata": {},
|
|
"source": [
|
|
"`\"Hello, Felicia!\"\n",
|
|
"\"Hello, Srinivas!\"`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "hidden-bonus",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "bigger-council",
|
|
"metadata": {},
|
|
"source": [
|
|
"\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": null,
|
|
"id": "preceding-enemy",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "explicit-negative",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"</aside>\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": null,
|
|
"id": "generic-chance",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"my_string = \"Hello, world!\"\n",
|
|
"\n",
|
|
"for character in my_string:\n",
|
|
" print(character)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "extreme-builder",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"</aside>\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"## What about...Looping For a Specific Number of Iterations?\n",
|
|
"\n",
|
|
"\n",
|
|
"We have:\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "desperate-whole",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"guest_list = [\"Fred\", \"Cho\", \"Brandi\", \"Yuna\", \"Nanda\", \"Denise\"]\n",
|
|
"\n",
|
|
"for guest in guest_list:\n",
|
|
" print(f\"Hello, {guest}!\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "bigger-weekend",
|
|
"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": null,
|
|
"id": "loving-growing",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# range(start, stop, step)\n",
|
|
"range(5) # => [0, 1, 2, 3, 4]"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "organic-coalition",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"list(range(5))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "boxed-offering",
|
|
"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": null,
|
|
"id": "closing-series",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "threaded-maria",
|
|
"metadata": {},
|
|
"source": [
|
|
"</aside>\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": null,
|
|
"id": "painful-newport",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "stuck-silicon",
|
|
"metadata": {},
|
|
"source": [
|
|
"</aside>\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": null,
|
|
"id": "electronic-president",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "caring-fiber",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"But we can do:\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "identical-phrase",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "controlled-frost",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"---\n",
|
|
"## Looping Over a Range\n",
|
|
"\n",
|
|
"Let's make the list all uppercase:\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "smaller-transmission",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "toxic-chase",
|
|
"metadata": {},
|
|
"source": [
|
|
"You can also use the `enumerate` function to loop over both the index and list elements simultaneously."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "automotive-bhutan",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"for i, name in enumerate(guest_list):\n",
|
|
" guest_list[i] = name.upper()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "compound-training",
|
|
"metadata": {},
|
|
"source": [
|
|
"</aside>\n",
|
|
"\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"## Knowledge Check: Which of the following lines is correct?\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "duplicate-brooklyn",
|
|
"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": "italic-priority",
|
|
"metadata": {},
|
|
"source": [
|
|
"---\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": null,
|
|
"id": "upper-headset",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "civic-default",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"## Quick Review: For Loops and Range\n",
|
|
"\n",
|
|
"\n",
|
|
"`for` loops:\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "processed-seventh",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "egyptian-viking",
|
|
"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",
|
|
"## While Loop Syntax\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "patient-yorkshire",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# While <something> is true:\n",
|
|
"# Run some code\n",
|
|
"# If you're done, set the <something> to false\n",
|
|
"# Otherwise, repeat.\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "royal-puzzle",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"\n",
|
|
"\n",
|
|
"---\n",
|
|
"\n",
|
|
"## While Loop: Be Careful!\n",
|
|
"\n",
|
|
"\n",
|
|
"Don't *ever* do:\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "immune-reporter",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# a = 0\n",
|
|
"# while a < 10:\n",
|
|
"# print(a)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "every-tokyo",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"And don't ever do:\n",
|
|
"\n"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "identical-server",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# a = 0\n",
|
|
"# while a < 10:\n",
|
|
"# print(a)\n",
|
|
"# a += 1"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "essential-vanilla",
|
|
"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",
|
|
"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:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "other-reward",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"glass = 0\n",
|
|
"glass_capacity = 12"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "hearing-pitch",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"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": null,
|
|
"id": "three-contrast",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "after-portsmouth",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"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": "sustainable-updating",
|
|
"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": "separate-desert",
|
|
"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.\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": "surrounded-grain",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "swiss-basket",
|
|
"metadata": {},
|
|
"source": [
|
|
"Discuss with your partner: Why do we need to make an initial variable before the loop?\n",
|
|
"\n",
|
|
"- One thing to keep in mind is that `input()` returns a string so if the user types `5` it will result in the string `\"5\"`. You cannot compare numbers to strings in Python. To work around this for a number guessing game, set your correct answer variable to be the string of the number (e.g. \"4\" or \"9\") instead of the number itself. This way when you do your loop comparison, you'll be comparing the same types.\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": "worldwide-scope",
|
|
"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!')"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "fabulous-shield",
|
|
"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": null,
|
|
"id": "intense-administration",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "threatened-instrument",
|
|
"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": null,
|
|
"id": "useful-exhaust",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"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": "formed-kingdom",
|
|
"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": null,
|
|
"id": "central-termination",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def my_empty_function():\n",
|
|
" pass\n",
|
|
"\n",
|
|
"my_empty_function()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "committed-lewis",
|
|
"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": null,
|
|
"id": "comic-margin",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"def my_empty_function():\n",
|
|
" raise NotImplementedError\n",
|
|
" \n",
|
|
"my_empty_function()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "determined-bloom",
|
|
"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)\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.7.6"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|