Newbie NameError problem

MartinRinehart at gmail.com MartinRinehart at gmail.com
Wed Dec 12 11:26:13 EST 2007


I don't understand what I don't understand in the following:
------------------------------------------
# reader.py - testing char-by-char marching methods

f = open('sample_decaf.d', 'r')
text = f.readlines()
f.close()

# this is C-style, 15 lines, in Python:
end_line = len(text)
line_ptr = 0

while line_ptr < end_line:

    input = text[line_ptr]
    output = ''
    char_ptr = 0
    end_char = len(input)

    while char_ptr < end_char:
        output += input[char_ptr]
        char_ptr += 1

    print output,
    line_ptr += 1

# this is Python, 7 lines:

for line in text:
    output = ''

    for char in line:
        output += char

    print output,

# but I need locations, so this is impure, 11-line, Python:

line_ptr = 0
for line in text:
    output = ''
    char_ptr = 0

    for char in line:
        output += char
        char_ptr += 1

    print output,
    line_ptr += 1

# with a Loc object, 10 lines (not counting the Loc class):

loc = Loc(0,0) # Name error: name 'Loc' is not defined
for line in text:
    output = ''

    for char in line:
        output += char
        loc.nextChar()

    print output + Loc.repr(),
    loc.nextLine()

class Loc:
    line = 0
    char = 0

    def __init__(self, l, c):
        line = l
        char = c

    def nextChar(self):
        char += 1

    def nextLine(self):
        line += 1
        char = 0

    def repr(self):
        return 'Loc: line='+str(line)+', char='+str(char)

# end of class Loc

# end of reader.py



More information about the Python-list mailing list