python newbie having strangeness

Paul McGuire ptmcg at users.sourceforge.net
Thu Feb 26 19:07:33 CET 2004


"Joe F. Blow" <dood at dood.com> wrote in message
news:of4s30p4a2nq964bjb0kcb25ocrv5kj2sk at 4ax.com...
> The program below has been acting very weird. Last night it complained
> that I was referencing X in getline() before defining it. Of course I
> wasn't, as X is a global.
>
> This morning I ran the exact same code again and now it says,
> "NameError: name 'convert' is not defined". HUH????? Of course it's
> defined!
>
> What am I doing wrong? Any ideas? I'm using pythonwin and python2.3 on
> windoze xp.
>
> --------------------------------------------------------------------------
--------
>
> x=1
> count=binlist=0
>
> #get s19 file in list named "line"
> inp=file("c:\\download\\electron\\68hc11\\a code\\tankbot2.s19","r")
> line = inp.read()
> inp.close()
>
> if line[x]=="0":            #is command char a "0"?
>     dig1=line[x+1]          #yes, get line length
>     dig2=line[x+2]
>     a=convert(dig1,dig2)
>     x=x+((a*2)+5)           #point to command char of next line
>
> if line[x]=="1":
>     getline()
> print binlist
>
> def getline():
>     global count
>     global x
>     global line
>     global binlist
>     dig1=line[x+1]
>     dig2=line[x+2]
>     a=convert(dig1,dig2)
>     x+=2
>     e=x
>     for e in range(e,e+a,2):
>         dig1=line[e+1]
>         dig2=line[e+2]
>         binlist[count]=convert(dig1,dig2)
>         count+=1
>
> #convert ascii hex digits x & y to an integer
> def convert(x,y):
>     a=int(x)
>     b=int(y)
>     a=a<<4
>     a=a+b
>     return(a)
>
Hey Joe -

Here are some keen Python features that might make your task easier:

file.readlines() - will give you each line of your file at a time, no need
to read it all at once (or even better, "for line in file('xyzzy.s19'):")
string slicing - line[x:x+2] will give you a 2-char substring at location x
hex to int conversion - int("0A",16) gives the value 10
list comprehensions (this is way cool!) - bytes = "AABBCCDD", bytelist = [
int(bytes[x:x+2],16) for x in range(0,len(bytes),2) ] results in a bytelist
containing [170, 187, 204, 221]

Python has been around a while, and before writing your own hex-to-int
conversion, it's worth trying to find a way to do it in the language.  Soon
you'll graduate from brute force range looping to list comprehensions.

Good luck with your S19 work.

-- Paul






More information about the Python-list mailing list