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.

593 lines
34 KiB

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="../../../lib/css/zenburn.css">
<link rel="stylesheet" href="../../../lib/css/prism.css">
<link rel="stylesheet" href="../../../css/reveal.css">
<link rel="stylesheet" href="../../../css/theme/ga-title.css" id="theme">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="c../../../ss/print/' +
( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) +
'.css" type="text/css" media="print">' );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
<link rel="stylesheet" type="text/css" href="https://nagale.com/proxima-nova/fonts.css" />
</head>
<body class="language-python">
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section id="section" class="level2 separator">
<h2></h2>
<h3 class="underscore">
Python Programming
</h3>
<hr class="underscore" />
<h2>
Loops
</h2>
<p><img src="https://i.imgur.com/VgHiXgy.png" class="full" /></p>
<hr />
</section>
<section id="discussion-a-small-list" class="level2">
<h2>Discussion: A Small list</h2>
<p>This situation isnt so bad…</p>
<pre><code> visible_colors = [&quot;red&quot;, &quot;orange&quot;, &quot;yellow&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;violet&quot;]
print(visible_colors[0])
print(visible_colors[1])
print(visible_colors[2])
print(visible_colors[3])
print(visible_colors[4])
print(visible_colors[5])</code></pre>
<p>But, what would we do if there were 1,000 items in the list to print?</p>
<aside class="notes">
<p>TEACHING TIPS: Try to get students to guess at the idea of putting the print statement in a loop.</p>
TALKING POINTS: What if we had a list with 283,000 items in it? We cant write one line for each element. We need a way to write the print statement once and have it run for every element in the list. One of the most powerful things that programming can do for you is automatically perform repetitive tasks. In the tiny scripts weve been writing, printing out every variable has not been much of an issue. But with lists in the game, things can get a bit more challenging. We need a way to automate some tasks so that they repeat for every item in a list.
</aside>
<hr />
</section>
<section id="the-for-loop" class="level2 separator-subhead">
<h2>The “For” Loop</h2>
<hr />
</section>
<section id="the-for-loop-1" class="level2">
<h2>The <code>for</code> Loop</h2>
<p>The <code>for</code> loop always follows this form:</p>
<pre><code>for item in collection:
# Do something with item</code></pre>
<p>For example:</p>
<pre><code>visible_colors = [&quot;red&quot;, &quot;orange&quot;, &quot;yellow&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;violet&quot;]
for each_color in visible_colors:
print(each_color)</code></pre>
<aside class="notes">
TEACHING TIPS: Go over the syntax. Point out the indentation; specifically, point out that its like the if statement they learned. TALKING POINTS: We need what is called a Loop. 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. This code: Prints each element in the list. Begins the for loop. We loop once for each “color” in the list (visible_colors). Prints the current color inside the loop. 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. Python will start with the first item and automatically stop after it loops with the last item.
</aside>
<hr />
</section>
<section id="knowledge-check-what-will-this-code-do" class="level2">
<h2>Knowledge Check: What Will This Code Do?</h2>
<p>Think about what the code will do before you actually run it.</p>
<iframe height="400px" width="100%" src="https://repl.it/@SuperTernary/python-programming-for-indents?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">
</iframe>
<aside class="notes">
The statements inside a loop that you want to repeat must be indented like the statements inside an if block. If you have three lines of code that you want to execute on each loop iteration, each must be indented one level underneath your for line. Each name is met with “THUNDEROUS APPLAUSE!” because that line, and the two above it, are indented to be in the body of the for loop.
</aside>
<hr />
</section>
<section id="writing-a-loop" class="level2">
<h2>Writing a Loop</h2>
<p>Lets write a loop to print names of guests.</p>
<p>First, we need a list.</p>
<ul>
<li>Create a local <code>.py</code> file named <code>my_loop.py</code>.</li>
<li>Make your list: Declare a variable <code>my_list</code> and assign it to a list containing the names of at least five people.</li>
</ul>
<aside class="notes">
Do this with them! Make sure theyre typing with you, to practice. See if they can give you the syntax you should write. The code is: <code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]</code>
</aside>
<hr />
</section>
<section id="write-a-loop-make-the-loop" class="level2">
<h2>Write a Loop — Make the Loop</h2>
<p>Now well add the loop.</p>
<ul>
<li>Skip a line and write the first line of your for loop.
<ul>
<li>For the variable that holds each item, give it a name that reflects what the item is (e.g., name of person).</li>
</ul></li>
<li>Inside your loop, add the code to print “Hello,” plus the name.</li>
</ul>
<pre><code>&quot;Hello, Felicia!&quot;
&quot;Hello, Srinivas!&quot;</code></pre>
<aside class="notes">
TEACHING TIPS: Do this with the class! Make sure theyre typing with you, to practice. See if they can give you the syntax you should write. TALKING POINTS: Remind them that the word collection is a list; this collection is the list variable they have. The code is: <code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;] for guest in guest_list: # Print out a greeting in here print(&quot;Hello, &quot; + guest + &quot;!&quot;)</code>
</aside>
<hr />
</section>
<section id="write-a-loop-greeting-your-guest-list" class="level2">
<h2>Write a Loop Greeting Your Guest List</h2>
<p>Our guests are definitely VIPs! Lets give them a lavish two-line greeting.</p>
<ul>
<li>Inside your loop, add the code to print another sentence of greeting:</li>
</ul>
<pre><code>&quot;Hello, Srinivas!&quot;
&quot;Welcome to the party!&quot;</code></pre>
<aside class="notes">
TEACHING TIPS: Do this with them! Make sure theyre typing with you to practice. See if they can give you the syntax you should write. Point out the indent. TALKING POINTS: Fantastic! Now each guest is greeted by their name and welcomed to the party. Those two print() lines are executed on every iteration because both are indented to be in the for loops code block. Think of the indented block as a unit of instructions executed as a group each time the loop runs. The code is: <code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;] for guest in guest_list: # Print out a greeting in here print(&quot;Hello,&quot;, guest, &quot;!&quot;) print(&quot;Welcome to the party!&quot;)</code>
</aside>
<hr />
</section>
<section id="where-else-could-we-use-a-loop" class="level2">
<h2>Where Else Could We Use a Loop?</h2>
<p>A loop prints everything in a collection of items.</p>
<ul>
<li><code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]</code></li>
</ul>
<p>What, besides a list, could we use a loop on? <strong>Hint</strong>: There are six on this slide!</p>
<aside class="notes">
The answer is a string! We can loop through the characters.
</aside>
<hr />
</section>
<section id="looping-strings" class="level2">
<h2>Looping Strings</h2>
<p>Loops are collections of strings and numbers.</p>
<p>Strings are collections of characters!</p>
<iframe height="400px" width="100%" src="https://repl.it/@SuperTernary/python-programming-string-for?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">
</iframe>
<aside class="notes">
TEACHING TIPS: Dont spend more than a minute or two on this slide; its not an exercise, just a demonstration. The point is to understand that a string is a collection of characters, and any collection can be looped. TALKING POINTS: You may not realize it, but a string is a collection of characters (which are also of type “str,” by the way). Just so you can see that a for loop has the same syntax for any collection, lets add the following code below what weve just written.
</aside>
<hr />
</section>
<section id="what-about-looping-for-a-specific-number-of-iterations" class="level2">
<h2>What About… Looping for a Specific Number of Iterations?</h2>
<p>We have:</p>
<pre><code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]
for guest in guest_list:
print(&quot;Hello, &quot; + guest + &quot;!&quot;)</code></pre>
<p>The loop runs for every item in the list — the length of the collection. Here, it runs six times.</p>
<p>What if we dont know how long guest_list will be?</p>
<p>Or only want to loop some of it?</p>
<aside class="notes">
Whenever we have a collection, such as a list or string, and we want to iterate over each item it contains, we should use a for loop. Python has internal logic for determining exactly how many times the loop should run, based on the length of the collection. What if we want to do something in a loop a specific number of times, but we dont have a collection to start with? Maybe we are initializing a new collection and we need to add a specific number of items to it, or maybe we just want something to run exactly 15 times. In this case, we can have the for loop iterate over a range of numbers.
</aside>
<hr />
</section>
<section id="range" class="level2 separator-subhead">
<h2>Range()</h2>
<hr />
</section>
<section id="enter-range" class="level2">
<h2>Enter: Range</h2>
<p>range(x):</p>
<ul>
<li>Automatically generated.</li>
<li>A list that contains only integers.</li>
<li>Starts at zero.</li>
<li>Stops before the number you input.</li>
</ul>
<p><code>range(5) # =&gt; [0, 1, 2, 3, 4]</code></p>
<aside class="notes">
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. Lets use this in a loop…
</aside>
<hr />
</section>
<section id="looping-over-a-range" class="level2">
<h2>Looping Over a Range</h2>
<p>Lets look at range() in action:</p>
<iframe height="400px" width="100%" src="https://repl.it/@SuperTernary/python-programming-string-for?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">
</iframe>
<aside class="notes">
TEACHING TIPS: This isnt an exercise, just a quick demo. Make sure they understand how range works. TALKING POINTS: We can see that this code prints each of the numbers in our range of 0 through 9 (10 numbers total). We dont need to have our loop print anything. This loop could be used to execute any sequence of code 10 times.
</aside>
<hr />
</section>
<section id="looping-over-a-range-1" class="level2">
<h2>Looping Over a Range</h2>
<p>Looping over names here is really just going through the loop four times: At index <code>0, 1, 2</code>, and <code>3</code>. We can instead use <code>range()</code> to track the index and loop names: <code>range(4)</code> is <code>[0, 1, 2, 3]</code>. We can then use <code>len(names)</code>, which is 4, as our range.</p>
<iframe height="400px" width="100%" src="https://repl.it/@SuperTernary/python-programming-range-loop?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">
</iframe>
<aside class="notes">
TEACHING TIPS: This isnt an exercise, just a demo. Make sure they understand how range works. This can be a bit tricky! Show a regular loop again, if you need to. Vary the size of range (try range(4) and range(2)) so students can see the differences. Give a bunch of examples. Range might make sense conceptually, but its hard to remember (and use) its syntax. TALKING POINTS: Recall that you can use the len() function to get the length of a list. Because that will always be an integer, we can feed that value into the range() function to generate a range that contains each index in the list. Dont be alarmed about the function inside the function. Thats fairly common. Lets break it down: len(names) will return the length of the names list; in this case, 4. The number 4 is then used as the parameter for range(), creating a range containing 0, 1, 2, and 3. These happen to all be valid indices for our list, so we can use them to modify the values stored at those indices.
</aside>
<hr />
</section>
<section id="using-range-to-modify-collections" class="level2">
<h2>Using <code>range()</code> to Modify Collections</h2>
<p>Why would you use <code>range()</code> on a list, when you could just loop the list?</p>
<p>We cant do:</p>
<pre><code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]
for guest in guest_list:
guest = &quot;A new name&quot;</code></pre>
<p>But we can do:</p>
<pre><code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]
for guest in range(len(guest_list)):
guest_list[guest] = &quot;A new name&quot;</code></pre>
<aside class="notes">
TALKING POINTS: But there is one special use for this that is vital to know about: When we loop using for item in collection, we cant ever really modify the elements in the list. Whenever we access item, we are actually getting a copy of the item in the list. In order to modify the item in the list, we would need the index of that item in the list. And guess what range() gives us… We can also use enumerate() here (if you want to cover that with students).
</aside>
<hr />
</section>
<section id="looping-over-a-range-2" class="level2">
<h2>Looping Over a Range</h2>
<p>Lets make this list all uppercase:</p>
<iframe height="400px" width="100%" src="https://repl.it/@SuperTernary/python-programming-range-modification?lite=true" scrolling="no" frameborder="no" allowtransparency="true" allowfullscreen="true" sandbox="allow-forms allow-pointer-lock allow-popups allow-same-origin allow-scripts allow-modals">
</iframe>
<aside class="notes">
<p>TEACHING TIPS: This is a bit difficult. Make sure they understand that a range hits the index, versus a regular for loop, which makes a copy. Give different examples if need be. TALKING POINTS: When we run this, we see that the names list has had all the string changed to uppercase. It is necessary to use list indices if you want to modify list elements. If we tried doing the same thing with an item from that list, then the changes would only apply to the temporary copy stored in item and would never actually make it into the list.</p>
<p>Note you can also use enumerate:</p>
<code>guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;] for guest in enumerate(guest_list): guest_list[guest[0]] = guest_list[guest[0]].upper() print(guest_list)</code>
</aside>
<hr />
</section>
<section id="knowledge-check" class="level2">
<h2>Knowledge Check</h2>
<p><code>my_list = ['mon', 'tue', 'wed', 'thu', 'fri']</code></p>
<p>Which of the following lines is correct?</p>
<pre><code>for day in range(my_list): # answer A
for day in range(len(my_list)): # answer B
for day in range(my_list.length): # answer C</code></pre>
<aside class="notes">
TEACHING TIPS: Give the class time to discuss and come up with an answer! The answer is B.
</aside>
<hr />
</section>
<section id="solo-exercise-range-510-minutes" class="level2">
<h2>Solo Exercise: Range() (510 minutes)</h2>
<p>Locally, create a new file called <code>range_practice.py</code>.</p>
<p>In it:</p>
<ul>
<li>Create a list of colors.</li>
<li>Using a <code>for</code> loop, print out the list.</li>
<li>Using <code>range()</code>, set each item in the list to be the number of characters in the list.</li>
<li>For example:</li>
</ul>
<pre><code>[&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]
# =&gt;
[3, 5, 4]</code></pre>
<aside class="notes">
<ul>
<li>If students seem a bit lost when you get here, run this as a partner exercise.
<ul>
<li>This is tough! Give them a bit before going over the answer. Bring up your own file or a repl.it and write it, talking through each step.</li>
</ul></li>
</ul>
</aside>
<hr />
</section>
<section id="quick-review-for-loops-and-range" class="level2">
<h2>Quick Review: <code>for</code> Loops and Range</h2>
<p><code>for</code> Loops</p>
<pre><code># On a list (a collection of strings) guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]
for guest in guest_list:
print(&quot;Hello, &quot; + guest + &quot;!&quot;)
# On a string (a collection of characters)
my_string = &quot;Hello, world!&quot;
for character in my_string:
print(character)
##### Range #####
range(4) # =&gt; [0, 1, 2, 3]
# Using Range as an Index Counter
names = [&quot;Flint&quot;, &quot;John Cho&quot;, &quot;Billy Bones&quot;, &quot;Nanda Yuna&quot;]
for each_name in range(4):
print(names[each_name])</code></pre>
<hr />
</section>
<section id="quick-review-for-loops-and-range-1" class="level2">
<h2>Quick Review: <code>for</code> Loops and Range</h2>
<pre><code># OR
for each_name in range(len(names)):
print(names[each_name])
# Using Range to Change a List:
guest_list = [&quot;Fred&quot;, &quot;Cho&quot;, &quot;Brandi&quot;, &quot;Yuna&quot;, &quot;Nanda&quot;, &quot;Denise&quot;]
for guest in range(len(guest_list)):
guest_list[guest] = &quot;A new name&quot;</code></pre>
<aside class="notes">
Quickly review key takeaways. Ask if there are questions. That was a lot to cover!
</aside>
<hr />
</section>
<section id="the-while-loop" class="level2 separator-subhead">
<h2>The “While” Loop</h2>
<hr />
</section>
<section id="the-while-loop-1" class="level2">
<h2>The <code>while</code> Loop</h2>
<p>What about “While the bread isnt brown, keep cooking”? Python provides two loop types.</p>
<p><code>for</code>:</p>
<ul>
<li>You just learned!</li>
<li>Loops over collections a finite number of times.</li>
</ul>
<p><code>while</code>:</p>
<ul>
<li>Youre about to learn!</li>
<li>When your loop could run an indeterminate number of times.</li>
<li>Checks if something is <code>True</code> <em>(the bread isnt brown yet)</em> and runs until its set to <code>False</code> <em>(now the bread is brown, so stop)</em>.</li>
</ul>
<aside class="notes">
Now that weve learned how to write for loops to iterate lists and how to use range to dynamically generate loops, were going to transition to while loops. Im going to show you how to write while loops, and then youre going to practice while loops with your partner.
</aside>
<hr />
</section>
<section id="while-loop-syntax" class="level2">
<h2><code>while</code> Loop Syntax</h2>
<pre><code># While &lt;something&gt; is True:
# Run some code.
# If you&#39;re done, set the &lt;something&gt; to False.
# Otherwise, repeat.
a = 0
while a &lt; 10:
print(a)
a += 1</code></pre>
<aside class="notes">
Call out that it wont print 10. Call out the indents!
</aside>
<hr />
</section>
<section id="while-loop-syntax-1" class="level2">
<h2><code>while</code> Loop Syntax</h2>
<p><img src="https://imgur.com/JXI7Rcr.png" /></p>
<aside class="notes">
We wont always have the luxury of a collection of discrete data items for controlling our loop. Frequently, we will need to write a loop that will run an unknown number of times. This is what the while loop is for. Its another loop construct that will continue to iterate while a given condition is True. These loops are quite useful for data sets of unknown sizes, or for when we need to loop until some value changes. Outside of our while loop, we create the variable “a,” which well use as our conditional. We then start our loop. We say to loop “while a is less than 10.” Then, in the loop, we print a and add one to its value. Once the value of a reaches 10, the loop condition evaluates to False and the loop finishes.
</aside>
<hr />
</section>
<section id="while-be-careful" class="level2">
<h2><code>while</code>: Be Careful!</h2>
<p>Dont <em>ever</em> do:</p>
<pre><code>a = 0
while a &lt; 10:
print(a)</code></pre>
<p>And dont <em>ever</em> do:</p>
<pre><code>a = 0
while a &lt; 10:
print(a)
a += 1</code></pre>
<p>Your program will run forever! If your program ever doesnt leave a loop, hit <code>control-c</code> (break).</p>
<aside class="notes">
TEACHING TIPS: Were telling them this in advance of practicing, in case they do it! Make it clear why this runs forever. TALKING POINTS: While loops present a potential “gotcha” in programming: the infinite loop. Because the while loop only terminates when a condition turns to False, its possible to write the loop in such a way that it never terminates. This creates a serious bug in your code where the loop never, ever returns control to the app, and it will freeze indefinitely. The way to avoid this is to always remember to update your conditional variable inside your loop block.
</aside>
<hr />
</section>
<section id="filling-a-glass-of-water" class="level2">
<h2>Filling a Glass of Water</h2>
<p>Create a new local file, <code>practicing_while.py</code>.</p>
<p>In it, well create:</p>
<ul>
<li>A variable for our current glass content.</li>
<li>Another variable for the total capacity of the glass.</li>
</ul>
<p>Lets start with this:</p>
<pre><code>glass = 0
glass_capacity = 12</code></pre>
<p>Can you start the <code>while</code> loop?</p>
<aside class="notes">
TEACHING TIPS: Make sure students are typing this with you and not just copying and pasting the code. Before you go to the next slide (adding the loop), see if they can guess the syntax. TALKING POINTS: Can you think of the mental process you follow when pouring water into a glass? You start with an empty glass and begin adding water to it, right? While you are adding the water, you must constantly check to see if the glass has reached its maximum capacity. If it has, you then stop pouring. Otherwise, you continue adding water. Lets see how that would work as a while loop… We need a variable for our current glass content and we need one for the total capacity of the glass. What we want to do is add water to the glass one unit at a time until the glass reaches capacity. Said another way: While the glass contains less than its capacity, add another unit of water. Can you start the loop code before we move to the next slide?
</aside>
<hr />
</section>
<section id="filling-a-glass-of-water-1" class="level2">
<h2>Filling a Glass of Water</h2>
<p>Add the loop:</p>
<pre><code>glass = 0
glass_capacity = 12
while glass &lt; glass_capacity:
glass += 1 # Here is where we add more water.</code></pre>
<p>Thats it!</p>
<aside class="notes">
TALKING POINTS: We declare our glass variable and set it to 0 water, currently. Then, we declare our glass capacity and set it to 12 units. Next, we set up our while loop. We want to loop while the glass has a value less than glass_capacity. Inside of our loop, we add 1 unit of water to our glass. Each time the loop runs, it checks the value of glass to see if it has reached the same value as glass_capacity. The loop stops once glass reaches 12, conveniently before we spill.
</aside>
<hr />
</section>
<section id="side-note-input" class="level2">
<h2>Side Note: <code>input()</code></h2>
<p>Lets do something more fun. With a partner, you will write a program that</p>
<ul>
<li>Has a user guess a number.</li>
<li>But first, how do we have users input numbers? Using <code>input()</code>.</li>
</ul>
<pre><code>user_name = input(&quot;Please enter your name:&quot;)
# user_name now has what the user typed.
print(user_name)</code></pre>
<p>Erase the code in your <code>practicing_while.py</code> file and replace it with the above code. Run it! What happens? Does it work?</p>
<aside class="notes">
TEACHING TIPS: Dont put learners into partner pairs yet; make sure they all have input working on their own. Demo that the text in the input prompt can be anything, and the variable user_name can be named anything. There is a lesson teaching input in depth (in Unit 5), so you just need them to be able to use the code. Put any further questions into the parking lot. TALKING POINTS: While loops are also great for guessing games. Lets use a small function called input() to get some user input so that they can take guesses about our secret number. Heres how input() works. Whatever string you put in the parentheses is printed to the screen. The user then has the opportunity to type something. The script will wait patiently for the user until something is typed and entered (a perfect example of a while loop in the Python internals). When the user hits enter, the string they typed is stored in the variable user_name above.
</aside>
<hr />
</section>
<section id="a-guessing-game-5-minutes" class="level2">
<h2>A Guessing Game (5 minutes)</h2>
<p>Now, get with a partner! Lets write the game.</p>
<p>Decide who will be the driver and who will be the navigator. Add this to your existing file.</p>
<ul>
<li>Set a variable, answer to “5” (yes, a string!).</li>
<li>Prompt the user for a guess and save it in a new variable, <code>guess</code>.</li>
<li>Create a <code>while</code> loop, ending when <code>guess</code> is equal to <code>answer</code>.</li>
<li>In the <code>while</code> loop, prompt the user for a new <code>guess</code>.</li>
<li>After the <code>while</code> loop, print: “You did it!”</li>
</ul>
<p>Discuss with your partner: Why do we need to make an initial variable before the loop?</p>
<aside class="notes">
DURATION: 5 minutes TEACHING TIPS: Run this as a partner exercise. Set students up in pairs, then walk around to make sure theyre all working and no one is stuck. TALKING POINTS: Now that you know how to accept input from the keyboard, make a game where the player must correctly guess a number. The game will continually prompt the user to enter a guess if they did not guess correctly. Once they correctly guess the number, the program congratulates them and exits. Can you think of how this would be written? You need a variable to hold the correct answer. You need another variable to hold each subsequent guess. We will need to compare the guess to the answer and, if it is wrong, ask the user again for a guess. This sounds like we will be repeatedly asking for a guess while the previous guess was incorrect. 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, youll be comparing the same types.
</aside>
<hr />
</section>
<section id="a-guessing-game-solution" class="level2">
<h2>A Guessing Game (Solution)</h2>
<pre><code>answer = &quot;4&quot;
guess = input(&quot;Guess what number I&#39;m thinking of (1-10): &quot;)
while guess != answer:
guess = input(&quot;Nope, try again: &quot;)
print(&quot;You got it!&quot;)</code></pre>
<p>Howd you do? Questions?</p>
<aside class="notes">
Walk through the answer here. Show it working. Check for understanding.
</aside>
<hr />
</section>
<section id="conclusion" class="level2 separator-subhead">
<h2>Conclusion</h2>
<hr />
</section>
<section id="python-programming-loops" class="level2 separator-subhead">
<h2>Python Programming: Loops</h2>
<p><strong>Lesson Summary</strong></p>
<p>Today we explored:</p>
<ul>
<li>Loops:
<ul>
<li>Common, powerful control structures that let us efficiently deal with repetitive tasks.</li>
</ul></li>
<li><code>for</code> loops:
<ul>
<li>Used to iterate a set number of times over a collection (e.g., list, string, or using <code>range</code>).</li>
<li><code>range()</code> uses indices, not duplicates, so it lets you modify the collection.</li>
</ul>
<hr /></li>
</ul>
</section>
<section id="python-programming-loops-1" class="level2 separator-subhead">
<h2>Python Programming: Loops</h2>
<p><strong>Lesson Summary</strong></p>
<p>Today we explored:</p>
<ul>
<li><code>while</code> loops:
<ul>
<li>Run until a condition is False.</li>
<li>Used when you dont know how many times you need to iterate. </li>
</ul></li>
</ul>
<p>Up Next: {Add Upcoming Lesson Topics/Pre-Work}</p>
<aside class="notes">
Briefly recap. Check for understanding! Bring up an interpreter if needed, or if you have extra time. The more they see this, the better! Go over next steps. Encourage students to check out all the additional resources at the end of each presentation.
</aside>
<hr />
</section>
<section id="qa" class="level2 separator-subhead">
<h2>Q&amp;A</h2>
<aside class="notes">
Answer any questions learners may have at this point.
</aside>
<hr />
</section>
<section id="additional-resources" class="level2 separator-subhead">
<h2>Additional Resources</h2>
<hr />
</section>
<section id="additional-reading" class="level2">
<h2>Additional Reading</h2>
<p><a href="https://www.youtube.com/watch?v=JkQ0Xeg8LRI">Learn Python Programming: Loops Video</a></p>
<p><a href="https://wiki.python.org/moin/ForLoop">Python: For Loop</a></p>
<p><a href="https://www.tutorialspoint.com/python/python_loops.htm">Python: Loops</a></p>
<aside class="notes">
Encourage students to go through these in their spare time, especially if they need more help.
</aside>
<hr />
</section>
<section id="exit-tickets" class="level2 separator-subhead">
<h2>Exit Tickets</h2>
<aside class="notes">
Dont forget to fill out your exit ticket before you leave!
</aside>
<hr />
</section>
<footer><span class='slide-number'></span></footer>
</div>
<script src="../../../lib/js/head.min.js"></script>
<script src="../../../js/reveal.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: false,
slideNumber: true,
// available themes are in /css/theme
theme: Reveal.getQueryHash().theme || 'default',
// default/cube/page/concave/zoom/linear/fade/none
transition: Reveal.getQueryHash().transition || 'slide',
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: '../../../lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: '../../../plugin/markdown/showdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: '../../../plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: '../../../plugin/prism/prism.js', async: true, callback: function() { /*hljs.initHighlightingOnLoad();*/ } },
{ src: '../../../plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: '../../../plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: 'plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
Reveal.addEventListener('ready', function() {
if (Reveal.getCurrentSlide().classList.contains('separator-subhead')) {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga-subhead.css');
} else if (Reveal.getCurrentSlide().classList.contains('separator')) {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga-title.css')
} else {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga.css');
}
});
Reveal.addEventListener('slidechanged', function(e) {
if (Reveal.getCurrentSlide().classList.contains('separator-subhead')) {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga-subhead.css');
} else if (Reveal.getCurrentSlide().classList.contains('separator')) {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga-title.css')
} else {
document.getElementById('theme').setAttribute('href', '../../../css/theme/ga.css');
}
});
</script>
</body>
</html>