Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do variables live longer (have bigger scopes) in Python than in C?

Tags:

python

c

scope

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

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

So, variables in Python will live on even after the for loop ends?

like image 701
Alcott Avatar asked Feb 21 '23 19:02

Alcott


1 Answers

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

Some basic information about this is in the Python Scopes and Namespaces section of the Classes page of the Python Tutorial. One important part:

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
like image 94
agf Avatar answered Apr 27 '23 00:04

agf