[~]$ cd [~]$ cd cs21/inclass/ [inclass]$ ls w01-intro/ w02-numAndString/ w03-decisions/ w04-graphics/ w05-functions/If the w06-loops directory does not yet exist, create it using mkdir
[inclass]$ mkdir w06-loopsCopy the sample files for today from my directory using cp
[inclass]$ cp ~adanner/public/cs21/w06-loops/* w05-loops/ [inclass]$ ls w01-intro/ w02-numAndString/ w03-decisions/ w04-graphics/ w05-functions/ w06-loops/ [inclass]$ cd w06-loops/ [w06-loops]$ ls fivequestions.py primefactors.py squareevens.py syracuse.py whileLoop.py listOps.py randOps.py stringOps.py tryExcept.py [w06-loops]$
The program stringOps.py covers some of the string methods you are likely to use. Read over the program, try a few extra examples in a python shell, and let me know if you have any questions.
Another new syntactic feature is the if <item> in <list>:. This statement evaluates to True and executes the body of the if statement if the specified item is present one or more times in the given list.
List elements can be modified. The syntax l[0]=x changes the contents of the first item in the list l to now contain the element x. Even though strings support index and slicing syntax (e.g., s[0], s[1:3], strings cannot be modified in this way. You can however convert a string to a list of characters, modify the list and then convert the list back to a string. The end of the program shows an example of this. Could this be how the method s.replace(old, new) works in the string class?
For more on list methods, type help(list) in a python shell. We will talk about some of these methods later in the course as we need them.
Sometimes we want the computer to pick a random number in a given range, pick a random element from a list, pick a random card from a deck, flip a coin, etc. The random module provides access to functions that support these types of operations. The random module is another library of functions that can extend the basic features of python. Other modules we have seen so far are string, math, time and graphics. With the exception of the graphics module, all of these modules are built into python. For a full list of python modules, see the online documentation listing all of the default modules. To get access to the random module, we add from random import * to the top of our program (or type it into the python shell).
Open the file randOps.py in vim, and run the program in a separate terminal. Note if you run the program again, you get different (random) results. This program illustrates the functions randrange and random. We will most often be using randrange. This function generates a list just like range, but then returns one item randomly from that list.
Next let's look at fivequestions.py.
And finally syracuse.py (time permitting)