[Tutor] Code Dosent work.

Lie Ryan lie.1296 at gmail.com
Mon May 4 07:40:39 CEST 2009


David wrote:
> Jacob Mansfield wrote:
>> hi everyone, I'm a bit new here but i was wondering if someone could 
>> check some of my code, it's not doing quite what it's meant to.
>> thanks
> 
> Why were you using pygame?
> 

The only line that uses pygame is pygame.time.delay(900). It is an 
overkill to import pygame just to put delay. Especially when it is 
possible to do the same thing with standard lib.

import time
time.sleep(0.9)

Now on to what you should know:
1) pythons' file.readline(x) reads until the end of line returning at 
most x bytes (it could return less than x bytes if it sees a newline). 
The x argument is not linenumber.
2) The problem starts from your "save" function. Look at your data file, 
it does not have line ending.

change the while block inside exitprog() function with:

     while ins > x :
         dac = databox[x]
         dac2 = databox2[x]
         x = x + 1
         fic.write(dac + ' ' + dac2 + '\n')

also, change this while block in the load():

         while dec != '':
             num = str(e)
             print "found " + num + " enteries"
             dec = fic.readline(e)
             databox[e] = dec
             dec = fic.readline((e+1))
             databox2[e] = dec
             e = e+1

with:

         for e, line in enumerate(fic):
             databox[e+1], databox2[e+1] = line.split()
             print "found" + str(e) + "entries"

Also, these minor things bothers me:
1) For databox and databox2, it is unnecessary to use dict. A list() or 
set() should serve you better (and is simpler than dict).
2) You have databox and databox2, which is a parallel container for each 
other. Keeping them in sync is going to be a mess. Rather you should use 
a single databox which contains a 2-tuple.
3) time.sleep() can replace pygame.time.delay(), however while 
pygame.time.delay() is in milisecond, time.sleep is in seconds so use 
0.9 instead of 900.
4) In python, index number usually starts with 0, the ugly [e+1] code in 
the for loop I gave above is caused by the use of 1-based indexing in 
the rest of the code.
5) Use for loop, it's easier.



More information about the Tutor mailing list