x is: 1
x is: 2
x is: 3
x is: 4
Week 6: Iteration
Reading: Think Python Chapter 6
Notes
The while
Loop
We have used if
statements to execute a block of code once if a condition is met.
The while
loop extends this functionality and executes a block of code multiple times based on a condition being met.
The syntax is similar: the keyword while
, followed by a condition, followed by a colon.
Unlike the if
statement, which executes code once and then moves on, the while
loop continues to execute as long as the condition is met:
- The conditional expression is evaluated. If
True
, the controlled block runs. - After the block finishes running, the conditional expression is evaluated again.
This makes it very important to change something about the conditional expression during the loop. In the example above, x
is increased, and the condition is checking if x
is less than some value. By increasing x
, we guarantee that the loop will eventually end.
This loop will run “forever:”
In practice, infinite loops will usually get stopped by your computer, or you will run out of memory, or get some other kind of error. You may need to manually terminate the loop, either by pressing Control+C or clicking a red “stop” button in your editor.
Because we subtract from x
each iteration, x
will always be less than 4.
Loops make performing some operation over a large number of values very simple. We could sum integers from 0 through 10:
infinite_loop.py
To perform the same computation on integers from 0 to one million, just change last_value
to 1000000
.
Shortcuts
Python includes a few shortcuts that make our lives easier when performing common tasks. They’re optional, but useful.
- The
+=
operator simultaneously adds and assignsx = x + 1
can be rewrittenx += 1
- There are also
-=
,*=
, and\=
operators - Underscores can be used in numbers to keep track of large values
1_000_000
is the same as1000000
, but it’s easier for humans to read1,000,000
means something in Python, but it does not mean “one million”- Don’t worry about it for now
- You can type something like
23_45
(the same as2345
), but that might be harder to read, not easier
Here’s the simple loop rewritten with +=
:
All of these shortcuts work with numbers; the +=
shortcut will work with strings as well.
= 'idea' k
+= 's' k
print(k)
ideas
The for
Loop
Basic while
loop syntax consists of three parts:
- Initializing a new variable to control the loop
- The
while
statement with a condition related to that variable - Something inside the loop that changes the loop-control variable
- This prevents an infinite loop
basic_while.py
There are other ways to use while
loops, but this way is very common.
The case of needing to iterate over an ordered collection of numbers is so common that Python has a specific way to do this: the for
loop. The syntax is very simple:
- The keyword
for
followed by a space - The name of the loop-control variable
- The keyword
in
- The
range
function, which creates a sequence
A sequence?
for i in range(5):
range(n)
creates the sequence \(0, 1, 2 ,..., n-1\)- Think of the sequence as starting at 0 and stopping before the argument
range(5)
creates sequence0, 1, 2, 3, 4
- The
for
loop iterates through the sequence- The loop-control variable takes each value in the sequence
- The controlled block executes once for each value in the sequence
Trace through this for
loop. It does the exact same thing as the while
loop we just saw:
The range
collection does not need to start at 0. If you pass two arguments to range
, the first argument is the starting value, and the second is the stop-before value.
range(2, 6)
starts at 2 and stops before 6- Yields the sequence
2, 3, 4, 5
- Yields the sequence
range(-2, 4)
starts at -2 and stops before 4- Yields the sequence
-2, -1, 0, 1, 2, 3
- Yields the sequence
range(0, 5)
is the same asrange(5)
- With one argument, starting at 0 is implied
If you pass three arguments to range
, the first is the starting value, the second is the stop-before value, the third is the spacing:
range(1, 6, 2)
starts at 1, stops before 6, and has a spacing of 2- Yields the sequence
1, 3, 5
- Yields the sequence
range(10, 5, -1)
starts at 10, stops before 5 and has a spacing of -1- It will go down, not up
- Yields the sequence
10, 9, 8, 7, 6
range(0, 5, 1)
is the same asrange(5)
- With one argument, starting at 0 and incrementing by 1 are implied
Choosing while
vs. for
for
loops are simpler to write- Anything that can be done with a
for
loop can be done with a while loop- The reverse of this is not true
- If the sequence you are looping through is fixed and regular, use a
for
loop - If not, use a
while
loop
Printing
The print
function can take multiple arguments to perform more ‘advanced’ printing. Print statements are very useful for writing and debugging loops.
- When given multiple positional arguments, the arguments are each printed on one line, separated by spaces
= 2 x
print("x is", 2, "!")
x is 2 !
The arguments can be any type (they do not need to be converted to strings).
By default, at the end of a print
statement, the output advances to the next line. This “end” behavior can be overridden with a keyword argument, end=
.
This example combines many of these concepts:
running_sum.py
Nesting
Just like conditionals, loops can be nested within each other:
Practice
Practice Problem 6.1
Practice Problem 6.2
Practice Problem 6.3
Practice Problem 6.4
Homework
Homework problems should always be your individual work. Please review the collaboration policy and ask the course staff if you have questions.
Double check your file names and printed output. These need to be exact matches for you to get credit.