Use of a variable in parent loop

Chris Angelico rosuav at gmail.com
Sat Sep 26 04:38:32 EDT 2020


On Sat, Sep 26, 2020 at 4:01 PM Stephane Tougard via Python-list
<python-list at python.org> wrote:
>
>
> Hello All,
>
> I've been working with Perl a long time and recently started to use
> Python. I've been surprised by one behavior of Python.
>
> In Perl:
>
> ===PERL===
> #!/usr/pkg/bin/perl
>
> use strict;
>
> if(4 == 4)
> {
>     my $name = "Stephane";
>     print("$name\n"
> }
> print("Out $name\n");
> =========
>
> This code will trigger an error because $name is declared inside the if
> and is not usable outside of the block code. That looks logic to me.
>
> ===PYTHON===
> #!/usr/local/bin/python
> if 4 == 4:
>     name = "Stephane"
>     print(name)
>     pass
>
> print("Out {}".format(name))
> ============
>
> The exact same code in Python works fine, the variable name is used
> outside of the if block even it has been declared inside.
>
> This does not look right to me. Can we change this behavior or is there
> any point to keep it this way ?

Just to get this part out of the way: No, that behaviour won't change. :)

The distinction is that, in Python, you didn't declare the variable at
all. It's not like C where you have to declare everything, and the
place it's declared defines the scope; in Python, variables generally
*aren't* declared, and there are a small number of cases where you
declare that something's a global when it would otherwise be local.
But for the most part, Python's default rules handle the situations
admirably.

Most variables are either global (if you assign something outside of
any function) or local (inside a function). There's no concept of
scoping a variable to just a single 'if' statement, so you don't have
to worry about it disappearing prematurely.

ChrisA


More information about the Python-list mailing list