Why do variables have bigger scopes in Python than in C

0 votes

Here is a Python code:

for i in xrange(10):
    for j in xrange(5):
        pass

# The for-loop ends, but i,j still live on
print i,j  # 9, 4

And the same for C code:

for(int i=0; i<=10; i++)
    for(int =0; j<=5; j++)
        ;

// The for-loop ends, so i,j can't be accessed, right?
printf("%d, %d", i, j);  // won't compile

Do variables in Python live on even after the for loop ends?

Jul 2, 2019 in Python by ana1504.k
• 7,910 points
1,017 views

1 answer to this question.

0 votes

Only functions, modules, and the bodies of class definitions delineate scopes in Python. Other control structures don't.

Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:

  • the innermost scope, which is searched first, contains the local names
  • the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
  • the next-to-last scope contains the current module’s global names
  • the outermost scope (searched last) is the namespace containing built-in names
answered Jul 2, 2019 by SDeb
• 13,300 points

Related Questions In Python

0 votes
1 answer

Why is reading lines from stdin much slower in C++ than Python?

tl;dr: Because of different default settings in ...READ MORE

answered Dec 18, 2020 in Python by Nikita
1,213 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

If you're already normalizing the inputs to ...READ MORE

answered May 29, 2018 in Python by aryya
• 7,460 points
10,637 views
0 votes
1 answer

Why there is no do while loop in python

There is no do...while loop because there ...READ MORE

answered Aug 6, 2018 in Python by Priyaj
• 58,100 points
7,608 views
0 votes
1 answer

How do you get the logical xor of two variables in Python?

What i found is that you can use ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 58,100 points
11,666 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,391 views
0 votes
1 answer
0 votes
1 answer

Print C format in Python

For printf- style formatting and special case ...READ MORE

answered Sep 18, 2018 in Python by SDeb
• 13,300 points
981 views
0 votes
1 answer

What does the return statement do in Python?

The print() function is use to write ...READ MORE

answered Oct 1, 2018 in Python by SDeb
• 13,300 points
1,342 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