Using the following code I am trying to check the users input string (CAcodes) and checking each one individually by assigning each element in CAcodes to a list (CAcode). A for-loop checks the conditions to make sure that the conditions for each code are met. The main for-loop tests several things.

1.) Try Statement: tests if there is a url entered for the corresponding code in the dictionary (urldict). If there is no url entered for that specific code, then the dictionary holds the value to be "0.0". If the value is "0.0" (making k =1) the program breaks at a later 'if' statement and prints that there is no url entered for that code.

2.) Except KeyError: tests each code the user inputed is in the urldictionary. If the code is not found (making j=1), the program prints that the code was not found and then an 'elif' statement breaks (if j == 1:).

If there are no problems (j and k both = 0 and the length of the list = y), then the for-loop breaks and then breaks the while loop. Then prints the desired information (print courseprint(CAcode)).

The Problem: The for-loop only tests for the first code in the list. If both codes are valid and have entered url's then the program runs fine. It also runs fine if the first code is not valid or has no url. But if the subsequent code is not valid, the program prints the desired information for the first code and then crashes on the second.

while True:
        y = 0
        CAcode = []
        CAcodes = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes = CAcodes.split()
        for codeA in CAcodes:
            CAcode.append(int(codeA))
        for codeB in CAcode:
            print codeB
            j = 0
            k = 0
            y += 1
            try:
                if urldict[int(codeB)] == "0.0":
                    print "A"
                    k = 1
                    break
                else:
                    print "B"
                    break
            except KeyError:
                print "C"
                j = 1
                print "\nSorry, " + str(codeB) + " was not found. Please enter a valid CA code."
            if j == 1:
                print "D"
                break
            elif k == 1:
                print "E"
                print"\nError: There is no URL entered for " + str(codeB) + "."
                break
            elif (y == len(CAcode)) and (j != 1) and (k != 1):
                break
        if (y == len(CAcode)):
            break
    print ""
    print courseprint(CAcode)

Thanks in advance!

Can you give a table of valid codes? What is valid input and desired output? I can not understand your control flow design, despite your nice explanations. You seem to be doing something very unpythonic despite one try except.

Could you maybe think more general pseudo code for what you want to accomplish, instead of how you tried to do it?

The breaks are your problem. Try to take them out.

Happy coding...

Can you give a table of valid codes? What is valid input and desired output? I can not understand your control flow design, despite your nice explanations. You seem to be doing something very unpythonic despite one try except.

Could you maybe think more general pseudo code for what you want to accomplish, instead of how you tried to do it?

I can try to explain in words (since my python methods are obviously not working).

1.) User input of codes separated by spaces
2.) Take each one of those codes from the input and enter into a list
3.) Test that each code in that list is in the previously created list of all codes: 'codelist' (not currently in the above section of code).
4.) Test that each code in that list has a corresponding url found in the dictionary 'urldict'.
5.) If each code passes each test, then print the result of the function 'printcourse(list)'.
6.) If one the codes does not pass the test:
a.) Tell the user which code did not work and why (code not in 'codelist', no url for code, or input is not even a code - a four digit number)
b.) Restart the loop that asks for input and runs the test again

The breaks are your problem. Try to take them out.

Happy coding...

I tried taking out all of the breaks and it didn't work so well. I tried taking out the last two breaks and it seems to work, except that even though the program states that one of the codes is invalid, it still tries to print out the result. I have tried removing all the breaks but the last two and then alternating having one of the last two breaks working and the other not. But still it isn't working.

The code below recognizes the second code and tells the user that it is not valid code, but then tries to print 'courseprint(list)' anyway and fails.

while True:
        y = 0
        CAcode = []
        CAcodes = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes = CAcodes.split()
        for codeA in CAcodes:
            CAcode.append(int(codeA))
        for codeB in CAcode:
            print codeB
            j = 0
            k = 0
            y += 1
            try:
                if urldict[int(codeB)] == "0.0":
                    print "A"
                    k = 1
##                    break
                else:
                    print "B"
##                    break
            except KeyError:
                print "C"
                j = 1
                print "\nSorry, " + str(codeB) + " was not found. Please enter a valid CA code."
            if j == 1:
                print "D"
##                break
            elif k == 1:
                print "E"
                print"\nError: There is no URL entered for " + str(codeB) + "."
##                break
            elif (y == len(CAcode)) and (j != 1) and (k != 1):
                break
        if (y == len(CAcode)):
            break
    print ""
    print courseprint(CAcode)

Maybe you should do:

try:
    url = urldict(CAcode)
    print courseprint(CAcode)
except: ## put suitable error from error message here
    print 'Dictionary problem or invalid code!'

Discard codelist, only consider urldict.keys() directly, only those are valid (I assume that only those keys are in dict which have urls entered)

What I mean by taking out the breaks, was to design the code in other way without that logical path.

Maybe you should do:

try:
    url = urldict(CAcode)
    print courseprint(CAcode)
except: ## put suitable error from error message here
    print 'Dictionary problem or invalid code!'

Discard codelist, only consider urldict.keys() directly, only those are valid (I assume that only those keys are in dict which have urls entered)

I changed the code to the following (removing breaks where I could):

