如果只是对全局变量引用,则不同声明global, 但是如果涉及到对全局变量的修改,则需要声明gloabl
上图表明,不用声明也能引用
上图表明,当修改global值时,会报错。
上图表明,当声明global时,程序正确。
而 nonlocal 在嵌套函数中具有同global类似的作用
上图表明,单纯引用 var6 没问题
上图表明,当修改局部变量的值时,没有nonlocal 会报错
上图表明,加上nonlocal 时,程序正常。
但是C不存在这个问题
#include<stdio.h> int a = 10; int main() { a += 1 ; printf("%d",a); getchar(); return 0; } // 在python 中不能修改全局变量
这段代码可以正常运行。