continue/else functionality

William Park parkw at better.net
Mon Mar 12 15:45:06 EST 2001


On Mon, Mar 12, 2001 at 05:27:39PM -0300, Chris Richard Adams wrote:
> I have a script that reads lines out of a text file. The first line in
> the file serves as a "flag-line" stating whether or not the file should
> be read: 1 yes, 0 no. The rest of the file contains data lines to be
> read. How can I get my script to read on the first line and upon getting
> a 1 go back to the for, get the next line and read the rest from there?
> For example, I tried:
> 
> 
> 	for line in f.readlines():
> 
> 	    datalist = string.split(line)
>           if datalist[0][0] == 1:
>              continue
>           elif datalist[0][0] == 0:
>              break
> 	    
> 	    ## Do a bunch of string manipulation here...

As it is written, you're checking first non-whitespace
character on every line.  If it's 1, you read next line; if it's 0, you
exit the loop; only if it's neither 1 or 0, do you go down further.

Solution:
    Check the first line.  Then, do the loop for 2nd, 3rd, ... lines.
    You may want to check for '1' or '0' (ie. entire string) instead of
    '1...' or '0...' (ie. first character of string).

---William Park, Open Geometry Consulting, Linux/Python, 8 CPUs.




More information about the Python-list mailing list