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 in Python by ana1504.k
• 7,870 points
21 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 by SDeb
• 13,180 points

Related Questions In Python

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 ariaholic
• 7,340 points
3,639 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
• 56,900 points
162 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
• 56,900 points
945 views
0 votes
2 answers

Why do we use return statement in python?

def maximum(x, y):     if x > y:     ...READ MORE

answered Apr 4 in Python by anonymous
59 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 329 views
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,180 points
43 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,180 points
104 views