Scoping in Python 'for' loops
The likeliest answer is that it just keeps the grammar simple, hasn't been a stumbling block for adoption, and many have been happy with not having to disambiguate the scope to which a name belongs when assigning to it within a loop construct. Variables are not declared within a scope, it is implied by the location of assignment statements. The global
keyword exists just for this reason (to signify that assignment is done at a global scope).
Update
Here's a good discussion on the topic: http://mail.python.org/pipermail/python-ideas/2008-October/002109.html
Previous proposals to make for-loop
variables local to the loop have
stumbled on the problem of existing
code that relies on the loop variable
keeping its value after exiting the
loop, and it seems that this is
regarded as a desirable feature.
In short, you can probably blame it on the Python community :P
Scope of python variable in for loop
The for loop iterates over all the numbers in range(10)
, that is, [0,1,2,3,4,5,6,7,8,9]
.
That you change the current value of i
has no effect on the next value in the range.
You can get the desired behavior with a while loop.
i = 0
while i < 10:
# do stuff and manipulate `i` as much as you like
if i==5:
i+=3
print i
# don't forget to increment `i` manually
i += 1
How to create a local variable in a for loop
It is not possible to have loop variables in a scope other than the loop's scope, simply because the variable is defined in the same line/indentation as the for
loop. If the for
loop is in the global scope, then so too will the loop variable. However, if your limitation is only on global variables, the for
loop could be placed within a non-global scope, such as a function, like so:
def loop():
for x in range(0, 5):
...
This workaround, however, likely goes against the spirit of your assignment, so use with care.
As a note, this approach still creates a global variable, in this case a function, but whether or not that counts would likely depend on the semantics of the assignment. "Use with care" should more likely be "don't use at all."
Python variables scope in loops example
Assuming this code is in a function then the scope of the variables is to the end of the function. If this code is at module-level then the scope of the variables is the module (aka global) scope.
You don't have to use different names. The following code will merely assign different objects to the archive
variable at different times:
with ZipFile(self.archive_name, "r") as archive:
print(id(archive))
with ZipFile(self.archive_name, "r") as archive:
print(id(archive))
It's equivalent to this:
archive = ZipFile(self.archive_name, "r")
with archive:
print(id(archive))
archive = ZipFile(self.archive_name, "r")
with archive:
print(id(archive))
That is to say, the blocks associated with with
statements and loops don't define a scope so far as variables are concerned, they are "just" assignments. You should see two different values printed for the ids of the different objects.
Beware that since your sample code uses id
as a variable name, my example using the built-in function id
should be used with care!
Are there any good-practice concerns to keep in mind?
At risk of straying into opinionated territory:
- You rarely use the value of a loop variable outside the loop. So it's usually fine to use the same loop variable again in a new loop later in the function, but in general you should examine all uses of that variable name in the function before using it again, to be sure. For module-level code this is even worse: before adding the second loop you'd need to make sure that no external users of your module are relying on the variable having the value that the first loop left in it.
- Unless the object is serving the exact same role in the two different places, then although it's safe to re-use a variable later in the function it can still be a little confusing.
- Obviously before copy-pasting code twice into a function you want to be reasonably sure that in your particular case, repetition (presumably with some changes) really is better than defining another function and calling it twice.
Scope of variables in Python when using for loop
You are saying that
sub == temp
Remember that the "==" operator is for comparison, NOT for assignment. You are comparing sub and temp instead of assigning. Use
sub = temp
Python variable declared in 'for' loop not seen outside of loop
It could be very likely that your loop never went into the if statement and hence Foo was never initialized.
You need to initialize it before the loop just to make sure that if that conditional is never met, you have something to print.
Related Topics
"Ssl Module in Python Is Not Available" When Installing Package with Pip3
Custom Sorting in Pandas Dataframe
Are Python Variables Pointers? or Else, What Are They
Security of Python's Eval() on Untrusted Strings
Generate Random Integers Between 0 and 9
How to Run Multiple Python Versions on Windows
How to Urlencode a Querystring in Python
Using Pandas to Pd.Read_Excel() for Multiple Worksheets of the Same Workbook
How to Keep Python Print from Adding Newlines or Spaces
Apply Function to Each Element of a List
Having Django Serve Downloadable Files
Setting Y-Axis Limit in Matplotlib
How Does Zip(*[Iter(S)]*N) Work in Python
How to Subtract a Day from a Date
Import CSV File as a Pandas Dataframe
Append Multiple Pandas Data Frames at Once
How to Remove the Ansi Escape Sequences from a String in Python