Monday, 6 March 2017

Python Glossy*

Glossary
Quick reference guide to Python.

">>>"
The default Python prompt of the interactive shell.

Often seen for code examples which can be executed interactively in the
interpreter.
abs
Return the absolute value of a number.
argument
Extra information which the computer uses to perform commands.
argparse
Argparse is a parser for command-line options, arguments and subcommands.
assert
Used during debugging to check for conditions that ought to apply
assignment
Giving a value to a variable.
block
Section of code which is grouped together
break
Used to exit a for loop or a while loop.
class
A template for creating user-defined objects.
compiler
Translates a program written in a high-level language into a low-level language.
continue
Used to skip the current block, and return to the "for" or "while" statement
conditional statement
Statement that contains an "if" or "if/else".
debugging
The process of finding and removing programming errors.
def
Defines a function or method
dictionary
A mutable associative array (or dictionary) of key and value pairs.

Can contain mixed types (keys and values). Keys must be a hashable type.
distutils
Package included in the Python Standard Library for installing, building and
distributing Python code.
docstring
A docstring is a string literal that occurs as the first statement in a module,
function, class, or method definition.
__future__
A pseudo-module which programmers can use to enable new language features which
are not compatible with the current interpreter.
easy_install
Easy Install is a python module (easy_install) bundled with setuptools that lets
you automatically download, build, install, and manage Python packages.
evaluation order
Python evaluates expressions from left to right. Notice that while evaluating
an assignment, the right-hand side is evaluated before the left-hand side.
exceptions
Means of breaking out of the normal flow of control of a code block in order to
handle errors or other exceptional conditions
expression
Python code that produces a value.
filter
filter(function, sequence) returns a sequence consisting of those items from the
sequence for which function(item) is true
float
An immutable floating point number.
for
Iterates over an iterable object, capturing each element to a local variable for
use by the attached block
function
A parameterized sequence of statements.
function call
An invocation of the function with arguments.
garbage collection
The process of freeing memory when it is not used anymore.
generators
A function which returns an iterator.
high level language
Designed to be easy for humans to read and write.
IDLE
Integrated development environment
if statement
Conditionally executes a block of code, along with else and elif
(a contraction of else-if).
immutable
Cannot be changed after its created.
import
Used to import modules whose functions or variables can be used in the current
program.
indentation
Python uses white-space indentation, rather than curly braces or keywords,
to delimit blocks.
int
An immutable integer of unlimited magnitude.
interactive mode
When commands are read from a tty, the interpreter is said to be in interactive
mode.
interpret
Execute a program by translating it one line at a time.
IPython
Interactive shell for interactive computing.
iterable
An object capable of returning its members one at a time.
lambda
They are a shorthand to create anonymous functions.
list
Mutable list, can contain mixed types.
list comprehension
A compact way to process all or part of the elements in a sequence and return
a list with the results.
literals
Literals are notations for constant values of some built-in types.
map
map(function, iterable, ...) Apply function to every item of iterable and return
a list of the results.
methods
A method is like a function, but it runs "on" an object.
module
The basic unit of code reusability in Python. A block of code imported by some
other code.
object
Any data with state (attributes or value) and defined behavior (methods).
object-oriented
allows users to manipulate data structures called objects in order to build and
execute programs.
pass
Needed to create an empty code block
PEP 8
A set of recommendations how to write Python code.
Python Package Index
Official repository of third-party software for Python
Pythonic
An idea or piece of code which closely follows the most common idioms of the
Python language, rather than implementing code using concepts common to other
languages.
reduce
reduce(function, sequence) returns a single value constructed by calling the
(binary) function on the first two items of the sequence,
then on the result and the next item, and so on.
set
Unordered set, contains no duplicates
setuptools
Collection of enhancements to the Python distutils that allow you to more easily
build and distribute Python packages
slice
Sub parts of sequences
str
A character string: an immutable sequence of Unicode codepoints.
strings
Can include numbers, letters, and various symbols and be enclosed by either
double or single quotes, although single quotes are more commonly used.
statement
A statement is part of a suite (a "block" of code).
try
Allows exceptions raised in its attached code block to be caught and handled by
except clauses.
tuple
Immutable, can contain mixed types.
variables
Placeholder for texts and numbers.

The equal sign (=) is used to assign values to variables.
while
Executes a block of code as long as its condition is true.
with
Encloses a code block within a context manager.

yield
Returns a value from a generator function.
Zen of Python
When you type "import this", Python’s philosophy is printed out.

Dealing with the imperfect - python (part 16)

Dealing with the imperfect

...or how to handle errors
So you now have the perfect program, it runs flawlessly, except for one detail, it will crash on invalid user input. Have no fear, for Python has a special control structure for you. It's called try and it tries to do something. Here is an example of a program with a problem:
print "Type Control C or -1 to exit"
number = 1
while number != -1:
    number = int(raw_input("Enter a number: "))
    print "You entered:", number
Notice how when you enter @#& it outputs something like:
Traceback (innermost last):
File "try_less.py", line 4, in ?
    number = int(raw_input("Enter a number: "))</source>

ValueError: invalid literal for int(): @#&
As you can see the int() function is unhappy with the number @#& (as well it should be). The last line shows what the problem is; Python found a ValueError. How can our program deal with this? What we do is first: put the place where the errors occurs in a try block, and second: tell Python how we want ValueErrors handled. The following program does this:
print "Type Control C or -1 to exit"
number = 1
while number != -1:
    try:
        number = int(raw_input("Enter a number: "))
        print "You entered:", number
    except ValueError:
        print "That was not a number."
Now when we run the new program and give it @#& it tells us "That was not a number." and continues with what it was doing before.
When your program keeps having some error that you know how to handle, put code in a try block, and put the way to handle the error in the except block.
Here is a more complex example of Error Handling.
# Program by Mitchell Aikens 2012
# No copyright.
import math

def main():
    try:
        epact()
    except ValueError:
        print "Error. Please enter an integer value."
        year = 0
        epact()
    except NameError:
        print "Error. Please enter an integer value."
        year = 0
        epact()
    except SyntaxError:
        print "Error. Please enter an integer value."
        year = 0
        epact()
    finally:
        print "Program Complete"

def epact():

    year = int(input("What year is it?\n"))
    C = year/100
    epactval = (8 + (C/4) - C + ((8*C + 13)/25) + 11 * (year%19))%30
    print "The Epact is: ",epactval

main()
The program above uses concepts from previous lessons as well as the current lesson. Let's look at the above program in sections.
After we define the function called "main", we tell it that we want to "try" function named "epact." The interpreter then goes to the the line year = int(input("What year is it?\n")). The interpreter takes the value entered by the user and stores it in the variable named "year".
If the value entered is not an integer or a floating point number (which would be converted to an integer by the interpreter), an exception would be raised.
Let's look at some possible exceptions. the program above does not have an except clause for every possible exception, as there are numerous types or exceptions.
If the value entered for year is an alphabetical character, a NameError exception is raised. In the program above, this is caught by the except NameError: line, and the interpreter executes the print statement below the except NameError:, then it sets the value of "year" to 0 as a precaution, clearing it of any non-numeric number. The interpreter then jumps back to the first line of the epact() function, and the process restarts.
The process above would be the same for the other exceptions we have. If an exception is raised, and there is an except clause for it in our program, the interpreter will jump to the statements under the appropriate except clause, and execute them.
The finally statement, is sometimes used in exception handling as well. Think of it as the trump card. Statements underneath the finally clause will be executed regardless of if we raise and exception or not. The finally statement will be executed after any try or except clauses prior to it.
In the case of the program above, our exception handlers serve as a type of recursion or loop. When we raise an exception that is handled, the statements underneath our handlers take us back to the beginning of the epact function. This forces the user to keep entering a value, until a valid numeric value is entered. This means our finally statement won't execute until a valid value is entered, because the except statements send us back tot he beginning of the function, which makes it possible to raise yet another exception, which will be handled, and will send us back to the beginning and...well, you get the idea.
Below is a simpler example where we are not looped, and the finally clause is executed regardless of exceptions.
#Program By Mitchell Aikens 2012
#Not copyright.

