Computer Science 111, Fall 2006

Lab #4

September 28, 2006

The purpose of today's lab is to try out some string functions, and work with decision structures.

Get a copy of the file lab4.pyc from my handout directory (with the command getcopy lab4.pyc)
- and then run this program by invoking the python interpreter, and typing import lab4 and then lab4.main().
This is the program that you will write for the this lab

Use emacs to write your own version of the program. This is not a deep, meaningful program. It's just a way to try out some of python's functions and statements.
I have broken it into three parts. Get each part to work first before moving on the the next part.
Here is what your program should do:

Part 1.

Part 2.

Part 3. Now try out the if statment

Type the following statements at the end of your lab4.py main() function definition:
    computer = ""
    for word in message:
        old_word = word
        word = string.replace(word,"I","You")
        if old_word==word:
            word = string.replace(word, "You", "I")
        computer = computer + word + " " 
     print computer
This code takes each word from the sequence user_words, and first places the word in a variable called old_word, for safe-keeping.
The statement
        word = string.replace(word,"I","You")
finds all occurrences of the string "I" in word, and replaces it with "You". The variable word will only contain one word so it is either replaced or not. It then assigns the resulting string to the variable word. The next line is the beginning of an if statement
        if old_word==word:
it checks if old_word and word are the same using the equality operator (==). This is a nice feature of python. If they are the same, then no replacement happened. In that case, we want to try
            word = string.replace(word, "You", "I")
and if the word contains "You", we'll replace it with "I" and assign the new string to word.
  • After this statement, but still in the for loop, concatenate the string in variable word to variable computer, with the string " ", as before. After the loop statement, print out the string contained in the variable computer.