What is the use of Global
keyword
The global
keyword is used to declare that a variable inside a function refers to a variable defined in the global scope—outside the function. Without it, Python treats variables assigned inside a function as local by default.
Each function runs in its own scope. Any changes made in it are confined within the scope of the function.
Hence, if a variable name is declared outside the function and is later modified inside the function, the modifications made inside the function will not reflect in the variable declared outside the function.
This functions similar to having a secret-lingo within friends. Outside the friends circle the same secret-lingo will not be shared. Modification to outer variables inside the functions also work in a similar way.
🔍 Understanding the above code
secret_lingo
is a global string that holds our "secret message".update_lingo()
usesglobal secret_lingo
to modify it from inside the function.reveal_lingo()
just prints the current value.
Let's try this with collection types. Here, we shall take the example of lists
No need to use global keyword in the case shown below
Reassigning the list (needs global)
Updating the list (no need of global)
No comments:
Post a Comment