我猜测以下两个代码的差异。第一个是 python ,工作得很好。这就是:
>>> 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
第二个是c,我想我想要实现这两个程序的方式是一样的。这就是:
void main(){
if(1){
printf("this is working");
int n=9;
}
printf("the value of n is %d",n);
}
n
在 c 代码中显示undeclared
,而在 python 中效果良好。
我知道在 c 代码中n
的范围在if block
范围内。但为什么 python 中没有这样的范围问题。块{ }
内的变量是否存储在 c 中的不同memory stacks
中,而 python 中的变量存储在function's memory stack
?中。如果我错在某处,请纠正我。
问候。
答案 0 :(得分:2)
在python中,局部变量是函数范围的一部分。 if
块(以及其他此类块)没有自己独立的范围。