problem with variable scoping
Hans Nowak
ivnowa at hvision.nl
Wed May 26 17:14:50 EDT 1999
On 26 May 99, Michael Dingler wrote:
> It's...
>
> an embarassing question. Yes folks, I'm writing my first
> Python program (a text to HTML converter) and I have a
> slight misunderstanding with the variable scoping...
>
> Let me present some code fragments:
>
> last_line_empty = 0
> .
> .
> .
> def process(line):
> ...
> if last_line_empty:
> pass
> else:
> print "<P>"
> last_line_empty = 1
Add this line
global last_line_empty
as the first line in your process function. Python's scoping is
different from, say, C's. Let's say I have this code:
x = 1
def p():
x = 2
then the x in function p is considered *local*. A similar construct
in C or Pascal would access the global variable x; not so in Python.
If you want to change this behavior, you can use the global
specifier. So this:
def q():
global x
x = 2
*would* access global variable x.
I'll be darned if this isn't in the FAQ somewhere. :o) [looks it up]
Try questions 4.36 and 4.57. They pretty much deal with this problem.
It used to bite me too when I started with Python.
Veel liefs,
--Hans Nowak (ivnowa at hvision.nl)
Homepage: http://fly.to/zephyrfalcon
More information about the Python-list
mailing list