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,090 points

edited Dec 17, 2018 by Anirudh 717 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,560 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 aryya
• 7,460 points
926 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
• 58,020 points
835 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,720 points
1,183 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
• 13,300 points
962 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,464 views
0 votes
1 answer
0 votes
1 answer
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, 2019 in Python by Nymeria
• 3,560 points
967 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP