Posts

Showing posts from June, 2018

Python: Scope

Global variables are confusing and the use should be avoided. If the variable is defined elsewhere, tracing the use of the variables gets hard and gets even harder for larger projects. The variable scope of Python is not as 'strict' as in C. The variables within for-loop are not shielded. If assigned a value outside the loop, the variable within the loop will be affected. a = 0 for i in range( 0 , 1 ) : a = 1 print (a) On the other hand, the variables within a function are shielded. If the variables should be shared outside the scope of the function, global keyword specifies that the variable values are shared. def func (): global a a = 0 a = 1 func() print (a)