Functions

  • Functions are the most important aspect of an application. A function can be defined as the organized block of reusable code, which can be called whenever required.
  • Python allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the Python program.
  • The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized.
  • Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions, which can be called user-defined functions.
  • There are mainly two types of functions.
    • User-define functions - The user-defined functions are those define by the user to perform the specific task.
    • Built-in functions - The built-in functions are those functions that are pre-defined in Python.

ADVANTAGE OF FUNCTIONS IN PYTHON

  • Using functions, we can avoid rewriting the same logic/code again and again in a program.
  • We can call Python functions multiple times in a program and anywhere in a program.
  • We can track a large Python program easily when it is divided into multiple functions.
  • Reusability is the main achievement of Python functions.
  • However, Function calling is always overhead in a Python program.

CREATING A FUNCTION

  • Python provides the def keyword to define the function. The syntax of the define function is given below.
  • Syntax:

  • Let's understand the syntax of functions definition.
    • The def keyword, along with the function name is used to define the function.
    • The identifier rule must follow the function name.
    • A function accepts the parameter (argument), and they can be optional.
    • The function block is started with the colon (:), and block statements must be at the same indentation.
    • The return statement is used to return the value. A function can have only one return

FUNCTION CALLING

  • In Python, after the function is created, we can call it from another function. A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses.
  • Consider the following example of a simple example that prints the message "Hello World".

  • Output:

THE RETURN STATEMENT

  • The return statement is used at the end of the function and returns the result of the function. It terminates the function execution and transfers the result where the function is called.
  • The return statement cannot be used outside of the function.
  • Syntax

  • It can contain the expression which gets evaluated and value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object.
  • Consider the following example:

  • Output:

  • In the above code, we have defined the function named sum, and it has a statement c = a+b, which computes the given values, and the result is returned by the return statement to the caller function.
  • Example: - Creating function without return statement

  • Output:

  • In the above code, we have defined the same function without the return statement as we can see that the sum() function returned the None object to the caller function.

ARGUMENTS IN FUNCTION

  • The arguments are types of information which can be passed into the function. The arguments are specified in the parentheses. We can pass any number of arguments, but they must be separate them with a comma.
  • Consider the following example, which contains a function that accepts a string as the argument.
  • Example 

  • Output:

  • Arguments are often shortened to args in Python documentations.
  • Example

  • Output:

PARAMETERS OR ARGUMENTS?

  • The terms parameter and argument can be used for the same thing: information that are passed into a function.
  • From a function's perspective:
    • A parameter is the variable listed inside the parentheses in the function definition.
    • An argument is the value that is sent to the function when it is called.

NUMBER OF ARGUMENTS

  • By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less.
  • Example
  • This function expects 2 arguments, and gets 2 arguments:

  • If you try to call the function with 1 or 3 arguments, you will get an error:
  • Example: - This function expects 2 arguments, but gets only 1:

ARBITRARY ARGUMENTS, *args

  • If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.
  • This way the function will receive a tuple of arguments, and can access the items accordingly:
  • Example
  • If the number of arguments is unknown, add a * before the parameter name:

  • Arbitrary Arguments are often shortened to *args in Python documentations.

KEYWORD ARGUMENTS

  • You can also send arguments with the key = value syntax.
  • This way the order of the arguments does not matter.
  • Example

  • The phrase Keyword Arguments are often shortened to kwargs in Python documentations.

ARBITRARY KEYWORD ARGUMENTS, **kwargs

  • If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.
  • This way the function will receive a dictionary of arguments, and can access the items accordingly:
  • Example
  • If the number of keyword arguments is unknown, add a double ** before the parameter name:

  • Arbitrary Keyword Arguments are often shortened to **kwargs in Python documentations.

DEFAULT PARAMETER VALUE

  • The following example shows how to use a default parameter value.
  • If we call the function without argument, it uses the default value:
  • Example

PASSING A LIST AS AN ARGUMENT

  • You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.
  • E.g. if you send a List as an argument, it will still be a List when it reaches the function:
  • Example

RETURN VALUES

  • To let a function return a value, use the return statement:
  • Example

THE PASS STATEMENT

  • Function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error.
  • Example

PYTHON LAMBDA FUNCTIONS

  • Python Lambda function is known as the anonymous function that is defined without a name. Python allows us to not declare the function in the standard manner, i.e., by using the def keyword. Rather, the anonymous functions are declared by using the lambda keyword. However, Lambda functions can accept any number of arguments, but they can return only one value in the form of expression.
  • The anonymous function contains a small piece of code. It simulates inline functions of C and C++, but it is not exactly an inline function.
  • The syntax to define an anonymous function is given below. 

  • It can accept any number of arguments and has only one expression. It is useful when the function objects are required.
  • Example:
  • A lambda function that adds 10 to the number passed in as an argument, and print the result:

  • Output

  • In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument and a+10 is an expression. The given expression gets evaluated and returned the result.
  • The above lambda function is same as the normal function.

  • Lambda functions can take any number of arguments:
  • Example
  • A lambda function that multiplies argument a with argument b and print the result:

  • Output

  • Example
  • A lambda function that sums argument a, b, and c and print the result:

  • Output

WHY USE LAMBDA FUNCTIONS?

  • The power of lambda is better shown when you use them as an anonymous function inside another function.
  • Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:

  • Use that function definition to make a function that always doubles the number you send in:
  • Example

  • Output

  • Or, use the same function definition to make both functions, in the same program:
  • Example

  • Output

  • Use lambda functions when an anonymous function is required for a short period of time.
  • Use that function definition to make a function that always doubles the number you send in:
  • Example

  • Output

  • The lambda function is commonly used with Python built-in functions filter() function and map() function.

USE LAMBDA FUNCTION WITH FILTER()

  • The Python built-in filter() function accepts a function and a list as an argument. It provides an effective way to filter out all elements of the sequence. It returns the new sequence in which the function evaluates to True.
  • Consider the following example where we filter out the only odd number from the given list.

  • Output

USING LAMBDA FUNCTION WITH MAP()

  • The map() function in Python accepts a function and a list. It gives a new list which contains all modified items returned by the function for each item.
  • Consider the following example of map() function.

  • Output

PASS BY REFERENCE VS VALUE

  • All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
  • Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result −
  • There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
  • The parameter mylist is local to the function change me. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −

HOW ARE ARGUMENTS PASSED BY VALUE OR BY REFERENCE IN PYTHON?

  • Python uses a mechanism, which is known as "Call-by-Object", sometimes also called "Call by Object Reference" or "Call by Sharing"
  • If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different, if we pass mutable arguments.
  • Example
  • Output:

CALL BY REFERENCE IN PYTHON

  • In Python, call by reference means passing the actual value as an argument in the function. All the functions are called by reference, i.e., all the changes made to the reference inside the function revert back to the original value referred by the reference.
  • Example: Passing Immutable Object (List)
  • Output:
  • Example: Passing Mutable Object (String)
  • Output:

RECURSION

  • Python also accepts function recursion, which means a defined function can call itself.
  • Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
  • The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
  • In example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).
  • To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
  • Recursion Example 
  • Output:

Comments

Popular posts from this blog

Modules

Control Structures

Classes and Objects