Python scoping

Chris Angelico rosuav at gmail.com
Mon Jun 20 18:52:22 EDT 2011


On Tue, Jun 21, 2011 at 8:35 AM, gervaz <gervaz at gmail.com> wrote:
> Hi all, can you explain me why this simple function works well (i.e. I
> can call the print function using txt) in py
>
>>>> def test(value):
> ...     if value%5: txt = "hello"
> ...     else: txt = "test"
> ...     print(txt)

It's as though you had "PyObject txt;" at the top of the function. The
scope is the function. There's no way (afaik) to make a variable be
local to a portion of the function - that's a feature that has to be
sacrificed to the simplicity of not declaring variables.

In my opinion it's better to declare them, except in interactive code
(eg IDLE or just typing "python"). But Python isn't that.

Chris Angelico



More information about the Python-list mailing list