Iteration Exercises

Harold Nelson

1/28/2020

Exercise 1

What does the following python program print?

i = 0
while i < 5:
    i = i + 1
    print(i)

Solution

i = 0
while i < 5:
    i = i + 1
    print(i)
## 1
## 2
## 3
## 4
## 5

Exercise 2

Think of this code as one of a number of variations on a theme.

  1. The loop variable i could be initialized at either the first value we want or one before that value.

  2. The < could have been <=

  3. The change in the loop variabe could have been the last statement in the loop instead of the first.

There are 3 choices, each with 2 possibilities. How many variations are there?

Solution

\[2^3=8\]

Exercise

Copy the code above to a Jupyter notebook and try the variations. After you write one, try to predict what the code will do, then run it. Five minutes.

Solution

Here’s an example with all of the opposite choices made.

i = 1
while i <= 5:
    print(i)
    i = i + 1
## 1
## 2
## 3
## 4
## 5

Comment

Indefinite loops are error-prone. I only use them when I can’t define ahead of time what values the loop variable should take on. One example of an appropriate usage is when prompting a user for input and checking the user’s response for correctness.

range()

The range() function can be the object of iteration. Note that it may not produce exactly what you expected.

for i in range(5):
    print(i)
        
## 0
## 1
## 2
## 3
## 4

Break

What does the following program print?

for i in range(5):
    j = i**2
    if i == 3:
        break
    print(i,j)

Solution

for i in range(5):
    j = i**2
    if i == 3:
        break
    print(i,j)
        
    
## 0 0
## 1 1
## 2 4

continue

What does the following program print?

for i in range(5):
    j = i**2
    if i == 3:
        continue
    print(i,j)

Solution

for i in range(5):
    j = i**2
    if i == 3:
        continue
    print(i,j)
        
    
## 0 0
## 1 1
## 2 4
## 4 16

Exercise

Prompt a user to provide an integer. If the user gives an inappropriate response, give the use another chance. There is no limit to the possible number of chances.

Solution

while True:
    n_str = input("Give me an integer")
    try:
        n_int = int(n_str)
        break
    except:
        print("Try again for an integer")
print("Success: Your integer is", n_int)      

Be sure to run this in Cocalc

Crash Course: Lists

A list consists of multiple python objects, separated by commas and enclosed in square brackets.

The in operator can be used to test for the presence of a particular value in the list.

The members of the list can be referenced by indexing, where the first value has an index of 0.

You can iterate over the objects in the list.

Examples

li = ["Tom", "Dick", 3]
print(li[0])
## Tom
for i in li:
    print(i)
## Tom
## Dick
## 3

Exercise

Create a function avg_the_list(nl). The parameter nl is a list in which all of the members are numbers. The function is fruitful and it returns the average value of the numbers in the list.

Test your function using tl = [1,2,3,4]

Solution

def avg_the_list(nl):
    sum = 0
    n = 0
    for i in nl:
        sum = sum + i
        n = n + 1
    avg = sum/n
    return avg
tl = [1,2,3,4]    
print(avg_the_list(tl))    
## 2.5

Exercise

Create a function avg_the_odds(nl) by modifying the previous function so that returns the average value of the odd integers in the list. Again, test it using tl = [1,2,3,4].

Solution

def avg_the_odds(nl):
    sum = 0
    n = 0
    for i in nl:
        if i%2 != 0:
            sum = sum + i
            n = n + 1
    avg = sum/n
    return avg
tl = [1,2,3,4]    
print(avg_the_odds(tl))    
## 2.0

Exercise

Create a function largest(nl). The parameter nl is a list of numbers. The function returns the largest value in the list. Assume that you can’t assume anything about the numbers in the list. How would you initialize the largest value? Test your function with tl = [1,-5,16,76,127,4]

Solution

def largest(nl):
    lrgv = nl[0]
    for i in nl:
        if i > lrgv:
            lrgv = i
    return(lrgv)
 
tl = [1,-5,16,76,127,4] 
print(largest(tl))
## 127

Exercise

Modify largest() to create smallest().

Solution

def smallest(nl):
    smlv = nl[0]
    for i in nl:
        if i < smlv:
            smlv = i
    return(smlv)
 
tl = [1,-5,16,76,127,4] 
print(smallest(tl))
## -5