A parameter is actually a
variable, but there are two important factors that make parameters different
& special.
Parameters exist only inside
functions in which they have been defined, and the only place where the
parameter can be defined is a space between a pair of parentheses in the “def”
statement.
Assigning a value to the
parameter is done at the time of the function’s invocation, by specifying the
corresponding argument.
We should remember this
carefully. Specifying one or more parameters in a function’s definition is also
a requirement, and we have to fulfill it during invocation. We must provide as
many arguments as there are defined parameters.
Failure to do so will cause
an error.
Let’s consider this example.
This code will produce the
following output.
The value of the argument
used during invocation (1) has been passed into the function, setting the
initial value of the parameter named “number”.
Also it’s legal and possible to have a variable named the same as a function’s parameter. Let’s see the below snippet.
Also it’s legal and possible to have a variable named the same as a function’s parameter. Let’s see the below snippet.
Output is
A situation like this
activates a mechanism called shadowing.
Parameter “x” shadows
any variable of the same name, but... only inside the function defining the
parameter.
The parameter named
“number” is a completely different entity from the variable named “number”.
A function can have as many parameters as we want, but the more parameters we have, the harder it is to memorize their roles and purposes.
Let's modify the function - it has two parameters now.
Output is
No comments:
Post a Comment