while True:
        CAcode = []
        CAcodes = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes = CAcodes.split()
        k = 0
        for codeA in CAcodes:
            try:
                CAcode.append(int(codeA))
            except ValueError:
                k = 1
                print "\nSorry, '"+ str(codeA) + "' was not found. Please enter a valid CA code."
        for codeB in CAcode:
            print codeB
            try:
                url = urldict[codeB]
                break
            except KeyError:
                try:
                    if urldict[int(codeB)] == "0.0":
                        k = 1
                        print "\nError: There is no URL entered for " + str(codeB) + "."
                except KeyError:
                    k = 1
                    print "\nSorry, "+ str(codeB) + " was not found. Please enter a valid CA code."
        if k == 0:
            break
    print ""
    print courseprint(CAcode)

The program displays the following looks like the following:

Enter CA Codes (separated by a space): 3198 3202
3198

------------------------------------------------------------
| 3198 | Enrolled: | 1 |
| 3202 | Enrolled: | 0 |
------------------------------------------------------------

Do you want to look up any else? (y/n)
n
Goodbye

As you can see, I have codeB be printed each time. But the only code printed is the first 3198. Although both codes (3198 and 3202) are printed using the 'courseprint' (as they both pass the tests), it does not check 3202. This is a problem when say the first is included but the second code isn't.

Any ideas on how to make sure that it checks all codes in the list? I was thinking about removing each code from the list and adding it to another so that it is forced to check the next in the list. But that sounds complicated.

Thanks for all the advice!

Without your input values for dictionaries it is difficult to test your code.

We can see some real inputs and outputs now from this last post.

Any help from this:

def validcode(code):
    return code if code in students and code in urls else None

def courseprint(code):
    if code: print "|%6i| Enrolled: | %5s |" % (code,code in enrolled)

students = {3:'a',5:'b',7:'c',11:'d',17:'e'}
enrolled = (5,17)
urls = {7:'http://s.sf.ssf',11:'http://sfas.llj.sf',17:'http://sfa.alasf'}

for student in (str(i) for i in range(20)+['a','test']): ## str to simulate inputted values
    try:
        courseprint(validcode(int(student)))
    except ValueError:
        print 'Student code %r is not number' % student

Here is the full code:

