Why is Python scoping made the way it is?

0 votes

I understand generally how scoping works in Python for loops. My question is why the design decisions were made in this way. For example:

for foo in xrange(10):
    bar = 2
print(foo, bar)

The above will print (9,2).

T'foo' is really just controlling the loop, and 'bar' was defined inside the loop. I can understand why it might be necessary for 'bar' to be accessible outside the loop (otherwise, for loops would have very limited functionality). 

What I don't understand is why it is necessary for the control variable to remain in scope after the loop exits. I'd appreciate if anyone threw some light at this!

Nov 5, 2018 in Python by Anirudh
• 2,060 points

edited Dec 17, 2018 by Anirudh 24 views

1 answer to this question.

0 votes

The likeliest answer is that it just to keep the grammar simple.

It 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).

answered Nov 5, 2018 by Nymeria
• 3,500 points

edited Dec 17, 2018 by Nymeria

Related Questions In Python

0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

950down voteaccepted It's because any iterable can be ...READ MORE

answered May 15, 2018 in Python by ariaholic
• 7,320 points
29 views
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 56,160 points
56 views
0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,710 points
64 views
0 votes
1 answer

Is arr.__len__() the preferred way to get the length of an array in Python?

my_list = [1,2,3,4,5,6,7] len(my_list) # 7 The same works for ...READ MORE

answered Oct 8, 2018 in Python by SDeb
• 12,440 points
44 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 134 views
0 votes
1 answer

What is the recommended way to randomize a list of strings using Python?

Hi. Nice question. Here is the simplified answer ...READ MORE

answered Jan 18 in Python by Nymeria
• 3,500 points
38 views