def main():
    try:
        number = int(input("Please enter a number.\n"))
        half = number/2
        print "Half of the number you entered is ",half
    except NameError:
        print "Error."
    except ValueError:
        print "Error."
    except SyntaxError:
        print "Error."
    finally:
        print "I am executing the finally clause."

main()
If we were to enter an alphabetic value for number = int(input("Please enter a number.\n")), the output would be as follows:
Please enter a number.
t
Error.
I am executing the finally clause.
Exercises
Update at least the phone numbers program (in section File IO) so it doesn't crash if a user doesn't enter any data at the menu

File IO - python (part 15)

File IO

Here is a simple example of file IO (input/output):
# Write a file
out_file = open("test.txt", "w")
out_file.write("This Text is going to out file\nLook at it and see!")
out_file.close()

# Read a file
in_file = open("test.txt", "r")
text = in_file.read()
in_file.close()

print text
The output and the contents of the file test.txt are:
This Text is going to out file
Look at it and see!
Notice that it wrote a file called test.txt in the directory that you ran the program from. The \n in the string tells Python to put a newline where it is.
A overview of file IO is:
Get a file object with the open function.
Read or write to the file object (depending on how it was opened)
Close it
The first step is to get a file object. The way to do this is to use the open function. The format is file_object = open(filename, mode) where file_object is the variable to put the file object, filename is a string with the filename, and mode is "r" to read a file or "w" to write a file (and a few others we will skip here). Next the file objects functions can be called. The two most common functions are read and write. The write function adds a string to the end of the file. The read function reads the next thing in the file and returns it as a string. If no argument is given it will return the whole file (as done in the example).
Now here is a new version of the phone numbers program that we made earlier:
def print_numbers(numbers):
    print "Telephone Numbers:"
    for x in numbers.keys():
        print "Name:", x, "\tNumber:", numbers[x]
    print

def add_number(numbers, name, number):
    numbers[name] = number

def lookup_number(numbers, name):
    if name in numbers:
        return "The number is " + numbers[name]
    else:
        return name + " was not found"

def remove_number(numbers, name):
    if name in numbers:
        del numbers[name]
    else:
        print name," was not found"

def load_numbers(numbers, filename):
    in_file = open(filename, "r")
    while True:
        in_line = in_file.readline()
        if not in_line:
            break
        in_line = in_line[:-1]
        name, number = in_line.split(",")
        numbers[name] = number
    in_file.close()

def save_numbers(numbers, filename):
    out_file = open(filename, "w")
    for x in numbers.keys():
        out_file.write(x + "," + numbers[x] + "\n")
    out_file.close()

def print_menu():
    print '1. Print Phone Numbers'
    print '2. Add a Phone Number'
    print '3. Remove a Phone Number'
    print '4. Lookup a Phone Number'
    print '5. Load numbers'
    print '6. Save numbers'
    print '7. Quit'
    print

phone_list = {}
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Type in a number (1-7): ")
    if menu_choice == 1:
        print_numbers(phone_list)
    elif menu_choice == 2:
        print "Add Name and Number"
        name = raw_input("Name: ")
        phone = raw_input("Number: ")
        add_number(phone_list, name, phone)
    elif menu_choice == 3:
        print "Remove Name and Number"
        name = raw_input("Name: ")
        remove_number(phone_list, name)
    elif menu_choice == 4:
        print "Lookup Number"
        name = raw_input("Name: ")
        print lookup_number(phone_list, name)
    elif menu_choice == 5:
        filename = raw_input("Filename to load: ")
        load_numbers(phone_list, filename)
    elif menu_choice == 6:
        filename = raw_input("Filename to save: ")
        save_numbers(phone_list, filename)
    elif menu_choice == 7:
        break
    else:
        print_menu()

print "Goodbye"
Notice that it now includes saving and loading files. Here is some output of my running it twice:
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit

Type in a number (1-7): 2
Add Name and Number
Name: Jill
Number: 1234
Type in a number (1-7): 2
Add Name and Number
Name: Fred
Number: 4321
Type in a number (1-7): 1
Telephone Numbers:
Name: Jill     Number: 1234
Name: Fred     Number: 4321

Type in a number (1-7): 6
Filename to save: numbers.txt
Type in a number (1-7): 7
Goodbye
1. Print Phone Numbers
2. Add a Phone Number
3. Remove a Phone Number
4. Lookup a Phone Number
5. Load numbers
6. Save numbers
7. Quit

Type in a number (1-7): 5
Filename to load: numbers.txt
Type in a number (1-7): 1
Telephone Numbers:
Name: Jill     Number: 1234
Name: Fred     Number: 4321

Type in a number (1-7): 7
Goodbye
The new portions of this program are:
def load_numbers(numbers, filename):
    in_file = open(filename, "r")
    while True:
        in_line = in_file.readline()
        if not in_line:
            break
        in_line = in_line[:-1]
        name, number = in_line.split(",")
        numbers[name] = number
    in_file.close()
def save_numbers(numbers, filename):
    out_file = open(filename, "w")
    for x in numbers.keys():
        out_file.write(x + "," + numbers[x] + "\n")
    out_file.close()
First we will look at the save portion of the program. First it creates a file object with the command open(filename, "w"). Next it goes through and creates a line for each of the phone numbers with the command out_file.write(x + "," + numbers[x] + "\n"). This writes out a line that contains the name, a comma, the number and follows it by a newline.
The loading portion is a little more complicated. It starts by getting a file object. Then it uses a while True: loop to keep looping until a break statement is encountered. Next it gets a line with the line in_line = in_file.readline(). The readline function will return a empty string when the end of the file is reached. The if statement checks for this and breaks out of the while loop when that happens. Of course if the readline function did not return the newline at the end of the line there would be no way to tell if an empty string was an empty line or the end of the file so the newline is left in what readline returns. Hence we have to get rid of the newline. The line in_line = in_line[:-1] does this for us by dropping the last character. Next the line name, number = in_line.split(",") splits the line at the comma into a name and a number. This is then added to the numbers dictionary.
Exercises
Now modify the grades program from section Dictionaries so that is uses file IO to keep a record of the students.

Revenge of the Strings - python (part 14)

Revenge of the Strings

And now presenting a cool trick that can be done with strings:
def shout(string):
    for character in string:
        print "Gimme a " + character
        print "'" + character + "'"
shout("Lose")

def middle(string):
    print "The middle character is:", string[len(string) / 2]

middle("abcdefg")
middle("The Python Programming Language")
middle("Atlanta")
And the output is:
Gimme a L
'L'
Gimme a o
'o'
Gimme a s
's'
Gimme a e
'e'
The middle character is: d
The middle character is: r
The middle character is: a
What these programs demonstrate is that strings are similar to lists in several ways. The shout() function shows that for loops can be used with strings just as they can be used with lists. The middle procedure shows that that strings can also use the len() function and array indexes and slices. Most list features work on strings as well.
The next feature demonstrates some string specific features:
def to_upper(string):
    ## Converts a string to upper case
    upper_case = ""
    for character in string:
        if 'a' <= character <= 'z':
            location = ord(character) - ord('a')
            new_ascii = location + ord('A')
            character = chr(new_ascii)
        upper_case = upper_case + character
    return upper_case

