Diving Into Python: Chapter 13

This is the 13th part of this article series about Python. In this article series you will learn Python step-by-step and in an easier way.

Getting Theme

For getting the theme of Python, kindly go through my previous articles:

Function

A function in programming terms can be defined as “a block of reusable, managed code block that is used to perform any certain single operation.

Functions provide better functioning for your application and a high degree of code reusability.

We can also call it a machine that gives desired outputs depending on our input. Something like the following:

machine

Python contains several types of built-in functions such as print(), del, len and so on. These types of functions are called built-in functions, but still, like several other programming languages, they provide complete freedom to create your own functions based on your requirements. These types of functions are called user-defined functions.

Creating a Function

As I said earlier, you can create your own built-in functions. So let's have a look at how to create a function.

The following are the set of rules that you need to follow when creating a function:

  • A function block in Python begins with a keyword def.
  • A function name after that keyword "def" and parentheses "()".
  • Any input parameter or arguments for a specific functionality should be placed between these parentheses.
  • An optional statement, "fun_docstring" is followed by the parentheses, but it's optional.
  • For accessing and invoking a function In Python, we should use a colon ":".
  • Then your function or some set of code for performing certain operation.
  • Finally a return statement.

Structure

Let's have a look at the structure:

    Def funcname (parameters):
    “func_docstring”
    Func_suite
    return [expression]

Example

Creating several basic functions.

    # Function: Add

    def add(a, b):
    print ("Adding : %d + %d" % (a, b))
    return a + b

    # Function: Subtract

    def subtract(a, b):
    print ("Subtracting : %d - %d" % (a, b))
    return a - b

    # Function: Multiply

    def multiply(a, b):
    print ("Multiplying : %d * %d" % (a, b))
    return a * b

    # Function: Divide

    def divide(a, b):
    print ("Dividing : %d / %d" % (a, b))
    return a / b

    print ("Let's use the functions created by us")

    # Calling Functions

    A = add(5, 5)
    B = subtract(5, 6)
    C = multiply(6, 5)
    D = divide(5, 5)

    print ("A : %d | B : %d | C : %d | D : %d" % (A, B, C, D))

Output

print

Calling a Function

Creating a function is just 50% of the entire work, moreover for performing certain operations you need to call that function later in your code snippet. So let's have a look at how it can be done in Python.

Once the basic block of function is formed, here are the approaches that you need to use when calling a function in Python.

Function Calling | Approaches

Here are some approaches:

Function Calling Approaches

  • Call By value

    - The most common strategy of parameter or argument passing is call-by-value, sometimes it is also called pass-by-value. This strategy is used in several programming languages like C, C#, Java, C++ and so on.

    - In the call by value approach the argument expression is evaluated first and the result of this evaluation is bound to the corresponding variable in the function. So, if the expression is a variable, a local replica of its value will be used.

    - Here's how it works:

    call by value

    Explanation

    Here a replica of the list (all the values and elements in it) are used for a functionality via passing a value.
  • Call By Reference

    - In a call by reference approach, a function gets an implicit reference to the argument rather than a copy of its value. As a result, the function can modify the argument and the value of the variable in the caller's scope can be changed.

    - This strategy is also known as pass by reference and is used in several programming languages, such as C, C#, Java, C++ and so on.

    - The advantage of call by reference is greater time and space efficient because arguments do not need to be copied.

    - Here's a sample functionality:

    list

    Explanation

    In this approach, it works slightly differently. Here there are two locations and for both of the locations only a reference is being used instead of the replica itself.
Function Calling | Arguments

In Python you can call a function using these types of arguments:

Function Calling Arguments
  • Default Arguments

    As the name suggests, a default argument always assumes a default value in case there is no value provided in the function call for a specific argument.

    Example

    def empinfo(name = "ABC", designation):
    print ("Name : ", name)
    print ("Designation : ", designation)
    return;
    empinfo( designation = "Dev" )

    Output

    Function Calling

    Now let us see some changes in the code and call the function again for a different pair or a different value:

    def empinfo(name = "XYZ", designation):
    print ("Name : ", name)
    print ("Designation : ", designation)
    return;
    empinfo( name = "ABC", designation = "Dev" )
    empinfo( designation = "Dev" )

    Output

    empinfo

  • Required Arguments

    Required arguments are those that are passed to a function in a proper positional / hierarchical order. In Python, the number of arguments in the function call should be exactly same as the function definition.

    Example

    def callme( str ):
    "This prints a passed string into this function"
    print (str)
    return;
    callme();

    Output

    Required Arguments

    Explanation

    As I explained in the preceding paragraph, a required argument needs to pass one argument in the callme function and we didn't do that. That's why the snippet is showing an error.

    But if you pass an argument then it will produce an output for sure.
  • Keyword Arguments

    Keyword arguments are somehow similar to the function calls. Whenever you use keyword arguments in a function call, it is identified by the parameter name directly.

    There are many advantages to the use of this approach, these are:

      - it allows you to skip the arguments.
      - Even you can place the arguments out of order.
      - You can also make keyword calls (using function name).

    Example

    def callme( str ):
    print (str)
    return;
    callme( str = "Calling that function");

    Output

    Output

    Explanation

    If you haven't yet gotten the theme then don't worry. Let's explore it with a similar type of example as we used for the default try arguments, to provide you a clear view.

    def empinfo(name , designation):
    print ("Name : ", name)
    print ("Designation : ", designation)
    return;
    empinfo( name = "ABC", designation = "Dev" )

    Output

    Keyword Arguments

    (I hope now it will be clear to you guys.)

  • Variable Length Arguments

    All the three above specified arguments are enough to perform any operation, but still you may need to process a function for more arguments than you specified. For that, here comes the concept of Variable Length Arguments.

    Example

    def callme( arg, *vartuple ):
    print ("India??")
    print (arg)
    for var in vartuple:
    print (var)
    return;

    callme( "Democracy", "or", "Gerontocracy")

    Output

    Variable Length Arguments
Guidelines from my Side
  • Do as much as code you can
  • Code anything you want, the best way to learn
  • Don't just study things, try to learn them
  • Work on your Concepts
  • Work on the fundamentals of any technology or stuff you want to learn

Moto

“Keep calm and code Python”.

I tried to make it an interesting and interactive article and wish you guys like that, meanwhile if you have any suggestions then your welcome.

Until the next part, keep sharing!