Use of a variable in parent loop
Joel Goldstick
joel.goldstick at gmail.com
Sat Sep 26 03:48:12 EDT 2020
On Sat, Sep 26, 2020 at 2:01 AM 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 ?
> --
> https://mail.python.org/mailman/listinfo/python-list
It looks like perl creates a local namespace inside the code suite of
the if statement. Python namespace is function based.
--
Joel Goldstick
http://joelgoldstick.com/blog
http://cc-baseballstats.info/stats/birthdays
More information about the Python-list
mailing list