T27. Make a small list of strings to use for testing index expressions:
notes = ['do', 're', 'mi', 'fa', 'sol', 'la', 'ti']
T28. Use an index expression to get the first item in the list:
notes[0]
T29. Because there are seven strings in this list we can find the last one at location 6:
notes[6]
T30. Type another expression to access the last item:
notes[len(notes) - 1]
T31. Try asking Python for values at other locations, using any index between 0 and 6. Is the result what you expected?
notes[2]
notes[4]
T32. Ask for an index that is past the end of the list:
notes[12]
T33. Next try some expressions using in
, which should evaluate to True
or False
, depending on whether the list contains the specified item:
're' in notes
'bzzt' in notes
T34. Use Python's index
method to find out where the items are located:
notes.index('re')
notes.index('bzzt')
T35. Enter a for
loop in the code cell below. The loop should use range
to iterate over the notes
list and print something about each note:
for i in range(0, len(notes)):
print(notes[i], 'has', len(notes[i]), 'letters')
T36. Enter the for
loop that prints the square roots of numbers from 1 to 10 (don't forget to import the sqrt
function if you haven't done it already):
from math import sqrt
for i in range(1, 11):
print(i, sqrt(i))
T37. Repeat the previous exercise, but this time use range(1,11,2)
. Did Python execute the body of the loop only for odd values of i
? Do you see why?
for i in range(1, 11, 2):
print(i, sqrt(i))
partial_total
¶T38. Enter the definition of the partial_total
function from Figure 3.6 in the code cell below. You can either type the definitions shown in the figure, or copy and paste the code from partialtotal.py
.
After the definition is complete type ⌃⏎ to execute the cell to make the function available in this notebook.
def partial_total(n,a):
""""
Compute the total of the first
n items in list a.
"""
sum = 0
for i in range(0,n):
sum += a[i]
return sum
Make a list named a
containing the numbers 3, 5, 2, 16, and 7:
a = [3, 5, 2, 16, 7]
How would you call partial_total
to get the sum of the first three numbers? Type the expression in the code cell below to verify your answer.
partial_total(3, a)
If you're not sure how partial_total
works add this print statement to the for
loop, right after the statement that adds a[i]
to sum
. Type ⌃⏎ to update the function definition, then call the function with different values of n
.
print('i =', i, 'sum =', sum)
T39. What happens if you pass a number to partial_total
that is larger than the number of items in the list? For example, what does Python do if a
has five items and you call partial_total(7,a)
?
partial_total(7, a)
♦ Add statements to your definition of partial_total
so the function returns a correct value even if n
is too large. If n
is greater than the number of items in the list, simply return the sum of all the items.
♦ Repeat the call to partial_total(7,a)
. Does your function return the correct result now?