########################################
# Functions
def check(str):
    import urllib
    import urllib2
    from urllib2 import urlopen

    url = urldict[str]
    response = urllib2.urlopen(url)
    html = response.read()

    values = {'Spots Available' : '' }

    user_agent = 'Mozilla/5.0(compatible;MSIE 5.5;Windows NT)'
    headers = {'User-Agent': user_agent}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    split_page = the_page.splitlines()

    from BeautifulSoup import BeautifulSoup
    html = the_page
    soup = BeautifulSoup(''.join(html))

    CRFP = "Spots Available:"
    S = "Total Enrolled:"
    x = 999
    d = 0
    f = 999
    lines = html.splitlines()
    L = ""
    if channeldict[str] == ("XCR"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("F"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("P"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    L = int(L)
    return L

def codegen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0 
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    codelist = []
    for col in range(col_idx_max+1):
        if col == 0:
            codelist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                codelist[col].append(int(float(vdict[(row,col)])))
    return codelist

def channelgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime  
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    channellist = []
    for col in range(col_idx_max+1):
        if col == 1:
            channellist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                channellist[col-1].append(vdict[(row,col)])
    return channellist

def caagen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    caalist = []
    for col in range(col_idx_max+1):
        if col == 2:
            caalist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                caalist[col-2].append(vdict[(row,col)])
    return caalist

def maxgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    maxlist = []
    for col in range(col_idx_max+1):
        if col == 3:
            maxlist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                maxlist[col-3].append(vdict[(row,col)])
    return maxlist

def urlgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    urllist = []
    for col in range(col_idx_max+1):
        if col == 4:
            urllist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                urllist[col-4].append(vdict[(row,col)])
    return urllist


########################################
# Decode Excel
alpha = 'codedatabase.xls'
beta = codegen(alpha)
gamma = channelgen(alpha)
delta = caagen(alpha)
epsilon = maxgen(alpha)
zeta = urlgen(alpha)

codelist = []
channellist = []
caalist = []
maxlist = []
urllist = []

for item in beta:
    for thing in item:
        codelist.append(thing)
for item in gamma:
    for thing in item:
        thing2 = str(thing)
        channellist.append(thing2)
for item in delta:
    for thing in item:
        thing2 = str(thing)
        caalist.append(thing2)
for item in epsilon:
    for thing in item:
        thing2 = int(thing)
        maxlist.append(thing2)
for item in zeta:
    for thing in item:
        thing2 = str(thing)
        urllist.append(thing2)


########################################
# Create Excel Dictionaries
channeldict = {}
caadict = {}
maxdict = {}
urldict = {}
size = len(codelist)
for i in range(0,size):
    item = codelist[i]
    item2 = channellist[i]
    channeldict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = caalist[i]
    caadict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = maxlist[i]
    maxdict[item] = (item2)
for i in range(0,size):
    item = codelist[i]
    item2 = urllist[i]
    urldict[item] = item2


########################################
# Other Functions
def available(str):
    course = str
    x = 0
    P = ""
    size4 = len(codelist)
    for code in codelist:
        if (caadict[code]) == course:
            x = 1
    if x == 0:
        P = False
    elif x == 1:
        P = True
    return P

def clist(str):
    course = str
    courselist = []
    for code in codelist:
        if caadict[ code ] == course:
            courselist.append(code)
    return courselist

def enrolled(int):
    m = ""
    CAcode = int
    if channeldict[CAcode] == "X":
        m = "| " + str(CAcode) + " | Error:    | This is a CA exclusive class."
    elif urldict[CAcode] == "0.0":
        m = "| " + str(CAcode) + " | Error:    | There is no URL entered for that code."
    elif channeldict[CAcode] == "XCR":
        if caadict[CAcode] == "AMC8":
            m = "| " + str(CAcode) + " | Enrolled: | " + str(6 - check(CAcode))
        elif caadict[CAcode] == "ASC":
            m = "| " + str(CAcode) + " | Enrolled: | " + str((24 - ((check(CAcode)))))
        else:
            m = "| " + str(CAcode) + " | Enrolled: | " + str(((maxdict[CAcode])/2) - ((check(CAcode))))
    elif channeldict[CAcode] == ("F"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    elif channeldict[CAcode] == ("P"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    else:
        m = "| " + str(CAcode) + " | Enrolled: | Unknown. Check " + str(channeldict[CAcode]) + " website."
    size3 = len(m)
    add = 59 - size3
    for i in range(0,add):
        m = m + " "
    m = m + "|\n"
    return m

def courseprint(list):
    courselist = list
    size6 = len(courselist)
    courseprint = "------------------------------------------------------------\n"
    for code in courselist:
        m = str(enrolled(code))
        courseprint = courseprint + m
    courseprint = courseprint + "------------------------------------------------------------"
    return courseprint


########################################
# Main Program - Start
v = 0
ny = 0
print "\nLook up individual CA code(s)? (y/n)"
yn = raw_input().lower()

if yn == "y":
    ny = 1
if yn == "n":
    ny = 1

while ny == 0:
    print "\nSorry, please enter 'y' or 'n'"
    yn = raw_input().lower()
    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

if yn == "y":
    while True:
        CAcode = []
        CAcodes = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes = CAcodes.split()
        k = 0
        for codeA in CAcodes:
            try:
                CAcode.append(int(codeA))
            except ValueError:
                k = 1
                print "\nSorry, '"+ str(codeA) + "' was not found. Please enter a valid CA code."
        for codeB in CAcode:
            print codeB
            try:
                print "a"
                url = urldict[codeB]
                break
            except KeyError:
                try:
                    if urldict[int(codeB)] == "0.0":
                        k = 1
                        print "\nError: There is no URL entered for " + str(codeB) + "."
                except KeyError:
                    k = 1
                    print "\nSorry, "+ str(codeB) + " was not found. Please enter a valid CA code."
        if k == 0:
            break
    print ""
    print courseprint(CAcode)

if yn == "n":
    ny = 0
    print "\nDo you want to search by course name? (y/n)"
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1

    if yn == "y":
        course = str(raw_input("\nEnter class name: (ex: PPSCCS) ")).upper()
        while available(course) == False:
            print "\nSorry, that acronym does not exist. Please try another."
            course = str(raw_input().upper())
            if available(course) == True:
                break
        if available(course) == True:
            courselist = clist(course)
            print "\n", course
            print courseprint(courselist)

    if yn == "n":
        ny = 0
        yn = ""
        print "\nCheck enrollment for the quarter? (y/n)"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1
        while ny == 0:
            print "\nSorry, please enter 'y' or 'n'"
            yn = raw_input().lower()
            if yn == "y":
                ny = 1
            if yn == "n":
                ny = 1
        if yn == "y":
            alpha = 'database.xls'
            beta = codegen(alpha)
            codelist = []
            for item in beta:
                for thing in item:
                    codelist.append(thing)
            x = 0
            out = open('enrollment.txt', 'w')
            import datetime
            r = datetime.datetime.now()
            q = "\nUpdated:" + str(r) + "\n\n"
            q = q + str(courseprint(codelist))
            out.write(q)
            out.close()
            print "\nTable was printed to the file: 'enrollment.txt'"
            v = 1
        if yn == "n":
            print "\nWell in that case..."

########################################
# Do you want to run again?
ny = 0
if v == 0:    
    print """
Do you want to look up any else? (y/n)"""
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1


########################################
# Main Program - Restart
    if yn == "y":
        import os
        print """
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"""
        os.system('CAMain1.1.py')

########################################
# Main Program - End
    if yn == "n":
        print "Goodbye"
if v == 1:
    print "Goodbye"

Note, you have code in your code messing up the code tags!!

Thats not complicated. If there is a fixed code lenght you can call them like:

codeA, codeB = CAcodes.split(' ')

and eliminate the for's.

EDIT: I'll read your code when I return.

########################################
# Functions
def check(str):
    import urllib
    import urllib2
    from urllib2 import urlopen

    url = urldict[str]
    response = urllib2.urlopen(url)
    html = response.read()

    values = {'Spots Available' : '' }

    user_agent = 'Mozilla/5.0(compatible;MSIE 5.5;Windows NT)'
    headers = {'User-Agent': user_agent}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    split_page = the_page.splitlines()

    from BeautifulSoup import BeautifulSoup
    html = the_page
    soup = BeautifulSoup(''.join(html))

    CRFP = "Spots Available:"
    S = "Total Enrolled:"
    x = 999
    d = 0
    f = 999
    lines = html.splitlines()
    L = ""
    if channeldict[str] == ("XCR"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("F"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("P"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    L = int(L)
    return L

def codegen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0 
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    codelist = []
    for col in range(col_idx_max+1):
        if col == 0:
            codelist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                codelist[col].append(int(float(vdict[(row,col)])))
    return codelist

def channelgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime  
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    channellist = []
    for col in range(col_idx_max+1):
        if col == 1:
            channellist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                channellist[col-1].append(vdict[(row,col)])
    return channellist

def caagen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    caalist = []
    for col in range(col_idx_max+1):
        if col == 2:
            caalist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                caalist[col-2].append(vdict[(row,col)])
    return caalist

def maxgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    maxlist = []
    for col in range(col_idx_max+1):
        if col == 3:
            maxlist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                maxlist[col-3].append(vdict[(row,col)])
    return maxlist

def urlgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    urllist = []
    for col in range(col_idx_max+1):
        if col == 4:
            urllist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                urllist[col-4].append(vdict[(row,col)])
    return urllist


########################################
# Decode Excel
alpha = 'codedatabase.xls'
beta = codegen(alpha)
gamma = channelgen(alpha)
delta = caagen(alpha)
epsilon = maxgen(alpha)
zeta = urlgen(alpha)

codelist = []
channellist = []
caalist = []
maxlist = []
urllist = []

for item in beta:
    for thing in item:
        codelist.append(thing)
for item in gamma:
    for thing in item:
        thing2 = str(thing)
        channellist.append(thing2)
for item in delta:
    for thing in item:
        thing2 = str(thing)
        caalist.append(thing2)
for item in epsilon:
    for thing in item:
        thing2 = int(thing)
        maxlist.append(thing2)
for item in zeta:
    for thing in item:
        thing2 = str(thing)
        urllist.append(thing2)


########################################
# Create Excel Dictionaries
channeldict = {}
caadict = {}
maxdict = {}
urldict = {}
size = len(codelist)
for i in range(0,size):
    item = codelist[i]
    item2 = channellist[i]
    channeldict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = caalist[i]
    caadict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = maxlist[i]
    maxdict[item] = (item2)
for i in range(0,size):
    item = codelist[i]
    item2 = urllist[i]
    urldict[item] = item2


########################################
# Other Functions
def available(str):
    course = str
    x = 0
    P = ""
    size4 = len(codelist)
    for code in codelist:
        if (caadict[code]) == course:
            x = 1
    if x == 0:
        P = False
    elif x == 1:
        P = True
    return P

def clist(str):
    course = str
    courselist = []
    for code in codelist:
        if caadict[code] == course:
            courselist.append(code)
    return courselist

def enrolled(int):
    m = ""
    CAcode = int
    if channeldict[CAcode] == "X":
        m = "| " + str(CAcode) + " | Error:    | This is a CA exclusive class."
    elif urldict[CAcode] == "0.0":
        m = "| " + str(CAcode) + " | Error:    | There is no URL entered for that code."
    elif channeldict[CAcode] == "XCR":
        if caadict[CAcode] == "AMC8":
            m = "| " + str(CAcode) + " | Enrolled: | " + str(6 - check(CAcode))
        elif caadict[CAcode] == "ASC":
            m = "| " + str(CAcode) + " | Enrolled: | " + str((24 - ((check(CAcode)))))
        else:
            m = "| " + str(CAcode) + " | Enrolled: | " + str(((maxdict[CAcode])/2) - ((check(CAcode))))
    elif channeldict[CAcode] == ("F"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    elif channeldict[CAcode] == ("P"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    else:
        m = "| " + str(CAcode) + " | Enrolled: | Unknown. Check " + str(channeldict[CAcode]) + " website."
    size3 = len(m)
    add = 59 - size3
    for i in range(0,add):
        m = m + " "
    m = m + "|\n"
    return m

def courseprint(list):
    courselist = list
    size6 = len(courselist)
    courseprint = "------------------------------------------------------------\n"
    for code in courselist:
        m = str(enrolled(code))
        courseprint = courseprint + m
    courseprint = courseprint + "------------------------------------------------------------"
    return courseprint


########################################
# Main Program - Start
v = 0
ny = 0
print "\nLook up individual CA code(s)? (y/n)"
yn = raw_input().lower()

if yn == "y":
    ny = 1
if yn == "n":
    ny = 1

while ny == 0:
    print "\nSorry, please enter 'y' or 'n'"
    yn = raw_input().lower()
    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

if yn == "y":
    while True:
        CAcode = []
        CAcodes = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes = CAcodes.split()
        k = 0
        for codeA in CAcodes:
            try:
                CAcode.append(int(codeA))
            except ValueError:
                k = 1
                print "\nSorry, '"+ str(codeA) + "' was not found. Please enter a valid CA code."
        for codeB in CAcode:
            print codeB
            try:
                print "a"
                url = urldict[codeB]
                break
            except KeyError:
                try:
                    if urldict[int(codeB)] == "0.0":
                        k = 1
                        print "\nError: There is no URL entered for " + str(codeB) + "."
                except KeyError:
                    k = 1
                    print "\nSorry, "+ str(codeB) + " was not found. Please enter a valid CA code."
        if k == 0:
            break
    print ""
    print courseprint(CAcode)

if yn == "n":
    ny = 0
    print "\nDo you want to search by course name? (y/n)"
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1

    if yn == "y":
        course = str(raw_input("\nEnter class name: (ex: PPSCCS) ")).upper()
        while available(course) == False:
            print "\nSorry, that acronym does not exist. Please try another."
            course = str(raw_input().upper())
            if available(course) == True:
                break
        if available(course) == True:
            courselist = clist(course)
            print "\n", course
            print courseprint(courselist)

    if yn == "n":
        ny = 0
        yn = ""
        print "\nCheck enrollment for the quarter? (y/n)"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1
        while ny == 0:
            print "\nSorry, please enter 'y' or 'n'"
            yn = raw_input().lower()
            if yn == "y":
                ny = 1
            if yn == "n":
                ny = 1
        if yn == "y":
            alpha = 'database.xls'
            beta = codegen(alpha)
            codelist = []
            for item in beta:
                for thing in item:
                    codelist.append(thing)
            x = 0
            out = open('enrollment.txt', 'w')
            import datetime
            r = datetime.datetime.now()
            q = "\nUpdated:" + str(r) + "\n\n"
            q = q + str(courseprint(codelist))
            out.write(q)
            out.close()
            print "\nTable was printed to the file: 'enrollment.txt'"
            v = 1
        if yn == "n":
            print "\nWell in that case..."

########################################
# Do you want to run again?
ny = 0
if v == 0:    
    print """
Do you want to look up any else? (y/n)"""
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1


########################################
# Main Program - Restart
    if yn == "y":
        import os
        print """
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"""
        os.system('CAMain1.1.py')

########################################
# Main Program - End
    if yn == "n":
        print "Goodbye"
if v == 1:
    print "Goodbye"

Can you post as file or PM it to me, it's a litle messy to copy.

Cheers and Happy coding

Actually the first time I have ever seen this on DaniWeb, you are using CODE as part of your script which messes up the code tags. You may want to consider renaming all CODE references to CODE or such.

Thats not complicated. If there is a fixed code lenght you can call them like:

codeA, codeB = CAcodes.split(' ')

and eliminate the for's.

EDIT: I'll read your code when I return.

I'm a little confused. Can I do that when codeA is defined by the 'for' loop. I am unsure because codeA helps split up the raw_input string into codes and into a list and then codeA are the segments of going through the list. codeA and codeB are not actual variables but 'for' loop stand in variables.

Thanks.

Actually the first time I have ever seen this on DaniWeb, you are using [B][code][/B] as part of your script which messes up the code tags. You may want to consider renaming all code references to code1 or such.

Hmmm. Well unless I am missing anything everything in my script is labeled codeA, codeB, or CAcode. If you see any named 'code' please alert me. Also, if you think that just renaming them to something completely different to reduce confusion, please let me know.

Can you post as file or PM it to me, it's a litle messy to copy.

Cheers and Happy coding

Here is the file as a txt document.

Hmmm. Well unless I am missing anything everything in my script is labeled codeA, codeB, or CAcode. If you see any named 'code' please alert me. Also, if you think that just renaming them to something completely different to reduce confusion, please let me know.

Actually I found a few. Thank you for alerting me.

I solved my own problem. I changed the script to functions instead of loops and then if statements. So here is the code one last time.

Thanks to everyone that helped!

########################################
# Functions
def check(str):
    import urllib
    import urllib2
    from urllib2 import urlopen

    url = urldict[str]
    response = urllib2.urlopen(url)
    html = response.read()

    values = {'Spots Available' : '' }

    user_agent = 'Mozilla/5.0(compatible;MSIE 5.5;Windows NT)'
    headers = {'User-Agent': user_agent}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    split_page = the_page.splitlines()

    from BeautifulSoup import BeautifulSoup
    html = the_page
    soup = BeautifulSoup(''.join(html))

    CRFP = "Spots Available:"
    S = "Total Enrolled:"
    x = 999
    d = 0
    f = 999
    lines = html.splitlines()
    L = ""
    if channeldict[str] == ("XCR"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("F"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("P"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    L = int(L)
    return L

def codegen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0 
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    codelist = []
    for col in range(col_idx_max+1):
        if col == 0:
            codelist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                codelist[col].append(int(float(vdict[(row,col)])))
    return codelist

def channelgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime  
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    channellist = []
    for col in range(col_idx_max+1):
        if col == 1:
            channellist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                channellist[col-1].append(vdict[(row,col)])
    return channellist

def caagen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    caalist = []
    for col in range(col_idx_max+1):
        if col == 2:
            caalist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                caalist[col-2].append(vdict[(row,col)])
    return caalist

def maxgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    maxlist = []
    for col in range(col_idx_max+1):
        if col == 3:
            maxlist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                maxlist[col-3].append(vdict[(row,col)])
    return maxlist

def urlgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    urllist = []
    for col in range(col_idx_max+1):
        if col == 4:
            urllist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                urllist[col-4].append(vdict[(row,col)])
    return urllist


########################################
# Decode Excel
alpha = 'codedatabase.xls'
beta = codegen(alpha)
gamma = channelgen(alpha)
delta = caagen(alpha)
epsilon = maxgen(alpha)
zeta = urlgen(alpha)

codelist = []
channellist = []
caalist = []
maxlist = []
urllist = []

for item in beta:
    for thing in item:
        codelist.append(thing)
for item in gamma:
    for thing in item:
        thing2 = str(thing)
        channellist.append(thing2)
for item in delta:
    for thing in item:
        thing2 = str(thing)
        caalist.append(thing2)
for item in epsilon:
    for thing in item:
        thing2 = int(thing)
        maxlist.append(thing2)
for item in zeta:
    for thing in item:
        thing2 = str(thing)
        urllist.append(thing2)


########################################
# Create Excel Dictionaries
channeldict = {}
caadict = {}
maxdict = {}
urldict = {}
size = len(codelist)
for i in range(0,size):
    item = codelist[i]
    item2 = channellist[i]
    channeldict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = caalist[i]
    caadict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = maxlist[i]
    maxdict[item] = (item2)
for i in range(0,size):
    item = codelist[i]
    item2 = urllist[i]
    urldict[item] = item2


########################################
# Other Functions
def available(str):
    course = str
    x = 0
    P = ""
    size4 = len(codelist)
    for code1 in codelist:
        if (caadict[code1]) == course:
            x = 1
    if x == 0:
        P = False
    elif x == 1:
        P = True
    return P

def clist(str):
    course = str
    courselist = []
    for code in codelist:
        if caadict[code] == course:
            courselist.append(code)
    return courselist

def enrolled(int):
    m = ""
    CAcode = int
    if channeldict[CAcode] == "X":
        m = "| " + str(CAcode) + " | Error:    | This is a CA exclusive class."
    elif urldict[CAcode] == "0.0":
        m = "| " + str(CAcode) + " | Error:    | There is no URL entered for that code."
    elif channeldict[CAcode] == "XCR":
        if caadict[CAcode] == "AMC8":
            m = "| " + str(CAcode) + " | Enrolled: | " + str(6 - check(CAcode))
        elif caadict[CAcode] == "ASC":
            m = "| " + str(CAcode) + " | Enrolled: | " + str((24 - ((check(CAcode)))))
        else:
            m = "| " + str(CAcode) + " | Enrolled: | " + str(((maxdict[CAcode])/2) - ((check(CAcode))))
    elif channeldict[CAcode] == ("F"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    elif channeldict[CAcode] == ("P"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    else:
        m = "| " + str(CAcode) + " | Enrolled: | Unknown. Check " + str(channeldict[CAcode]) + " website."
    size3 = len(m)
    add = 59 - size3
    for i in range(0,add):
        m = m + " "
    m = m + "|\n"
    return m

def courseprint(list):
    courselist = list
    size6 = len(courselist)
    courseprint = "------------------------------------------------------------\n"
    for code2 in courselist:
        m = str(enrolled(code2))
        courseprint = courseprint + m
    courseprint = courseprint + "------------------------------------------------------------"
    return courseprint

def codevalid(int):
    code3 = int
    if code3 in codelist:
        valid = True
    else:
        valid = False
    return valid

def urlvalid(int):
    code4 = int
    if urldict[code4] != "0.0":
        valid = True
    else:
        valid = False
    return valid



########################################
# Main Program - Start
v = 0
ny = 0
print "\nLook up individual CA code(s)? (y/n)"
yn = raw_input().lower()

if yn == "y":
    ny = 1
if yn == "n":
    ny = 1

while ny == 0:
    print "\nSorry, please enter 'y' or 'n'"
    yn = raw_input().lower()
    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

if yn == "y":
    while True:
        CAcode = []
        CAcodes1 = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes2 = CAcodes1.split()
        k = 0
        for codeA in CAcodes2:
            try:
                CAcode.append(int(codeA))
            except ValueError:
                print "\nSorry, '"+ str(codeA) + "' was not found. Please enter a valid CA code."
        for codeB in CAcode:
            if codevalid(codeB) == False:
                print  "\nSorry, "+ str(codeB) + " was not found. Please enter a valid CA code."
            elif codevalid(codeB) == True:
                if urlvalid(codeB) == False:
                    print "\nError: There is no URL entered for " + str(codeB) + "."
                elif urlvalid(codeB) == True:
                    k += 1
        if k == len(CAcodes2):
            break
    print ""
    print courseprint(CAcode)

if yn == "n":
    ny = 0
    print "\nDo you want to search by course name? (y/n)"
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1

    if yn == "y":
        course = str(raw_input("\nEnter class name: (ex: PPSCCS) ")).upper()
        while available(course) == False:
            print "\nSorry, that acronym does not exist. Please try another."
            course = str(raw_input().upper())
            if available(course) == True:
                break
        if available(course) == True:
            courselist = clist(course)
            print "\n", course
            print courseprint(courselist)

    if yn == "n":
        ny = 0
        yn = ""
        print "\nCheck enrollment for the quarter? (y/n)"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1
        while ny == 0:
            print "\nSorry, please enter 'y' or 'n'"
            yn = raw_input().lower()
            if yn == "y":
                ny = 1
            if yn == "n":
                ny = 1
        if yn == "y":
            alpha = 'database.xls'
            beta = codegen(alpha)
            codelist = []
            for item in beta:
                for thing in item:
                    codelist.append(thing)
            x = 0
            out = open('enrollment.txt', 'w')
            import datetime
            r = datetime.datetime.now()
            q = "\nUpdated:" + str(r) + "\n\n"
            q = q + str(courseprint(codelist))
            out.write(q)
            out.close()
            print "\nTable was printed to the file: 'enrollment.txt'"
            v = 1
        if yn == "n":
            print "\nWell in that case..."

########################################
# Do you want to run again?
ny = 0
if v == 0:    
    print """
Do you want to look up any else? (y/n)"""
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1


########################################
# Main Program - Restart
    if yn == "y":
        import os
        print """
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"""
        os.system('CAMain1.1.py')

########################################
# Main Program - End
    if yn == "n":
        print "Goodbye"
if v == 1:
    print "Goodbye"

########################################
# Previous Scripts

##print soup.prettify()

##import pyExcelerator
##print dir(pyExcelerator)

Funny reaction to code continue, I change the variable to codevalue in that function, hope I did not mess up your code!

Can not run your code of course without the needed files:

IOError: [Errno 2] No such file or directory: 'codedatabase.xls'

########################################
# Functions
def check(str):
    import urllib
    import urllib2
    from urllib2 import urlopen

    url = urldict[str]
    response = urllib2.urlopen(url)
    html = response.read()

    values = {'Spots Available' : '' }

    user_agent = 'Mozilla/5.0(compatible;MSIE 5.5;Windows NT)'
    headers = {'User-Agent': user_agent}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    split_page = the_page.splitlines()

    from BeautifulSoup import BeautifulSoup
    html = the_page
    soup = BeautifulSoup(''.join(html))

    CRFP = "Spots Available:"
    S = "Total Enrolled:"
    x = 999
    d = 0
    f = 999
    lines = html.splitlines()
    L = ""
    if channeldict[str] == ("XCR"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("F"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    if channeldict[str] == ("P"):
        for line in lines:
            if CRFP in line:
                x = d
            d += 1
        e = 0
        for line in lines:
            if e == x:
                L = line.strip()
                L = L.strip('<BR><BR><B>Spots Available:</B>&nbsp;')
            e += 1
    L = int(L)
    return L

def codegen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0 
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    codelist = []
    for col in range(col_idx_max+1):
        if col == 0:
            codelist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                codelist[col].append(int(float(vdict[(row,col)])))
    return codelist

def channelgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime  
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    channellist = []
    for col in range(col_idx_max+1):
        if col == 1:
            channellist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                channellist[col-1].append(vdict[(row,col)])
    return channellist

def caagen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    caalist = []
    for col in range(col_idx_max+1):
        if col == 2:
            caalist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                caalist[col-2].append(vdict[(row,col)])
    return caalist

def maxgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    maxlist = []
    for col in range(col_idx_max+1):
        if col == 3:
            maxlist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                maxlist[col-3].append(vdict[(row,col)])
    return maxlist

def urlgen(fname, worksheet=1,encoding='cp1251'):
    from pyExcelerator import parse_xls, Workbook, Cell, Column, Row, Worksheet
    from datetime import datetime 
    data = parse_xls(fname,encoding) 
    values = data[worksheet-1][1] 
    vdict = {} 
    row_idx_max = 0 
    col_idx_max = 0
    for row_idx, col_idx in sorted(values.keys()):
        row_idx_max = max(row_idx,row_idx_max) 
        col_idx_max = max(col_idx,col_idx_max) 
        v = values[(row_idx, col_idx)] 
        vdict[(row_idx,col_idx)] = v
    urllist = []
    for col in range(col_idx_max+1):
        if col == 4:
            urllist.append([])
            for row in range(3,row_idx_max+1):
                if (row,col) not in vdict:
                    vdict[(row,col)]=None
                urllist[col-4].append(vdict[(row,col)])
    return urllist


########################################
# Decode Excel
alpha = 'codedatabase.xls'
beta = codegen(alpha)
gamma = channelgen(alpha)
delta = caagen(alpha)
epsilon = maxgen(alpha)
zeta = urlgen(alpha)

codelist = []
channellist = []
caalist = []
maxlist = []
urllist = []

for item in beta:
    for thing in item:
        codelist.append(thing)
for item in gamma:
    for thing in item:
        thing2 = str(thing)
        channellist.append(thing2)
for item in delta:
    for thing in item:
        thing2 = str(thing)
        caalist.append(thing2)
for item in epsilon:
    for thing in item:
        thing2 = int(thing)
        maxlist.append(thing2)
for item in zeta:
    for thing in item:
        thing2 = str(thing)
        urllist.append(thing2)


########################################
# Create Excel Dictionaries
channeldict = {}
caadict = {}
maxdict = {}
urldict = {}
size = len(codelist)
for i in range(0,size):
    item = codelist[i]
    item2 = channellist[i]
    channeldict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = caalist[i]
    caadict[item] = item2
for i in range(0,size):
    item = codelist[i]
    item2 = maxlist[i]
    maxdict[item] = (item2)
for i in range(0,size):
    item = codelist[i]
    item2 = urllist[i]
    urldict[item] = item2


########################################
# Other Functions
def available(str):
    course = str
    x = 0
    P = ""
    size4 = len(codelist)
    for code1 in codelist:
        if (caadict[code1]) == course:
            x = 1
    if x == 0:
        P = False
    elif x == 1:
        P = True
    return P

def clist(str):
    course = str
    courselist = []
    for codevalue in codelist:
        if caadict[codevalue] == course:
            courselist.append(codevalue)
    return courselist

def enrolled(int):
    m = ""
    CAcode = int
    if channeldict[CAcode] == "X":
        m = "| " + str(CAcode) + " | Error:    | This is a CA exclusive class."
    elif urldict[CAcode] == "0.0":
        m = "| " + str(CAcode) + " | Error:    | There is no URL entered for that code."
    elif channeldict[CAcode] == "XCR":
        if caadict[CAcode] == "AMC8":
            m = "| " + str(CAcode) + " | Enrolled: | " + str(6 - check(CAcode))
        elif caadict[CAcode] == "ASC":
            m = "| " + str(CAcode) + " | Enrolled: | " + str((24 - ((check(CAcode)))))
        else:
            m = "| " + str(CAcode) + " | Enrolled: | " + str(((maxdict[CAcode])/2) - ((check(CAcode))))
    elif channeldict[CAcode] == ("F"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    elif channeldict[CAcode] == ("P"):
        m = "| " + str(CAcode) + " | Enrolled: | " + str((maxdict[CAcode]) - ((check(CAcode))))
    else:
        m = "| " + str(CAcode) + " | Enrolled: | Unknown. Check " + str(channeldict[CAcode]) + " website."
    size3 = len(m)
    add = 59 - size3
    for i in range(0,add):
        m = m + " "
    m = m + "|\n"
    return m

def courseprint(list):
    courselist = list
    size6 = len(courselist)
    courseprint = "------------------------------------------------------------\n"
    for code2 in courselist:
        m = str(enrolled(code2))
        courseprint = courseprint + m
    courseprint = courseprint + "------------------------------------------------------------"
    return courseprint

def codevalid(int):
    code3 = int
    if code3 in codelist:
        valid = True
    else:
        valid = False
    return valid

def urlvalid(int):
    code4 = int
    if urldict[code4] != "0.0":
        valid = True
    else:
        valid = False
    return valid



########################################
# Main Program - Start
v = 0
ny = 0
print "\nLook up individual CA code(s)? (y/n)"
yn = raw_input().lower()

if yn == "y":
    ny = 1
if yn == "n":
    ny = 1

while ny == 0:
    print "\nSorry, please enter 'y' or 'n'"
    yn = raw_input().lower()
    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

if yn == "y":
    while True:
        CAcode = []
        CAcodes1 = str(raw_input("\nEnter CA Codes (separated by a space): "))
        CAcodes2 = CAcodes1.split()
        k = 0
        for codeA in CAcodes2:
            try:
                CAcode.append(int(codeA))
            except ValueError:
                print "\nSorry, '"+ str(codeA) + "' was not found. Please enter a valid CA code."
        for codeB in CAcode:
            if codevalid(codeB) == False:
                print  "\nSorry, "+ str(codeB) + " was not found. Please enter a valid CA code."
            elif codevalid(codeB) == True:
                if urlvalid(codeB) == False:
                    print "\nError: There is no URL entered for " + str(codeB) + "."
                elif urlvalid(codeB) == True:
                    k += 1
        if k == len(CAcodes2):
            break
    print ""
    print courseprint(CAcode)

if yn == "n":
    ny = 0
    print "\nDo you want to search by course name? (y/n)"
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1

    if yn == "y":
        course = str(raw_input("\nEnter class name: (ex: PPSCCS) ")).upper()
        while available(course) == False:
            print "\nSorry, that acronym does not exist. Please try another."
            course = str(raw_input().upper())
            if available(course) == True:
                break
        if available(course) == True:
            courselist = clist(course)
            print "\n", course
            print courseprint(courselist)

    if yn == "n":
        ny = 0
        yn = ""
        print "\nCheck enrollment for the quarter? (y/n)"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1
        while ny == 0:
            print "\nSorry, please enter 'y' or 'n'"
            yn = raw_input().lower()
            if yn == "y":
                ny = 1
            if yn == "n":
                ny = 1
        if yn == "y":
            alpha = 'database.xls'
            beta = codegen(alpha)
            codelist = []
            for item in beta:
                for thing in item:
                    codelist.append(thing)
            x = 0
            out = open('enrollment.txt', 'w')
            import datetime
            r = datetime.datetime.now()
            q = "\nUpdated:" + str(r) + "\n\n"
            q = q + str(courseprint(codelist))
            out.write(q)
            out.close()
            print "\nTable was printed to the file: 'enrollment.txt'"
            v = 1
        if yn == "n":
            print "\nWell in that case..."

########################################
# Do you want to run again?
ny = 0
if v == 0:    
    print """
Do you want to look up any else? (y/n)"""
    yn = raw_input().lower()

    if yn == "y":
        ny = 1
    if yn == "n":
        ny = 1

    while ny == 0:
        print "\nSorry, please enter 'y' or 'n'"
        yn = raw_input().lower()
        if yn == "y":
            ny = 1
        if yn == "n":
            ny = 1


########################################
# Main Program - Restart
    if yn == "y":
        import os
        print """
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"""
        os.system('CAMain1.1.py')

########################################
# Main Program - End
    if yn == "n":
        print "Goodbye"
if v == 1:
    print "Goodbye"

########################################
# Previous Scripts

##print soup.prettify()

##import pyExcelerator
##print dir(pyExcelerator)[/CODE]
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.