1

I am guessing differences in the following two codes. The first one is in python and works just fine.Here it is:

>>> def foo():
        if 1:
            print "this is working"
            n=6 
        print "the value of n is {0}".format(n)


>>> foo()
this is working
the value of n is 6

The second one is in c, i guess the way i want to implement both programs is same.Here it is:

void main(){
    if(1){
        printf("this is working");
        int n=9;
    }
    printf("the value of n is %d",n);
}

n goes undeclared in the c code while it works good in python. I know that in the c code n has scope within the if block.But why there is no as such scope issue in python. Do the variables inside a block { } are stored in different memory stacks in c while in python they are stored in function's memory stack ?.Correct me if i am wrong somewhere. Regards.

darxtrix
  • 2,032
  • 2
  • 23
  • 30
  • "memory stack" isn't an actual term in either C or Python. There is (conceptually) only one stack per thread in either language, no matter what functions you call or what variables with what scopes you use. – user2357112 Apr 02 '14 at 09:58
  • I suggest reading [PEP 3104](http://legacy.python.org/dev/peps/pep-3104/#rationale). This is as close as you will get to an answer to your question. – Michael Foukarakis Apr 02 '14 at 09:59
  • In your C example the variable n has "block scope" i.e. it does not exist outside of the curly braces – CatsLoveJazz Apr 02 '14 at 10:02
  • @unwind, the other question pointed out by you was useful.Thanks for that.But it does not relate totally to my case, have a look again. – darxtrix Apr 02 '14 at 10:32

1 Answers1

2

In python, a local variable is part of the function's scope. if blocks (and other such blocks) do not have their own separate scope.

Lee White
  • 3,649
  • 8
  • 37
  • 62