10 Loops
10 Loops
• A loop is a control structure that repeats some lines of code until a certain
condition is met.
• The important word there is: repeats. A loop repeats lines of code.
• Their real power of loop is their ability to repeat code a dynamic number of
times based on some conditions.
• There are two common kinds of loops: for loops and while loops.
FOR LOOPS
• A for loop repeats some code a certain number of times: “for 7 times, do
this.”
• Sometimes, we’ll know exactly how many times a loop should run in advance.
• Other times, the desired number of iterations (i.e., repetitions) might vary.
• Some languages, like Python, supply a special kind of for loop called a foreach
loop.
• for-each loops come from the observation that a large number of times that
we use for loops.
WHILE LOOPS
• for loops run with some advanced knowledge about how many times the
loop will run: “for 7 times, do this.” while loops, on the other hand, run while
something remains true.
• Some languages, like Java, also have a special kind of while loop called a
dowhile loop. We can think of the standard while loop above as a “while-
do” loop: while a condition is true, do something. A do-while loop is
identical, except that it guarantees the “something” will be run at least once: it
does it before checking the condition the first time.
WHILE LOOPS
• Notice also how while loops are heavily dependent on logical expressions,
just like conditionals were.
• Just as we filled a conditional with a logical expression to decide whether
to run its code block, so also we fill a while loop with a logical expression to
decide whether to keep repeating its code block.
• In many ways, you can think of a while loop as a repeated conditional: it
repeats while the condition is true, rather than running once if the condition is
true.
TRADITIONAL FOR LOOPS IN PYTHON
• In practice, the traditional for loop is actually used less in Python than the for-
each loop; however, in computing as a whole, the traditional for loop is
probably more fundamental.
• In fact, technically Python does not even have a traditional for loop: even the
for loops are technically for-each loops.
FOR LOOPS WITH KNOWN RANGES
• This loop control variable we’ll be able to access inside the loop to see how
many times the loop has run so far.
• In our sample code, range(1, 11) means that in this kind of loop, the first time
it runs, the variable (in this case, i) will take the first number specified in
range() as its value (in this case, the 1 in range(1, 11)).
• Then, each time the loop runs, the variable will increase by 1.
• The loop will stop running when the variable equals the second number (in
this case, 11).
FOR LOOPS WITH KNOWN RANGES
• Note that when the variable equals that number, it will not run the loop again;
it runs until the variable equals the second number, not until the variable
exceeds the second number.
• Then, the for loop ends with a colon, Python’s indicator that some indented
code block is coming.
• Then, each line of code indented under the loop statement will be run, in
order, each time the loop runs.
• One interesting (but non-essential) note: if you modify i within the body of the
loop, the modified value will be used for the rest of that iteration of the loop;
however, when that iteration ends, it restores the previous value of i.
• The contents of the loop can control the loop itself.
FOR LOOPS WITH KNOWN RANGES
FOR LOOPS WITH UNKNOWN RANGES
• sdfghj
FOR LOOPS WITH UNKNOWN RANGES
• Why do we have to create it outside the loop? Couldn’t we create it inside like
declaring variables inside our conditionals?
• The reason is that every time the loop runs, we need to set sum equal to the
previous sum plus the new number; if sum didn’t exist before, there is no
previous sum, and so the program crashes because we’re not in sum’s scope
the first time it runs!
FOR LOOPS WITH UNKNOWN RANGES
• asdfg
FOR-EACH LOOPS IN PYTHON
• Python is specifically set up to make dealing with lists of items easier, and since
so many for loops exist to iterate over lists of items, for-each loops are very
common.
• A for-each loop runs the same way as a for loop, but it streamlines the
process of creating a variable, getting the length of the list, and grabbing the
next item during each iteration.
FOR-EACH AND LISTS
• The computer infers from the context what it should do, like when it inferred
from the data types we were using how to use addition and multiplication
operators.
• Just like i took on each number in a range in a for loop, currentNumber is
given each value in sequence from the list.
FOR-EACH AND OTHER TYPES
• Lists, tuples, and dictionaries are all data types that in some way implement a
list-like structure.
• Another one, however, you’ve already seen: strings. Strings are, effectively,
ordered lists of individual characters. So, we can use a for-each loop with a
string as well.
FOR-EACH AND OTHER TYPES
• Notice that technically, characters and strings aren’t different data types in
Python. They are in many other languages, but in Python, a character is just a
string with a length of 1.
• Notice the nested structures. The conditional on line 7 is inside, or controlled
by, the for loop on line 5, so it’s indented under the for loop.
• Line 8, which increments numSpaces, is controlled by both the for loop (it
could repeat for each character) and the conditional, so it’s indented under
both (and doubleindented as a result).
FOR-EACH AND OTHER TYPES
• Notice that this code doesn’t really work the way it’s intended to.
• It works when we have predictable strings, but it would generate a lot of
wrong results.
• If a string had back-to-back spaces, it would assume there was a word between
them even if there wasn’t.
• If a string had back-to-back spaces, it would assume there was a word between
them even if there wasn’t.
WHILE LOOPS IN PYTHON
• We then write the logical expression that will control the loop.
• Notice this is just like an if statement: in many ways, a while loop is an if
statement that repeats until the condition is False instead of just running
once if it was True.
• As before, we end with a colon to mark off the code block the loop will
control.
• Notice that we increment i after we print it.
SIMPLE WHILE LOOPS
• Notice how similar this is to our for loops. With for loop, we noted that
when the code jumps back to the top, it increments i or whatever variable we
use to control the loop. Here, we increment i manually.
• So, anything a for loop can do, a while loop can do, too.
• A for loop—especially a for-each loop in Python—is just a little more
efficient to write and often more natural to think about.
FOR LOOPS AND NUMBER GUESSING
• zxc
FOR LOOPS AND NUMBER GUESSING
• We start with import random on line 1 just so we can get random numbers.
• Then on line 3, we create a random number from 1 to 100 using
random.randint(1, 100).
• The while loop repeats as long as the user’s guess is not correct.
• At the end of the loop’s contents, userGuess is whatever number the user
entered.
• Then, it checks userGuess to see if it’s equal to hiddenNumber. If it is equal,
then this statement is False because of the not in front, and so if it is equal, the
loop will not repeat. If it’s not equal, the loop repeats again.
INFINITE LOOPS