print to_upper("This is Text")
with the output being:
THIS IS TEXT
This works because the computer represents the characters of a string as numbers from 0 to 255. Python has a function called ord() (short for ordinal) that returns a character as a number. There is also a corresponding function called chr() that converts a number into a character. With this in mind the program should start to be clear. The first detail is the line: if 'a' <= character <= 'z': which checks to see if a letter is lower case. If it is then the next lines are used. First it is converted into a location so that a = 0, b = 1, c = 2 and so on with the line: location = ord(character) - ord('a'). Next the new value is found with new_ascii = location + ord('A'). This value is converted back to a character that is now upper case.
Now for some interactive typing exercise:
>>> # Integer to String
>>> 2
2
>>> repr(2)
'2'
>>> -123
-123
>>> repr(-123)
'-123'
>>> `123`
'123'
>>> # String to Integer
>>> "23"
'23'
>>> int("23")
23
>>> "23" * 2
'2323'
>>> int("23") * 2
46
>>> # Float to String
>>> 1.23
1.23
>>> repr(1.23)
'1.23'
>>> # Float to Integer
>>> 1.23
1.23
>>> int(1.23)
1
>>> int(-1.23)
-1
>>> # String to Float
>>> float("1.23")
1.23
>>> "1.23"
'1.23'
>>> float("123")
123.0
>>> `float("1.23")`
'1.23'
If you haven't guessed already the function repr() can convert a integer to a string and the function int() can convert a string to an integer. The function float() can convert a string to a float. The repr() function returns a printable representation of something. `...` converts almost everything into a string, too. Here are some examples of this:
>>> repr(1)
'1'
>>> repr(234.14)
'234.14'
>>> repr([4, 42, 10])
'[4, 42, 10]'
>>> `[4, 42, 10]`
'[4, 42, 10]'
The int() function tries to convert a string (or a float) into a integer. There is also a similar function called float() that will convert a integer or a string into a float. Another function that Python has is the eval() function. The eval() function takes a string and returns data of the type that python thinks it found. For example:
>>> v = eval('123')
>>> print v, type(v)
123 <type 'int'>
>>> v = eval('645.123')
>>> print v, type(v)
645.123 <type 'float'>
>>> v = eval('[1, 2, 3]')
>>> print v, type(v)
[1, 2, 3] <type 'list'>
If you use the eval() function you should check that it returns the type that you expect.
One useful string function is the split() method. Here's an example:
>>> "This is a bunch of words".split()
['This', 'is', 'a', 'bunch', 'of', 'words']
>>> text = "First batch, second batch, third, fourth"
>>> text.split(",")
['First batch', ' second batch', ' third', ' fourth']
Notice how split() converts a string into a list of strings. The string is split by whitespace by default or by the optional argument (in this case a comma). You can also add another argument that tells split() how many times the separator will be used to split the text. For example:
>>> list = text.split(",")
>>> len(list)
4
>>> list[-1]
' fourth'
>>> list = text.split(",", 2)
>>> len(list)
3
>>> list[-1]
' third, fourth'
Slicing strings (and lists)
Strings can be cut into pieces — in the same way as it was shown for lists in the previous chapter — by using the slicing "operator" [:]. The slicing operator works in the same way as before: text[first_index:last_index] (in very rare cases there can be another colon and a third argument, as in the example shown below).
In order not to get confused by the index numbers, it is easiest to see them as clipping places, possibilities to cut a string into parts. Here is an example, which shows the clipping places (in yellow) and their index numbers (red and blue) for a simple text string:

0
1
2
...
-2
-1









text = "
S
T
R
I
N
G
"











