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.

while_loop.py
x = 0
while x < 4:
    x = x + 1
    print("x is: " + str(x))
x is: 1
x is: 2
x is: 3
x is: 4

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:”

infinite_loop.py
x = 0
while x < 4:
    x = x - 1
    print("x is: " + str(x))

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
cumulative_sum = 0
x = 0
last_value = 10
while x <= last_value:
    cumulative_sum = cumulative_sum + x
    x = x + 1

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 assigns
    • x = x + 1 can be rewritten x += 1
  • There are also -=, *=, and \= operators
  • Underscores can be used in numbers to keep track of large values
    • 1_000_000 is the same as 1000000, but it’s easier for humans to read
    • 1,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 as 2345), but that might be harder to read, not easier

Here’s the simple loop rewritten with +=:

plus_equals_loop.py
x = 0
while x < 4:
    x += 1
    print("x is: " + str(x))

All of these shortcuts work with numbers; the += shortcut will work with strings as well.

k = 'idea'
k += 's'
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
i = 0           # initialize the loop-control variable
while i < 5:    # the `while` statement
    i += 1      # changing the loop control variable
    print(i)    # do something with the loop!

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 sequence 0, 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:

basic_for.py
for i in range(5): 
    print(i)

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
  • range(-2, 4) starts at -2 and stops before 4
    • Yields the sequence -2, -1, 0, 1, 2, 3
  • range(0, 5) is the same as range(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
  • 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 as range(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
x = 2
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=.

keyword_argument.py
print("Hello", end="")
print(" world!")
Hello world!

This example combines many of these concepts:

running_sum.py
running_sum = 0
for val in range(4): 
    running_sum += val
    print("iteration ", end="")
    print(val + 1, end=" - ")
    print("running sum is:", running_sum)

Nesting

Just like conditionals, loops can be nested within each other:

Practice

Practice Problem 6.1

Practice Problem 6.1

Write a program that uses a while loop to sum the integers between 1 and 20 (including 1 and 20).

(You should get 210 as the result).

After you have it working, rewrite the program to use a for loop instead.

Practice Problem 6.2

Practice Problem 6.2

Write a function sum_below that takes an integer argument and returns the sum of all integers between 1 and the argument, not including the argument.

  • sum_below(20) would return 190
  • sum_below(15) would return 105

You can assume the argument will always be a positive integer.

Practice Problem 6.3

Practice Problem 6.3

Write a function sum_skip that takes two integer arguments. Your function should sum all integers less (but including) than the first argument, skipping the second argument.

  • sum_skip(5, 4) would return 11 (\(1 + 2 + 3 + 5\), because 4 was skipped)
  • sum_skip(6, 3) would return 18 (\(1 + 2 + 4 + 5 + 6\), because 3 was skipped)
  • sum_skip(4, 6) would return 10 (\(1 + 2 + 3 + 4\), nothing is skipped because 6 is not part of the sum)

You can assume the argument will always be a positive integer.

Note: There is an “easy” way to solve this, by subtracting the second argument from the sum. Try solving this problem a different way.

Practice Problem 6.4

Practice Problem 6.4

Write a function round_three that takes an argument, a number, and rounds up to the nearest multiple of three, returning that value.

  • round_three(4.2) returns 6
  • round_three(3) returns 3
  • round_three(-2) returns 0

Hint: You can check if a number is divisible by three by using the % operator: if x % y is equal to zero, x is evenly divisible by y.

6 % 3 == 0
True
5 % 3 == 0
False

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.

Homework Problem 6.1

Homework Problem 6.1 (30 pts)

Write a function sequence_skip that takes two arguments, both integers.

  • The function should return a string that consists of every integer less than the first argument
    • These should be in sequential order, increasing by one
    • Exclude the second argument.
    • There should be a space between each integer (but no leading or trailing spaces).
  • sequence_skip(5, 2) returns string '0 1 3 4'
  • sequence_skip(4, 3) returns string '0 1 2'
  • sequence_skip(6, 1) returns string '0 2 3 4 5'

Submit as sequence_skip.py.

Homework Problem 6.2

Homework Problem 6.2 (35 pts)

Write a function sequence_string that takes one argument, an integer, and returns a string.

  • The string should consist of integers in sequential order, increasing by one,
    • These integers start with the argument
    • These integers end with the next multiple of five (inclusive).
  • sequence_string(2) returns string '2 3 4 5'
  • sequence_string(7) returns string '7 8 9 10'
  • sequence_string(15) returns string '15'

Submit as sequence_string.py

Homework Problem 6.3

Homework Problem 6.3 (35 pts)

Write a function greatest_factor that takes one argument, an integer, and returns the largest integer, smaller than the argument, that the argument divides into evenly. (The return value does not need to be prime.) The argument will always be greater than one.

  • greatest_factor(9) returns integer 3
  • greatest_factor(20) returns integer 10
  • greatest_factor(24) returns integer 12

Submit as greatest_factor.py