Python- Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Eg : print() this is an built-in function. We can create our own functions. The following example will help understand functions better

we have taken a function called simple_interest and tried various things on it by passing parameters , not passing parameters, assigning parameters but changing it on run time.

Note: here p=1000 will come after r and t. This returns syntax error.
We see default arguments and non-default argument.
Note : here we notice type error because we have missed one value t
this is also a Required argument.

There are different types of Function Arguments:

  1. Required Arguments: Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
  2. Keywords Arguments : Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
  3. Default Arguments: A default argument is an argument that assumes a default value if a value is not provided in the function call .
  4. Variable Length Arguments: We may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.

Using keyword arguments is the same thing as normal arguments except order doesn’t matter. For example the two functions calls below are the same Arguments with a default value may be passed positionally, and arguments without a default value may be passed by keyword

Difference between positional and keyword argument.

Variable Length Arguments

The Anonymous Functions

These functions are called anonymous because they are not declared in the standard manner by using the def keyword.  lambda keyword to create small anonymous functions. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.

Call by Reference and Call by value

When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable. (It changes)

When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller. (It does not change)

An example will elucidate the points above:

Leave a Reply