[Tutor] IndexError and appending to lists [Was: Re: Need Helpon Assignment]

Tom Strickland tlinux at comcast.net
Thu Aug 25 02:26:43 CEST 2005


Alan,

Thanks for your comments. I see how I can simplify my code, but I've run 
into a problem trying to do so. If I replace the "while" loop with a 
"for" loop as you suggest, the program won't enter the loop unless "s" 
is initialized so that it's in "input". How do I do that?

Also, near the end of your remarks you say that the code at the bottom 
of my program doesn't do anything. It does for me. Since I'm trying to 
learn Python, I'm not too sure that what I'm doing is correct. Thus, I 
put in those print statements to verify that the contents of those 
variables are what I expected them to be. That's all that mess is for.

Thanks for your help and Danny's too!

Tom


Alan G wrote:

> Hi Tom,
>
> Glad you got it working with Danny's help.
>
> I'll throw in some style points too.
>
>> input = open('/home/tom/Python/Input/SPY3.txt', 'r')
>
>
>> N=0
>> s = 'boo'
>> while s:
>>    s = input.readline()
>>    if s == '':break
>
>
> You might find it easier to use a for loop.
>
> you could for example use
>
> for s in input:
>
>
> to replace most of the above code and, in the process, eliminate the 
> need for N completely, see below...
>
>
>>    s = s[:-2]
>>    T[N] = s.split(',')
>
>
> Since you are using append elsewhere why not for T too?
> And if you store the split result in a local value before putting it 
> into T you can use that variable in all the following appends to save 
> indexing T...
>
>>    date.append(T[N][0])
>>    open.append(float(T[N][1]))
>>    hi.append(float(T[N][2]))
>>    lo.append(float(T[N][3]))
>>    close.append(float(T[N][4]))
>>    vol.append(float(T[N][5]))
>
>
>>    N+=1
>
>
> And with the for loop you don;t need to increment N either.
>
>> print N
>> for i in range(N):
>
>
> And you can use len(T) to replace N here.
>
>>    T[i]
>
>
> This doesn't do anything! :-)
>
>>    print T[i]
>>    print date[i], open[i], hi[i], lo[i], close[i], vol[i]
>> print T[1][2], T[0][0]
>> z = (hi[2] +lo[2])/2.0
>> print z
>
>
> HTH,
>
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>




More information about the Tutor mailing list