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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With