Hey everyone. I would really appreciate some help. I'm currently building a program in Python 2.6 for an introductory Comp Sci class. The program is supposed to use functions to read a text file from a URL, parse the data into tokens, and use the data to calculate a sort of average 'course grade' for hypothetical students using the URL data.

This is all something I've done before, only I didn't use functions. Now that I'm using them, I'm running into errors and need help.

Specifically, when I try to run the program I get an error like this:

Traceback (most recent call last):
  File "C:\Users\Denis Walker\Documents\CSM\CSCI 101\CourseGradeFunctions.py", line 35, in <module>
    for li in lines[1:] :
TypeError: 'NoneType' object is unsubscriptable

Here is the code for what I have so far.

theURL = "http://inside.mines.edu/~khellman/teaching/csci101/qo/coursegrades.dat"

def download(theURL):
    import urllib2
    urlConnection = urllib2.urlopen( theURL )
    lines = urlConnection.readlines()
    print lines
    
def parse(li):
    theLine = lines[li]
    theTokens = theLine.split()
    theValues = []
    theValues.append( theTokens[0] )
    t = 1
    while t < len(theTokens) :
        theValues.append( float( theTokens[t] ) )
        t = t + 1

def courseGrade():
    CWID = theValues[0]
    fi = theValues[1]
    a = theValues[2]
    b = theValues[3]
    p = theValues[4]
    q = theValues[5]
    t = theValues[6]
    c = (p*.2 + q*.1 + a*.15 + b*.2 + fi*.25 + t*.1)
    print c
    
def printStudent( outfile, cg, scores ):
    f = file( "FunctionCourseGrades.txt", "a" )
    f.write("%-s %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f\n" % (CWID, c, fi, a, b, p, q, t))

lines = download(theURL)
for li in lines[1:] :
    scores = parse(1)
    cg = courseGrade(scores)
    printStudent( f, cg, scores )

f.close()
print "Please open FunctionCourseGrades.txt to see the listed scores including calculated course grades."

Recommended Answers

All 2 Replies

Your download function doesn't contain a return statement, which means that it doesn't return a value. So when you execute line 34, the variable "lines" is set to None. In line 35, when you try to select elements of Lines, the Python system tells you that you can't select elements of None.

If your goal is for download to return the value of the local variable "lines," which is completely distinct from the variable "lines" in line 34 of your program, then you need to put

return lines

at the end of your download function (appropriately indented, of course).

commented: good point +13
commented: on target +5

Thanks for the help, that was precisely the problem!

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.