Monday, April 26, 2021

The way of function interacts with its arguments

 Consider the below example.

Example - 1







The output is given below.





Here, changing the parameter's value doesn't propagate outside the function.

This also means that a function receives the argument's value, not the argument itself. This is true for scalars.


Let's apply this theory for lists.

Example - 2







The output is,





Example - 3







The output is,




Explanation:-

  1. If the argument is a list, then changing the value of the corresponding parameter doesn't affect the list (But variables containing lists are stored in a different way than scalars)
  2. But if we change a list identified by the parameter (not the parameter), the list will reflect the change.

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,