[:








:]
Note that the red indexes are counted from the beginning of the string and the blue ones from the end of the string backwards. (Note that there is no blue -0, which could seem to be logical at the end of the string. Because -0 == 0, (-0 means "beginning of the string" as well.) Now we are ready to use the indexes for slicing operations:
text[1:4] → "TRI"
text[:5] → "STRIN"
text[:-1] → "STRIN"
text[-4:] → "RING"
text[2] → "R"
text[:] → "STRING"
text[::-1] → "GNIRTS"
text[1:4] gives us all of the text string between clipping places 1 and 4, "TRI". If you omit one of the [first_index:last_index] arguments, you get the beginning or end of the string as default: text[:5] gives "STRIN". For both first_index and last_index we can use both the red and the blue numbering schema: text[:-1] gives the same astext[:5], because the index -1 is at the same place as 5 in this case. If we do not use an argument containing a colon, the number is treated in a different way: text[2] gives us one character following the second clipping point, "R". The special slicing operation text[:] means "from the beginning to the end" and produces a copy of the entire string (or list, as shown in the previous chapter).
Last but not least, the slicing operation can have a second colon and a third argument, which is interpreted as the "step size": text[::-1] is text from beginning to the end, with a step size of -1. -1 means "every character, but in the other direction". "STRING" backwards is "GNIRTS" (test a step length of 2, if you have not got the point here).
All these slicing operations work with lists as well. In that sense strings are just a special case of lists, where the list elements are single characters. Just remember the concept ofclipping places, and the indexes for slicing things will get a lot less confusing.
Examples
# This program requires an excellent understanding of decimal numbers
def to_string(in_int):
    """Converts an integer to a string"""
    out_str = ""
    prefix = ""
    if in_int < 0:
        prefix = "-"
        in_int = -in_int
    while in_int / 10 != 0:
        out_str = chr(ord('0') + in_int % 10) + out_str
        in_int = in_int / 10
    out_str = chr(ord('0') + in_int % 10) + out_str
    return prefix + out_str

def to_int(in_str):
    """Converts a string to an integer"""
    out_num = 0
    if in_str[0] == "-":
        multiplier = -1
        in_str = in_str[1:]
    else:
        multiplier = 1
    for x in range(0, len(in_str)):
        out_num = out_num * 10 + ord(in_str[x]) - ord('0')
    return out_num * multiplier

print to_string(2)
print to_string(23445)
print to_string(-23445)
print to_int("14234")
print to_int("12345")
print to_int("-3512")
The output is:
2
23445
-23445
14234
12345
-3512

More on Lists - python (part 13)

More on Lists

We have already seen lists and how they can be used. Now that you have some more background I will go into more detail about lists. First we will look at more ways to get at the elements in a list and then we will talk about copying them.
Here are some examples of using indexing to access a single element of a list:
>>> some_numbers = ['zero', 'one', 'two', 'three', 'four', 'five']
>>> some_numbers[0]
'zero'
>>> some_numbers[4]
'four'
>>> some_numbers[5]
'five'
All those examples should look familiar to you. If you want the first item in the list just look at index 0. The second item is index 1 and so on through the list. However what if you want the last item in the list? One way could be to use the len() function like some_numbers[len(some_numbers) - 1]. This way works since the len() function always returns the last index plus one. The second from the last would then be some_numbers[len(some_numbers) - 2]. There is an easier way to do this. In Python the last item is always index -1. The second to the last is index -2 and so on. Here are some more examples:
>>> some_numbers[len(some_numbers) - 1]
'five'
>>> some_numbers[len(some_numbers) - 2]
'four'
>>> some_numbers[-1]
'five'
>>> some_numbers[-2]
'four'
>>> some_numbers[-6]
'zero'
Thus any item in the list can be indexed in two ways: from the front and from the back.
Another useful way to get into parts of lists is using slicing. Here is another example to give you an idea what they can be used for:
>>> things = [0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, "Jack", "Jill"]
>>> things[0]
0
>>> things[7]
'Jill'
>>> things[0:8]
[0, 'Fred', 2, 'S.P.A.M.', 'Stocking', 42, 'Jack', 'Jill']
>>> things[2:4]
[2, 'S.P.A.M.']
>>> things[4:7]
['Stocking', 42, 'Jack']
>>> things[1:5]
['Fred', 2, 'S.P.A.M.', 'Stocking']
Slicing is used to return part of a list. The slicing operator is in the form things[first_index:last_index]. Slicing cuts the list before the first_index and before thelast_index and returns the parts inbetween. You can use both types of indexing:
>>> things[-4:-2]
['Stocking', 42]
>>> things[-4]
'Stocking'
>>> things[-4:6]
['Stocking', 42]
Another trick with slicing is the unspecified index. If the first index is not specified the beginning of the list is assumed. If the last index is not specified the whole rest of the list is assumed. Here are some examples:
>>> things[:2]
[0, 'Fred']
>>> things[-2:]
['Jack', 'Jill']
>>> things[:3]
[0, 'Fred', 2]
>>> things[:-5]
[0, 'Fred', 2]
Here is a (HTML inspired) program example (copy and paste in the poem definition if you want):
poem = ["<B>", "Jack", "and", "Jill", "</B>", "went", "up", "the",
        "hill", "to", "<B>", "fetch", "a", "pail", "of", "</B>",
        "water.", "Jack", "fell", "<B>", "down", "and", "broke",
        "</B>", "his", "crown", "and", "<B>", "Jill", "came",
        "</B>", "tumbling", "after"]

def get_bolds(text):
    true = 1
    false = 0
    ## is_bold tells whether or not the we are currently looking at
    ## a bold section of text.
    is_bold = false
    ## start_block is the index of the start of either an unbolded
    ## segment of text or a bolded segment.
    start_block = 0
    for index in range(len(text)):
        ## Handle a starting of bold text
        if text[index] == "<B>":
            if is_bold:
                print "Error: Extra Bold"
            ## print "Not Bold:", text[start_block:index]
            is_bold = true
            start_block = index + 1
        ## Handle end of bold text
        ## Remember that the last number in a slice is the index
        ## after the last index used.
        if text[index] == "</B>":
            if not is_bold:
                print "Error: Extra Close Bold"
            print "Bold [", start_block, ":", index, "]", text[start_block:index]
            is_bold = false
            start_block = index + 1

get_bolds(poem)
with the output being:
Bold [ 1 : 4 ] ['Jack', 'and', 'Jill']
Bold [ 11 : 15 ] ['fetch', 'a', 'pail', 'of']
Bold [ 20 : 23 ] ['down', 'and', 'broke']
Bold [ 28 : 30 ] ['Jill', 'came']
The get_bold() function takes in a list that is broken into words and tokens. The tokens that it looks for are <B> which starts the bold text and </B> which ends bold text. The function get_bold() goes through and searches for the start and end tokens.
The next feature of lists is copying them. If you try something simple like:
>>> a = [1, 2, 3]
>>> b = a
>>> print b
[1, 2, 3]
>>> b[1] = 10
>>> print b
[1, 10, 3]
>>> print a
[1, 10, 3]
This probably looks surprising since a modification to b resulted in a being changed as well. What happened is that the statement b = a makes b a reference to a. This means that b can be thought of as another name for a. Hence any modification to b changes a as well. However some assignments don't create two names for one list:
>>> a = [1, 2, 3]
>>> b = a * 2
>>> print a
[1, 2, 3]
>>> print b
[1, 2, 3, 1, 2, 3]
>>> a[1] = 10
>>> print a
[1, 10, 3]
>>> print b
[1, 2, 3, 1, 2, 3]
In this case b is not a reference to a since the expression a * 2 creates a new list. Then the statement b = a * 2 gives b a reference to a * 2 rather than a reference to a. All assignment operations create a reference. When you pass a list as an argument to a function you create a reference as well. Most of the time you don't have to worry about creating references rather than copies. However when you need to make modifications to one list without changing another name of the list you have to make sure that you have actually created a copy.
There are several ways to make a copy of a list. The simplest that works most of the time is the slice operator since it always makes a new list even if it is a slice of a whole list:
>>> a = [1, 2, 3]
>>> b = a[:]
>>> b[1] = 10
>>> print a
[1, 2, 3]
>>> print b
[1, 10, 3]
Taking the slice [:] creates a new copy of the list. However it only copies the outer list. Any sublist inside is still a references to the sublist in the original list. Therefore, when the list contains lists, the inner lists have to be copied as well. You could do that manually but Python already contains a module to do it. You use the deepcopy function of the copymodule:
>>> import copy
>>> a = [[1, 2, 3], [4, 5, 6]]
>>> b = a[:]
>>> c = copy.deepcopy(a)
>>> b[0][1] = 10
>>> c[1][1] = 12
>>> print a
[[1, 10, 3], [4, 5, 6]]
>>> print b
[[1, 10, 3], [4, 5, 6]]
>>> print c
[[1, 2, 3], [4, 12, 6]]
First of all notice that a is a list of lists. Then notice that when b[0][1] = 10 is run both a and b are changed, but c is not. This happens because the inner arrays are still references when the slice operator is used. However with deepcopy c was fully copied.
So, should I worry about references every time I use a function or =? The good news is that you only have to worry about references when using dictionaries and lists. Numbers and strings create references when assigned but every operation on numbers and strings that modifies them creates a new copy so you can never modify them unexpectedly. You do have to think about references when you are modifying a list or a dictionary.
By now you are probably wondering why are references used at all? The basic reason is speed. It is much faster to make a reference to a thousand element list than to copy all the elements. The other reason is that it allows you to have a function to modify the inputed list or dictionary. Just remember about references if you ever have some weird problem with data being changed when it shouldn't be.

Modules - Python (part 12)

Using Modules 

Here's this chapter's typing exercise (name it cal.py (import actually looks for a file named calendar.py and reads it in. If the file is named calendar.py and it sees a "import calendar" it tries to read in itself which works poorly at best.)):

import calendar
year = input("Type in the year number: ")
calendar.prcal(year)
And here is part of the output I got:

Type in the year number: 2001

                                 2001                                 

       January                  February                    March     

Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
1  2  3  4  5  6  7                1  2  3  4                1  2  3  4    
8  9 10 11 12 13 14       5  6  7  8  9 10 11       5  6  7  8  9 10 11
15 16 17 18 19 20 21      12 13 14 15 16 17 18      12 13 14 15 16 17 18    
22 23 24 25 26 27 28      19 20 21 22 23 24 25      19 20 21 22 23 24 25    
29 30 31                  26 27 28                  26 27 28 29 30 31       
(I skipped some of the output, but I think you get the idea.) So what does the program do? The first line import calendar uses a new command import. The command import loads a module (in this case the calendar module). To see the commands available in the standard modules either look in the library reference for python (if you downloaded it) or go to http://docs.python.org/library/. If you look at the documentation for the calendar module, it lists a function called prcal that prints a calendar for a year. The line calendar.prcal(year) uses this function. In summary to use a module import it and then use module_name.function for functions in the module. Another way to write the program is:

from calendar import prcal

year = input("Type in the year number: ")
prcal(year)
This version imports a specific function from a module. Here is another program that uses the Python Library (name it something like clock.py) (press Ctrl and the 'c' key at the same time to terminate the program):

from time import time, ctime

prev_time = ""
while True:
    the_time = ctime(time())
    if prev_time != the_time:
        print "The time is:", ctime(time())
        prev_time = the_time
With some output being:

The time is: Sun Aug 20 13:40:04 2000
The time is: Sun Aug 20 13:40:05 2000
The time is: Sun Aug 20 13:40:06 2000
The time is: Sun Aug 20 13:40:07 2000

Traceback (innermost last):
File "clock.py", line 5, in ?
    the_time = ctime(time())

KeyboardInterrupt
The output is infinite of course so I canceled it (or the output at least continues until Ctrl+C is pressed). The program just does a infinite loop (True is always true, so while True: goes forever) and each time checks to see if the time has changed and prints it if it has. Notice how multiple names after the import statement are used in the line from time import time, ctime.

The Python Library contains many useful functions. These functions give your programs more abilities and many of them can simplify programming in Python.

Exercises

Rewrite the High_low.py program from section Decisions to use a random integer between 0 and 99 instead of the hard-coded 78. Use the Python documentation to find an appropriate module and function to do this.

Dictionaries - python (part 11)

Dictionaries 

This chapter is about dictionaries. If you open a dictionary, you should notice every entry consists of two parts, a word and the word's definition. The word is the key to finding out what a word means, and what the word means is considered the value for that key. In Python, dictionaries have keys and values. Keys are used to find values. Here is an example of a dictionary in use:
def print_menu():
    print '1. Print Dictionary'
    print '2. Add definition'
    print '3. Remove word'
    print '4. Lookup word'
    print '5. Quit'
    print

words = {}
menu_choice = 0
print_menu()

while menu_choice != 5:
    menu_choice = input("Type in a number (1-5): ")
    if menu_choice == 1:
        print "Definitions:"
        for x in words.keys():
            print x, ": ", words[x]
        print
    elif menu_choice == 2:
        print "Add definition"
        name = raw_input("Word: ")
        means = raw_input("Definition: ")
        words[name] = means
    elif menu_choice == 3:
        print "Remove word"
        name = raw_input("Word: ")
        if name in words:
            del words[name]
            print name, " was removed."
        else:
            print name, " was not found."
    elif menu_choice == 4:
        print "Lookup Word"
        name = raw_input("Word: ")
        if name in words:
            print "The definition of ", name, " is: ", words[name]
        else:
            print name, "No definition for ", name, " was found."
    elif menu_choice != 5:
        print_menu()
And here is my output:
1. Print Dictionary
2. Add definition
3. Remove word
4. Lookup word
5. Quit

Type in a number (1-5): 2
Add definition
Word: Python
Definition: A snake, a programming language, and a British comedy.
Type in a number (1-5): 2
Add definition
Word: Dictionary
Definition: A book where words are defined.
Type in a number (1-5): 1
Definitions:
Python: A snake, a programming language, and a British comedy.
Dictionary: A book where words are defined.

Type in a number (1-5): 4
Lookup Word
Word: Python
The definition of Python is: A snake, a programming language, and a British comedy.
Type in a number (1-5): 3
Remove Word
Word: Dictionary
Dictionary was removed.
Type in a number (1-5): 1
Definitions:
Python: A snake, a programming language, and a British comedy.
Type in a number (1-5): 5
This program is similar to the name list from the earlier chapter on lists (note that lists use indexes and dictionaries don't). Here's how the program works:
First the function print_menu is defined. print_menu just prints a menu that is later used twice in the program.
Next comes the funny looking line words = {}. All that line does is tell Python that words is a dictionary.
The next few lines just make the menu work.
for x in words.keys():
    print x, ": ", words[x]
This goes through the dictionary and prints all the information. The function words.keys() returns a list that is then used by the for loop. The list returned by keys() is not in any particular order so if you want it in alphabetic order it must be sorted. Similar to lists the statement words[x] is used to access a specific member of the dictionary. Of course in this case x is a string.
Next the line words[name] = means adds a word and definition to the dictionary. If name is already in the dictionary means replaces whatever was there before.
if name in words:
    del words[name]
See if name is in words and remove it if it is. The expression name in words returns true if name is a key in words but otherwise returns false. The line del words[name]removes the key name and the value associated with that key.
if name in words:
    print "The definition of ", name, " is: ", words[name]
Check to see if words has a certain key and if it does prints out the definition associated with it.
Lastly if the menu choice is invalid it reprints the menu for your viewing pleasure.
A recap: Dictionaries have keys and values. Keys can be strings or numbers. Keys point to values. Values can be any type of variable (including lists or even dictionaries (those dictionaries or lists of course can contain dictionaries or lists themselves (scary right? :-) )). Here is an example of using a list in a dictionary:
max_points = [25, 25, 50, 25, 100]
assignments = ['hw ch 1', 'hw ch 2', 'quiz   ', 'hw ch 3', 'test']
students = {'#Max': max_points}

def print_menu():
    print "1. Add student"
    print "2. Remove student"
    print "3. Print grades"
    print "4. Record grade"
    print "5. Print Menu"
    print "6. Exit"

def print_all_grades():
    print '\t',
    for i in range(len(assignments)):
        print assignments[i], '\t',
    print
    keys = students.keys()
    keys.sort()
    for x in keys:
        print x, '\t',
        grades = students[x]
        print_grades(grades)

def print_grades(grades):
    for i in range(len(grades)):
        print grades[i], '\t', '\t',
    print

print_menu()
menu_choice = 0
while menu_choice != 6:
    print
    menu_choice = input("Menu Choice (1-6): ")
    if menu_choice == 1:
        name = raw_input("Student to add: ")
        students[name] = [0] * len(max_points)
    elif menu_choice == 2:
        name = raw_input("Student to remove: ")
        if name in students:
            del students[name]
        else:
            print "Student:", name, "not found"
    elif menu_choice == 3:
        print_all_grades()
    elif menu_choice == 4:
        print "Record Grade"
        name = raw_input("Student: ")
        if name in students:
            grades = students[name]
            print "Type in the number of the grade to record"
            print "Type a 0 (zero) to exit"
            for i in range(len(assignments)):
                print i + 1, assignments[i], '\t',
            print
            print_grades(grades)
            which = 1234
            while which != -1:
                which = input("Change which Grade: ")
                which = which - 1
                if 0 <= which < len(grades):
                    grade = input("Grade: ")
                    grades[which] = grade
                elif which != -1:
                    print "Invalid Grade Number"
        else:
            print "Student not found"
    elif menu_choice != 6:
        print_menu()
and here is a sample output:
1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit

Menu Choice (1-6): 3
       hw ch 1         hw ch 2         quiz            hw ch 3         test
#Max    25              25              50              25              100

Menu Choice (1-6): 5
1. Add student
2. Remove student
3. Print grades
4. Record grade
5. Print Menu
6. Exit

Menu Choice (1-6): 1
Student to add: Bill

Menu Choice (1-6): 4
Record Grade
Student: Bill
Type in the number of the grade to record
Type a 0 (zero) to exit
1   hw ch 1     2   hw ch 2     3   quiz        4   hw ch 3     5   test
0               0               0               0               0
Change which Grade: 1
Grade: 25
Change which Grade: 2
Grade: 24
Change which Grade: 3
Grade: 45
Change which Grade: 4
Grade: 23
Change which Grade: 5
Grade: 95
Change which Grade: 0

Menu Choice (1-6): 3
       hw ch 1         hw ch 2         quiz            hw ch 3         test
#Max    25              25              50              25              100
Bill    25              24              45              23              95

Menu Choice (1-6): 6
Heres how the program works. Basically the variable students is a dictionary with the keys being the name of the students and the values being their grades. The first two lines just create two lists. The next line students = {'#Max': max_points} creates a new dictionary with the key {#Max} and the value is set to be [25, 25, 50, 25, 100], since thats what max_points was when the assignment is made (I use the key #Max since # is sorted ahead of any alphabetic characters). Next print_menu is defined. Next the print_all_grades function is defined in the lines:
def print_all_grades():
    print '\t',
    for i in range(len(assignments)):
        print assignments[i], '\t',
    print
    keys = students.keys()
    keys.sort()
    for x in keys:
        print x, '\t',
        grades = students[x]
        print_grades(grades)
Notice how first the keys are gotten out of the students dictionary with the keys function in the line keys = students.keys(). keys is a list so all the functions for lists can be used on it. Next the keys are sorted in the line keys.sort() since it is a list. for is used to go through all the keys. The grades are stored as a list inside the dictionary so the assignment grades = students[x] gives grades the list that is stored at the key x. The function print_grades just prints a list and is defined a few lines later.
The later lines of the program implement the various options of the menu. The line students[name] = [0] * len(max_points) adds a student to the key of their name. The notation [0] * len(max_points) just creates a list of 0's that is the same length as the max_points list.
The remove student entry just deletes a student similar to the telephone book example. The record grades choice is a little more complex. The grades are retrieved in the linegrades = students[name] gets a reference to the grades of the student name. A grade is then recorded in the line grades[which] = grade. You may notice that gradesis never put back into the students dictionary (as in no students[name] = grades). The reason for the missing statement is that grades is actually another name forstudents[name] and so changing grades changes student[name].
Dictionaries provide a easy way to link keys to values. This can be used to easily keep track of data that is attached to various keys

Boolean Expressions - python (part 10)

Boolean Expressions

Here is a little example of boolean expressions (you don't have to type it in):
a = 6
b = 7
c = 42
print 1, a == 6
print 2, a == 7
print 3, a == 6 and b == 7
print 4, a == 7 and b == 7
print 5, not a == 7 and b == 7
print 6, a == 7 or b == 7
print 7, a == 7 or b == 6
print 8, not (a == 7 and b == 6)
print 9, not a == 7 and b == 6
With the output being:
1 True
2 False
3 True
4 False
5 True
6 True
7 False
8 True
9 False
What is going on? The program consists of a bunch of funny looking print statements. Each print statement prints a number and an expression. The number is to help keep track of which statement I am dealing with. Notice how each expression ends up being either False or True. In Python, false can also be written as 0 and true as 1.
The lines:
print 1, a == 6
print 2, a == 7
print out a True and a False respectively just as expected since the first is true and the second is false. The third print, print 3, a == 6 and b == 7, is a little different. The operator and means if both the statement before and the statement after are true then the whole expression is true otherwise the whole expression is false. The next line,print 4, a == 7 and b == 7, shows how if part of an and expression is false, the whole thing is false. The behavior of and can be summarized as follows:
expression result
true and true true
true and false false
false and true false
false and false false
Notice that if the first expression is false Python does not check the second expression since it knows the whole expression is false.
The next line, print 5, not a == 7 and b == 7, uses the not operator. not just gives the opposite of the expression. (The expression could be rewritten as print 5, a != 7 and b == 7). Here is the table:
expression result
not true false
not false true
The two following lines, print 6, a == 7 or b == 7 and print 7, a == 7 or b == 6, use the or operator. The or operator returns true if the first expression is true, or if the second expression is true or both are true. If neither are true it returns false. Here's the table:
expression result
true or true true
true or false true
false or true true
false or false false
Notice that if the first expression is true Python doesn't check the second expression since it knows the whole expression is true. This works since or is true if at least one half of the expression is true. The first part is true so the second part could be either false or true, but the whole expression is still true.
The next two lines, print 8, not (a == 7 and b == 6) and print 9, not a == 7 and b == 6, show that parentheses can be used to group expressions and force one part to be evaluated first. Notice that the parentheses changed the expression from false to true. This occurred since the parentheses forced the not to apply to the whole expression instead of just the a == 7 portion.
Here is an example of using a boolean expression:
list = ["Life", "The Universe", "Everything", "Jack", "Jill", "Life", "Jill"]

# make a copy of the list. See the More on Lists chapter to explain what [:] means.
copy = list[:]
# sort the copy
copy.sort()
prev = copy[0]
del copy[0]

count = 0

# go through the list searching for a match
while count < len(copy) and copy[count] != prev:
    prev = copy[count]
    count = count + 1

# If a match was not found then count can't be < len
# since the while loop continues while count is < len
# and no match is found

if count < len(copy):
    print "First Match:", prev
And here is the output:
First Match: Jill
This program works by continuing to check for match while count < len(copy) and copy[count] is not equal to prev. When either count is greater than the last index of copy or a match has been found the and is no longer true so the loop exits. The if simply checks to make sure that the while exited because a match was found.
The other "trick" of and is used in this example. If you look at the table for and notice that the third entry is "false and won't check". If count >= len(copy) (in other wordscount < len(copy) is false) then copy[count] is never looked at. This is because Python knows that if the first is false then they can't both be true. This is known as a short circuit and is useful if the second half of the and will cause an error if something is wrong. I used the first expression (count < len(copy)) to check and see if count was a valid index for copy. (If you don't believe me remove the matches "Jill" and "Life", check that it still works and then reverse the order of count < len(copy) and copy[count] != prev to copy[count] != prev and count < len(copy).)
Boolean expressions can be used when you need to check two or more different things at once.
A note on Boolean Operators
A common mistake for people new to programming is a misunderstanding of the way that boolean operators works, which stems from the way the python interpreter reads these expressions. For example, after initially learning about "and " and "or" statements, one might assume that the expression x == ('a' or 'b') would check to see if the variablex was equivalent to one of the strings 'a' or 'b'. This is not so. To see what I'm talking about, start an interactive session with the interpreter and enter the following expressions:
>>> 'a' == ('a' or 'b')
>>> 'b' == ('a' or 'b')
>>> 'a' == ('a' and 'b')
>>> 'b' == ('a' and 'b')
And this will be the unintuitive result:
>>> 'a' == ('a' or 'b')
True
>>> 'b' == ('a' or 'b')
False
>>> 'a' == ('a' and 'b')
False
>>> 'b' == ('a' and 'b')
True
At this point, the and and or operators seem to be broken. It doesn't make sense that, for the first two expressions, 'a' is equivalent to 'a' or 'b' while 'b' is not. Furthermore, it doesn't make any sense that 'b' is equivalent to 'a' and 'b'. After examining what the interpreter does with boolean operators, these results do in fact exactly what you are asking of them, it's just not the same as what you think you are asking.
When the Python interpreter looks at an or expression, it takes the first statement and checks to see if it is true. If the first statement is true, then Python returns that object's value without checking the second statement. This is because for an or expression, the whole thing is true if one of the values is true; the program does not need to bother with the second statement. On the other hand, if the first value is evaluated as false Python checks the second half and returns that value. That second half determines the truth value of the whole expression since the first half was false. This "laziness" on the part of the interpreter is called "short circuiting" and is a common way of evaluating boolean expressions in many programming languages.
Similarly, for an and expression, Python uses a short circuit technique to speed truth value evaluation. If the first statement is false then the whole thing must be false, so it returns that value. Otherwise if the first value is true it checks the second and returns that value.
One thing to note at this point is that the boolean expression returns a value indicating True or False, but that Python considers a number of different things to have a truth value assigned to them. To check the truth value of any given object x, you can use the function bool(x) to see its truth value. Below is a table with examples of the truth values of various objects:
True False
True False
1 0
Numbers other than zero The string 'None'
Nonempty strings Empty strings
Nonempty lists Empty lists
Nonempty dictionaries Empty dictionaries
Now it is possible to understand the perplexing results we were getting when we tested those boolean expressions before. Let's take a look at what the interpreter "sees" as it goes through that code:
First case:
>>> 'a' == ('a' or 'b')  # Look at parentheses first, so evaluate expression "('a' or 'b')"
                           # 'a' is a nonempty string, so the first value is True
                           # Return that first value: 'a'
>>> 'a' == 'a'           # the string 'a' is equivalent to the string 'a', so expression is True
True
Second case:
>>> 'b' == ('a' or 'b')  # Look at parentheses first, so evaluate expression "('a' or 'b')"
                           # 'a' is a nonempty string, so the first value is True
                           # Return that first value: 'a'
>>> 'b' == 'a'           # the string 'b' is not equivalent to the string 'a', so expression is False
False
Third case:
>>> 'a' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"
                           # 'a' is a nonempty string, so the first value is True, examine second value
                           # 'b' is a nonempty string, so second value is True
                           # Return that second value as result of whole expression: 'b'
>>> 'a' == 'b'           # the string 'a' is not equivalent to the string 'b', so expression is False
False
Fourth case:
>>> 'b' == ('a' and 'b') # Look at parentheses first, so evaluate expression "('a' and 'b')"
                           # 'a' is a nonempty string, so the first value is True, examine second value
                           # 'b' is a nonempty string, so second value is True
                           # Return that second value as result of whole expression: 'b'
>>> 'b' == 'b'           # the string 'b' is equivalent to the string 'b', so expression is True
True
So Python was really doing its job when it gave those apparently bogus results. As mentioned previously, the important thing is to recognize what value your boolean expression will return when it is evaluated, because it isn't always obvious.
Going back to those initial expressions, this is how you would write them out so they behaved in a way that you want:
>>> 'a' == 'a' or 'a' == 'b'
True
>>> 'b' == 'a' or 'b' == 'b'
True
>>> 'a' == 'a' and 'a' == 'b'
False
>>> 'b' == 'a' and 'b' == 'b'
False
When these comparisons are evaluated they return truth values in terms of True or False, not strings, so we get the proper results.

print "Try to guess my name!"
count = 0
name = "Tony"
guess = raw_input("What is my name? ")
while count < 3 and guess != name:
    print "You are wrong!"
    guess = raw_input("What is my name? ")
    count = count + 1

if guess != name:
    print "You are wrong!" # this message isn't printed in the third chance, so we print it now
    print "You ran out of chances."
    quit
else:
    print "Yes! My name is", name + "!"

For Loops - python (part 9)

For Loops

And here is the new typing exercise for this chapter:
onetoten = range(1, 11)
for count in onetoten:
    print count
and the ever-present output:
1
2
3
4
5
6
7
8
9
10
The output looks awfully familiar but the program code looks different. The first line uses the range function. The range function uses two arguments like this range(start, finish). start is the first number that is produced. finish is one larger than the last number. Note that this program could have been done in a shorter way:
for count in range(1, 11):
    print count
Here are some examples to show what happens with the range command:
>>> range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(-32, -20)
[-32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21]
>>> range(5,21)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(21, 5)
[]
The next line for count in onetoten: uses the for control structure. A for control structure looks like for variable in list:. list is gone through starting with the first element of the list and going to the last. As for goes through each element in a list it puts each into variable. That allows variable to be used in each successive time the for loop is run through. Here is another example (you don't have to type this) to demonstrate:
demolist = ['life', 42, 'the universe', 6, 'and', 9, 'everything']
for item in demolist:
    print "The Current item is:",
    print item
The output is:
The Current item is: life
The Current item is: 42
The Current item is: the universe
The Current item is: 6
The Current item is: and
The Current item is: 9
The Current item is: everything
Notice how the for loop goes through and sets item to each element in the list. Notice how if you don't want print to go to the next line add a comma at the end of the statement (i.e. if you want to print something else on that line). So, what is for good for? The first use is to go through all the elements of a list and do something with each of them. Here's a quick way to add up all the elements:
list = [2, 4, 6, 8]
sum = 0
for num in list:
    sum = sum + num

print "The sum is:", sum
with the output simply being:
The sum is: 20
Or you could write a program to find out if there are any duplicates in a list like this program does:
list = [4, 5, 7, 8, 9, 1, 0, 7, 10]
list.sort()
prev = list[0]
del list[0]
for item in list:
    if prev == item:
        print "Duplicate of", prev, "found"
    prev = item
and for good measure:
Duplicate of 7 Found
Okay, so how does it work? Here is a special debugging version to help you understand (you don't need to type this in):
l = [4, 5, 7, 8, 9, 1, 0, 7, 10]
print "l = [4, 5, 7, 8, 9, 1, 0, 7, 10]", "\t\tl:", l
l.sort()
print "l.sort()", "\t\tl:", l
prev = l[0]
print "prev = l[0]", "\t\tprev:", prev
del l[0]
print "del l[0]", "\t\tl:", l
for item in l:
    if prev == item:
        print "Duplicate of", prev, "found"
    print "if prev == item:", "\t\tprev:", prev, "\titem:", item
    prev = item
    print "prev = item", "\t\tprev:", prev, "\titem:", item
with the output being:
l = [4, 5, 7, 8, 9, 1, 0, 7, 10]        l: [4, 5, 7, 8, 9, 1, 0, 7, 10]
l.sort()                l: [0, 1, 4, 5, 7, 7, 8, 9, 10]
prev = l[0]             prev: 0
del l[0]                l: [1, 4, 5, 7, 7, 8, 9, 10]
if prev == item:        prev: 0         item: 1
prev = item             prev: 1         item: 1
if prev == item:        prev: 1         item: 4
prev = item             prev: 4         item: 4
if prev == item:        prev: 4         item: 5
prev = item             prev: 5         item: 5
if prev == item:        prev: 5         item: 7
prev = item             prev: 7         item: 7
Duplicate of 7 found
if prev == item:        prev: 7         item: 7
prev = item             prev: 7         item: 7
if prev == item:        prev: 7         item: 8
prev = item             prev: 8         item: 8
if prev == item:        prev: 8         item: 9
prev = item             prev: 9         item: 9
if prev == item:        prev: 9         item: 10
prev = item             prev: 10        item: 10
The reason I put so many print statements in the code was so that you can see what is happening in each line. (By the way, if you can't figure out why a program is not working, try putting in lots of print statements so you can see what is happening.) First the program starts with a boring old list. Next the program sorts the list. This is so that any duplicates get put next to each other. The program then initializes a prev(ious) variable. Next the first element of the list is deleted so that the first item is not incorrectly thought to be a duplicate. Next a for loop is gone into. Each item of the list is checked to see if it is the same as the previous. If it is a duplicate was found. The value of prev is then changed so that the next time the for loop is run through prev is the previous item to the current. Sure enough, the 7 is found to be a duplicate. (Notice how \t is used to print a tab.)
The other way to use for loops is to do something a certain number of times. Here is some code to print out the first 9 numbers of the Fibonacci series:
a = 1
b = 1
for c in range(1, 10):
    print a,
    n = a + b
    a = b
    b = n
with the surprising output:
1 1 2 3 5 8 13 21 34
Everything that can be done with for loops can also be done with while loops but for loops give an easy way to go through all the elements in a list or to do something a certain number of times.

List - python (part 8)

Lists

Variables with more than one value
You have already seen ordinary variables that store a single value. However other variable types can hold more than one value. The simplest type is called a list. Here is an example of a list being used:
which_one = input("What month (1-12)? ")
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']

if 1 <= which_one <= 12:
    print "The month is", months[which_one - 1]
and an output example:
What month (1-12)? 3
The month is March
In this example the months is a list. months is defined with the lines months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', and'August', 'September', 'October', 'November', 'December'] (note that a \ could also be used to split a long line, but that is not necessary in this case because Python is intelligent enough to recognize that everything within brackets belongs together). The [ and ] start and end the list with commas (,) separating the list items. The list is used in months[which_one - 1]. A list consists of items that are numbered starting at 0. In other words if you wanted January you would use months[0]. Give a list a number and it will return the value that is stored at that location.
The statement if 1 <= which_one <= 12: will only be true if which_one is between one and twelve inclusive (in other words it is what you would expect if you have seen that in algebra).
Lists can be thought of as a series of boxes. Each box has a different value. For example, the boxes created by demolist = ['life', 42, 'the universe', 6, 'and', 7] would look like this:
box number 0 1 2 3 4 5
demolist "life" 42 "the universe" 6 "and" 7
Each box is referenced by its number so the statement demolist[0] would get 'life', demolist[1] would get 42 and so on up to demolist[5] getting 7.
More features of lists
The next example is just to show a lot of other stuff lists can do (for once I don't expect you to type it in, but you should probably play around with lists until you are comfortable with them.). Here goes:
demolist = ["life", 42, "the universe", 6, "and", 7]
print "demolist = ",demolist
demolist.append("everything")
print "after 'everything' was appended demolist is now:"
print demolist
print "len(demolist) =", len(demolist)
print "demolist.index(42) =", demolist.index(42)
print "demolist[1] =", demolist[1]

# Next we will loop through the list
c = 0
while c < len(demolist):
    print "demolist[", c, "] =", demolist[c]
    c = c + 1

del demolist[2]
print "After 'the universe' was removed demolist is now:"
print demolist
if "life" in demolist:
    print "'life' was found in demolist"
else:
    print "'life' was not found in demolist"

if "amoeba" in demolist:
    print "'amoeba' was found in demolist"

if "amoeba" not in demolist:
    print "'amoeba' was not found in demolist"

demolist.sort()
print "The sorted demolist is", demolist
The output is:
demolist =  ['life', 42, 'the universe', 6, 'and', 7]
after 'everything' was appended demolist is now:
['life', 42, 'the universe', 6, 'and', 7, 'everything']
len(demolist) = 7
demolist.index(42) = 1
demolist[1] = 42
demolist[ 0 ] = life
demolist[ 1 ] = 42
demolist[ 2 ] = the universe
demolist[ 3 ] = 6
demolist[ 4 ] = and
demolist[ 5 ] = 7
demolist[ 6 ] = everything
After 'the universe' was removed demolist is now:
['life', 42, 6, 'and', 7, 'everything']
'life' was found in demolist
'amoeba' was not found in demolist
The sorted demolist is [6, 7, 42, 'and', 'everything', 'life']
This example uses a whole bunch of new functions. Notice that you can just print a whole list. Next the append function is used to add a new item to the end of the list. lenreturns how many items are in a list. The valid indexes (as in numbers that can be used inside of the []) of a list range from 0 to len - 1. The index function tells where the first location of an item is located in a list. Notice how demolist.index(42) returns 1, and when demolist[1] is run it returns 42. The line # Next we will loop through the list is a just a reminder to the programmer (also called a comment). Python will ignore any lines that start with a #. Next the lines:
c = 0
while c < len(demolist):
    print 'demolist[', c, '] =', demolist[c]
    c = c + 1
create a variable c, which starts at 0 and is incremented until it reaches the last index of the list. Meanwhile the print statement prints out each element of the list. The delcommand can be used to remove a given element in a list. The next few lines use the in operator to test if an element is in or is not in a list. The sort function sorts the list. This is useful if you need a list in order from smallest number to largest or alphabetical. Note that this rearranges the list. In summary, for a list, the following operations occur:
example explanation
demolist[2] accesses the element at index 2
demolist[2] = 3 sets the element at index 2 to be 3
del demolist[2] removes the element at index 2
len(demolist) returns the length of demolist
"value" in demolist is True if "value" is an element in demolist
"value" not in demolist is True if "value" is not an element in demolist
demolist.sort() sorts demolist
demolist.index("value") returns the index of the first place that "value" occurs
demolist.append("value") adds an element "value" at the end of the list
demolist.remove("value") removes the first occurrence of value from demolist (same as del demolist[demolist.index("value")])
This next example uses these features in a more useful way:
menu_item = 0
namelist = []
while menu_item != 9:
    print "--------------------"
    print "1. Print the list"
    print "2. Add a name to the list"
    print "3. Remove a name from the list"
    print "4. Change an item in the list"
    print "9. Quit"
    menu_item = input("Pick an item from the menu: ")
    if menu_item == 1:
        current = 0
        if len(namelist) > 0:
            while current < len(namelist):
                print current, ".", namelist[current]
                current = current + 1
        else:
            print "List is empty"
    elif menu_item == 2:
        name = raw_input("Type in a name to add: ")
        namelist.append(name)
    elif menu_item == 3:
        del_name = raw_input("What name would you like to remove: ")
        if del_name in namelist:
            # namelist.remove(del_name) would work just as fine
            item_number = namelist.index(del_name)
            del namelist[item_number]
            # The code above only removes the first occurrence of
            # the name.  The code below from Gerald removes all.
            # while del_name in namelist:
            #       item_number = namelist.index(del_name)
            #       del namelist[item_number]
        else:
            print del_name, "was not found"
    elif menu_item == 4:
        old_name = raw_input("What name would you like to change: ")
        if old_name in namelist:
            item_number = namelist.index(old_name)
            new_name = raw_input("What is the new name: ")
            namelist[item_number] = new_name
        else:
            print old_name, "was not found"

print "Goodbye"
And here is part of the output:
--------------------
1. Print the list
2. Add a name to the list
3. Remove a name from the list
4. Change an item in the list
9. Quit

Pick an item from the menu: 2
Type in a name to add: Jack

Pick an item from the menu: 2
Type in a name to add: Jill

Pick an item from the menu: 1
0 . Jack
1 . Jill

Pick an item from the menu: 3
What name would you like to remove: Jack

Pick an item from the menu: 4
What name would you like to change: Jill
What is the new name: Jill Peters

Pick an item from the menu: 1
0 . Jill Peters

Pick an item from the menu: 9
Goodbye
That was a long program. Let's take a look at the source code. The line namelist = [] makes the variable namelist a list with no items (or elements). The next important line is while menu_item != 9:. This line starts a loop that allows the menu system for this program. The next few lines display a menu and decide which part of the program to run.
The section
current = 0
if len(namelist) > 0:
    while current < len(namelist):
        print current, ".", namelist[current]
        current = current + 1
else:
    print "List is empty"
goes through the list and prints each name. len(namelist) tells how many items are in the list. If len returns 0, then the list is empty.
Then, a few lines later, the statement namelist.append(name) appears. It uses the append function to add an item to the end of the list. Jump down another two lines, and notice this section of code:
item_number = namelist.index(del_name)
del namelist[item_number]
Here the index function is used to find the index value that will be used later to remove the item. del namelist[item_number] is used to remove a element of the list.
The next section
old_name = raw_input("What name would you like to change: ")
if old_name in namelist:
    item_number = namelist.index(old_name)
    new_name = raw_input("What is the new name: ")
    namelist[item_number] = new_name
else:
   print old_name, "was not found"
uses index to find the item_number and then puts new_name where the old_name was.
Congratulations, with lists under your belt, you now know enough of the language that you could do any computations that a computer can do (this is technically known as Turing-Completeness). Of course, there are still many features that are used to make your life easier.
Examples
test.py
## This program runs a test of knowledge

# First get the test questions
# Later this will be modified to use file io.
def get_questions():
    # notice how the data is stored as a list of lists
    return [["What color is the daytime sky on a clear day? ", "blue"],
            ["What is the answer to life, the universe and everything? ", "42"],
            ["What is a three letter word for mouse trap? ", "cat"]]

# This will test a single question
# it takes a single question in
# it returns True if the user typed the correct answer, otherwise False

def check_question(question_and_answer):
    # extract the question and the answer from the list
    question = question_and_answer[0]
    answer = question_and_answer[1]
    # give the question to the user
    given_answer = raw_input(question)
    # compare the user's answer to the testers answer
    if answer == given_answer:
        print "Correct"
        return True
    else:
        print "Incorrect, correct was:", answer
        return False

# This will run through all the questions
def run_test(questions):
    if len(questions) == 0:
        print "No questions were given."
        # the return exits the function
        return
    index = 0
    right = 0
    while index < len(questions):
        # Check the question
        if check_question(questions[index]):
            right = right + 1
        # go to the next question
        index = index + 1
    # notice the order of the computation, first multiply, then divide
    print "You got", right * 100 / len(questions),\
           "% right out of", len(questions)

# now let's run the questions

run_test(get_questions())
The values True and False point to 1 and 0, respectively. They are often used in sanity checks, loop conditions etc. You will learn more about this a little bit later (chapterBoolean Expressions).
Sample Output:
What color is the daytime sky on a clear day?green
Incorrect, correct was: blue
What is the answer to life, the universe and everything?42
Correct
What is a three letter word for mouse trap?cat
Correct
You got 66 % right out of 3
Exercises
Expand the test.py program so it has a menu giving the option of taking the test, viewing the list of questions and answers, and an option to quit. Also, add a new question to ask, "What noise does a truly advanced machine make?" with the answer of "ping".