Week 10 Lab Exercise - Hsu Users Web Pages Page 2

ADVERTISEMENT

CIS 130 - Intro to Programming
p. 2
Week 10 Lab Exercise - 03-28-07
8.
You want to write 27 to this file, but also a newline character. Write a Python statement below that will do
so.
____________________________________________________________________________
9.
And, write a Python statement that will now close this file.
____________________________________________________________________________
10. Now, on to arrays/lists! Write a Python statement that will set the variable listy to be a list containing the
values 1, 3, 15, and 8.
____________________________________________________________________________
11. You decide you want to add 23 to list listy. Write a Python statement that will do so.
____________________________________________________________________________
12. You find that you need to change the value 3 in this list to instead be 13. Write a Python statement that will
do so.
____________________________________________________________________________
13. Three more items are added to listy (so that now it contains 8 items in all). Write a Python statement that
will print JUST the last element of the list listy.
____________________________________________________________________________
14. And, write a Python statement that will print the entire list listy.
____________________________________________________________________________
15. You can probably imagine that it is occasionally useful to read numbers from a file into a list.
Write a function read_nums that takes a string as argument, the name of a file in the current directory
expected to contain one integer per line. The function opens the file and reads its contents into a list, and
then returns a list of the numbers in this file as its result.
(Be careful -- the list should be a list of numbers, not a list of strings. How can you obtain the number
equivalent to a number-formatted string (read from the file)? Note that it turns out that this means will also
happily eliminate that pesky newline from the end of the string read...)
In the interests of lab time, I will just run your read_nums to see if it works. Create a file in the current
working directory named test.txt that contains the numbers 5, 8, 2, 7, 1, 4, and then you will show me the
results of the following when it is your turn:
read_nums("test.txt") == [5, 8, 2, 7, 1, 4]
16. Remember line_of_X from HW #5? (If not, you can remind yourself by looking at the "Some solutions"
section of the public course web page.)

ADVERTISEMENT

00 votes

Related Articles

Related forms

Related Categories

Parent category: Education
Go
Page of 3