Default scope of variables
Neil Cerutti
neilc at norwich.edu
Mon Jul 8 07:54:28 EDT 2013
On 2013-07-07, Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> On Fri, 05 Jul 2013 13:24:43 +0000, Neil Cerutti wrote:
>
>> for x in range(4):
>> print(x)
>> print(x) # Vader NOoooooOOOOOO!!!
>
> That loops do *not* introduce a new scope is a feature, not a bug. It is
> *really* useful to be able to use the value of x after the loop has
> finished.
I don't buy necessarily buy that it's "*really*" useful but I do
like introducing new names in (not really the scope of)
if/elif/else and for statement blocks.
z = record["Zip"]
if int(z) > 99999:
zip_code = z[:-4].rjust(5, "0")
zip4 = z[-4:]
else:
zip_code = z.rjust(5, "0")
zip4 = ""
As opposed to:
zip_code = None
zip4 = None
z = record["Zip"]
if int(z) > 99999:
zip_code = z[:-4].rjust(5, "0")
zip4 = z[-4:]
else:
zip_code = z.rjust(5, "0")
zip4 = ""
--
Neil Cerutti
More information about the Python-list
mailing list