Monday, April 26, 2021

Functions & Scopes - the "global" keyword

There's a special Python method which can extend a variable's scope in a way which includes the functions' bodies even if we want not only to read the values, but also to modify them.

This effect is caused by a keyword named "global".

Using this keyword inside a function with the name or names separated with commas of a variable(s), forces Python to refrain from creating a new variable inside the function - the one accessible from outside will be used instead.

In other words, this name becomes global. It has a global scope and it doesn't matter whether it's the subject of read or assign.


Look at the example given below.



Here the output is,


No comments:

Post a Comment