Scoping in Python 'For' Loops

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

Python scoping rules in nested for loops

This is not a scope issue. The issue is that when you assign primenumber = False inside the for loop, that assignment happens every time you go through the loop. It resets the value to False every time.

When you assign primenumber = False above the loop, it only gets assigned that way once, so primenumber remains True after the first time it's set to True.

Also, primenumber is a terrible name for a variable that indicates whether a number is composite.

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 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

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


Related Topics



Leave a reply



Submit