Workbook for Chapter 3 of Explorations in Computing

Section 3.4: List Indexes

T27. Make a small list of strings to use for testing index expressions:

In [ ]:
 

T28. Use an index expression to get the first item in the list:

In [ ]:
 

T29. Because there are seven strings in this list we can find the last one at location 6:

In [ ]:
 

T30. Type another expression to access the last item:

In [ ]:
 

T31. Try asking Python for values at other locations, using any index between 0 and 6. Is the result what you expected?

In [ ]:
 
In [ ]:
 

T32. Ask for an index that is past the end of the list:

In [ ]:
 

T33. Next try some expressions using in, which should evaluate to True or False, depending on whether the list contains the specified item:

In [ ]:
 
In [ ]:
 

T34. Use Python's index method to find out where the items are located:

In [ ]:
 
In [ ]:
 

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:

In [ ]:
 

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

In [ ]:
 

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?

In [ ]:
 

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.

In [ ]:
 

Make a list named a containing the numbers 3, 5, 2, 16, and 7:

In [ ]:
 

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.

In [ ]:
 

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)?

In [ ]:
 

♦ 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?