Harold Nelson
1/28/2020
Think of this code as one of a number of variations on a theme.
The loop variable i could be initialized at either the first value we want or one before that value.
The < could have been <=
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?
\[2^3=8\]
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.
Here’s an example with all of the opposite choices made.
## 1
## 2
## 3
## 4
## 5
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.
The range() function can be the object of iteration. Note that it may not produce exactly what you expected.
## 0
## 1
## 2
## 3
## 4
What does the following program print?
What does the following program print?
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.
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
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.
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]
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
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].
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
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]
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
Modify largest() to create smallest().