[OT] Re: Variable scoping rules in Python?
Peter Otten
__peter__ at web.de
Mon Oct 8 13:03:13 EDT 2007
joshua.davies wrote:
> Ok, I'm relatively new to Python (coming from C, C++ and Java). I'm
> working on a program that outputs text that may be arbitrarily long,
> but should still line up, so I want to split the output on a specific
> column boundary. Since I might want to change the length of a column,
> I tried defining the column as a constant (what I would have made a
> "#define" in C, or a "static final" in Java). I defined this at the
> top level (not within a def), and I reference it inside a function.
> Like this:
>
> COLUMNS = 80
>
> def doSomethindAndOutputIt( ):
> ...
> for i in range( 0, ( len( output[0] ) / COLUMNS ) ):
> print output[0][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> print output[1][ i * COLUMNS : i * COLUMNS + ( COLUMNS - 1 ) ]
> ..
>
> etc. etc. It works fine, and splits the output on the 80-column
> boundary just like I want.
Just in case it's not intentional: You'll lose every 80th character as
python intervals do not include the upper bound. The same problem
affects the for loop -- e. g. when output[0] has less than COLUMNS
columns nothing is printed:
>>> range(0, 79/80)
[]
Peter
More information about the Python-list
mailing list