CS 303e - Discussion for April 12, 2013
Loops and lists
Recall that every character (string of length 1) has an
associated integer value, 0 to 255. The integer values for lowercase
letters are larger than the integer values of uppercase letters.
Functions chr and ord allow you to switch back and forth between a
character and its integer value.
Exercise: Try this - complete the loop below, so that it prints the
uppercase letters, one per line.
Hint: Define a variable to contain the difference between a lowercase
letter and its uppercase version (note that this difference is the
same, regardless of which letter you pick.)
for i in range(ord('a'), ord('z')+1):
# put your code here - initialize the variable below:
Once you've given this a try with your partner, your discussion leader
will talk about the solution.
Remember: Indexing starts at 0. For a list L with n entries, the valid
index values are 0 to len(L)-1.
Exercise: Write a function everyOther() that takes a list as its
argument, and returns a list that contains every other element,
starting with the first element. If the argument is the empty list,
return the empty list.
Exercise: Now write a main() function that reads a text file and makes
a new list from the lines in the file. (Each line is one entry in the
list). Don't forget to open and close the file! Use everyOther() to
print every other line in the file (i.e., every list element) to a new
file called copy.txt.
After you've had a chance to try these with your partner, your
discussion leader will talk about the solution.