February 15 and 16, 2012
The purpose of today's lab is to work with
data structures (strings and lists) and sequence controllers (definite loops and the decision structure if-statement).
Work with a partner as before.
python3 statements/functions used:
1. a definite loop (for loop) for i in list: <statements> We will use a list written explicitly with square brackets, or a list that is stored in a variable. 2. string functions. examples x = "Computer Science is great" words = x.split() makes a list ["Computer","Science","is","great"] We can use this list in a definite loop for i in words: print(i) 3. random numbers x = random.randrange(4,9) x will have a value that is either 4,5,6,7, or 8 4. equality operator == "brown" == "brown" is True "brown" == "white" is False 5. if-statement if <True or False condition>: <statements> if word=="You": print("Hey you!")Get a copy of the file lab3judy.pyc from my handout directory (with the command getcopy lab3judy.pyc)
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.
We just demonstrated some string manipulationsGet all of this part to work before moving to Part 2. Place a call to the function main() after its definition, in the file. The call, main(), will not be an indented statement. It will be aligned with the reserved word def.
Part 2.
len(canned)as the second parameterm, m. What is the first parameter, n? Think of the possible index values of a list.
m = len(canned) n = ?? index = random.randrange(n,m)and use the variable called index with the variable canned to get one of the strings from the list.
Part 3. Now try out the if statment
Now use the input() function to ask the user to say something with lots of "Is" and "Yous" in it. Assign the user string to the varialbe message.message = message.split() computer = "" for word in message: old_word = word word = word.replace("I","You") if old_word==word: word = word.replace("You", "I") computer = computer + word + " " print(computer)This code takes each word from the sequence message, and first places the word in a variable called old_word, for safe-keeping.
word = word.replace("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 = word.replace("You", "I")and if the word contains "You", we'll replace it with "I" and assign the new string to word.