Wednesday, October 24, 2018

Functions in Python

Python provides several builtin functions like print(),input(), and len() but we have a flexibility to write our own functions, which are named blocks of code that are designed to do one specific job. Thus A function is like a mini-program within a program.

We define a particular task in a function and when we want to perform that task, we call the function responsible for doing it. If we need to perform that task multiple times throughout our program, we don’t need to type all the code for the same task again and again; we just call the function dedicated to handling that task, and the call tells Python to run the code inside the function. Thus using functions makes our programs easier to write, read, test, and fix. To better understand how functions work, let’s create one. This is a simple function named greetings() that prints a greeting:

def greetings():
   
    print("Hello learner! welcome to the world of Python")
   
greetings()


In the example the keyword def  inform Python that you’re defining a function. This is the function definition, which tells Python the name of the function and, if applicable, what kind of information the function needs to do its job. The parentheses hold that information. In this case, the name of the function is greetings(), and it needs no information to do its job, so its parentheses are empty, still the parentheses are required. Finally, the definition ends in a colon.

The indented lines that follow def greetings(): make up the body of the function. The line print("Hello learner! welcome to the world of Python") is the only line of actual code in the body
of this function, so greetings() has just one job: print("Hello learner! welcome to the world of Python").

The last statement of the program is a call to the function greetings() and you may have noticed we simply wrote the name of the function, followed by any necessary information in parentheses. As no information is needed here, calling our function is as simple as entering greetings().

A function call tells Python to execute the code in the function and thus as a result it prints -

Hello learner! welcome to the world of Python

The screen shot below shows the output of this program-



If in our program we call the function three times, the message will be printed three times as shown below-

def greetings():
   
    print("Hello learner! welcome to the world of Python")
   
greetings()

greetings()
greetings()

When you run this program, the output looks like this:


 
Thus the major purpose of functions is to group code that gets executed multiple times. Without a function defined, you would have to copy and paste this code each time, and the program would look like this:

print("Hello learner! welcome to the world of Python")
print("Hello learner! welcome to the world of Python")
print("Hello learner! welcome to the world of Python")   

It's a good programming practice to always avoid duplicating code, because if you ever decide to update the code—if, for example, you find a bug you need to fix—you’ll have to remember to change the code everywhere you copied it.

Functions with Parameters

We've already used print() and len() functions and in order to call these functions pass in values, called arguments in this context, by typing them between the parentheses. In the previous example we called print() by typing "Hello learner! welcome to the world of Python" between the parentheses.

print("Hello learner! welcome to the world of Python")

Now lets us modify our first program which would greet a user using his name. See the code below-

def greetings(name):
   
    print("Hello " + name + "! welcome to the world of Python")
   
greetings('Vivek')


To call greetings() we need to provide an argument which in our case will be a user's name. Thus when I wrote greetings('Vivek') I intend to print the desired message with Vivek in it. When you run this program, the output looks like this:


The variable name in the definition of greetings() is an example of a parameter, a piece of information the function needs to do its job. The value 'jesse' in greet_user('Vivek') is an example of an argument, which is a piece of information that is passed from a function call to a function.
When we call the function, we place the value we want the function to work with in parentheses. In this case the argument 'Vivek' was passed to the function greetings(), and the value was stored in the parameter username.

Each time we call greetings() with a different argument, the greeting will be printed using the parameter name in it as shown below-

greetings('Satya')
greetings('Raj')
greetings('Sheldon') 






Passing arguments to function

A function definition can have multiple parameters, a function call may need multiple arguments. As we can pass arguments to our functions in a number of ways, let’s look at each of these in turn.

1. Function call using Positional Arguments

When we call a function, Python must match each argument in the function call with a parameter in the function definition. The simplest way to do this is based on the order of the arguments provided. Values matched up this way are called positional arguments.

To see how this works, consider a function that displays information about employees. The function tells us what kind of work employee is doing and the employee’s name, as shown here:

def employees(work,name):
   
    print(name + " is a " + work)
   

employees('Programmar','Satya')

employees('Designer','Raj')

employees('Content editor','Sheldon')  


The function definition shows that it needs an employee's type of work and the employee's name as parameters. When we call employees(), we need to provide a work type and an employee name, in that order. Thus in the function call employees('Programmar','Satya') the argument 'Programmar' is stored in the parameter work and the argument 'Satya' is stored in the parameter name. In the function body, these two parameters are used to display information about the employee being described.

The output of the above program is shown below:



We can use as many positional arguments as we need in our functions. Python works through the arguments we provide when calling the function and matches each one with the corresponding parameter in the function’s definition. However we'll get unexpected results if we mix up the order of the arguments in a function call when using positional arguments.

Thus the function call - employees('Satya','Programmar') will produce the following output- Programmar is a Satya the argument 'Satya' is stored in the parameter work and the argument 'Programmar' is stored in the parameter name.


2. Function call using keyword Arguments 

A keyword argument is a name-value pair that we pass to a function. We directly associate the name and the value within the argument, so when we pass the argument to the function, there’s no confusion about correctly ordering our arguments in the function call. Keyword arguments clarify the role of each value in the function call.

Let us now call the employees() from our previous program using a keyword argument. The syntax is shown below:

employees(work='Programmar',name='Satya')
employees(name='Satya',work='Programmar')

As you can see we have changed the order of arguments in the function calls, still the output remains the same as shown below:



When we call the function, we explicitly tell Python which parameter each argument should be matched with. When Python reads the function call, it knows to store the argument 'Programmar' in the parameter work and the argument 'Satya' in name. The output correctly shows that we have a Programmar named Harry. The order of keyword arguments doesn’t matter because Python
knows where each value should go.


3. Functions using default values

It is possible to define a default value for each parameter at the time of writing the function. If an argument for a parameter is provided in the function call, Python uses the argument value. If not, it uses the parameter’s default value. So when we define a default value for a parameter, we can exclude the corresponding argument we’d usually write in the function call. Using default values we
can simplify our function calls and clarify the ways in which our functions are typically used. For example see the code below:

def employees(work='Programmar', name):
   
    print(name + " is a " + work)
   

employees(name='Satya')

employees(name='Vivek')


In the example above we are assuming that nature of work of our employees is of a Programmar hence we've set the default value of work to 'Programmar'. Now Now when the function is called with no work specified, Python knows to use the value 'Programmar' for this parameter. When we run this program we should get this output




But the following output is received-




Because the default value makes it unnecessary to specify a type of work as an argument, the only argument left in the function call is the employee’s name. Python still interprets this as a positional argument, so if the function is called with just a employee’s name, that argument will match up with the first parameter listed in the function’s definition. This is the reason the first parameter needs to be name. Hence to use a default value the order of the parameters in the function definition must be changed. Now our function becomes-


def employees(name, work='Programmar'):
   
    print(name + " is a " + work)
   

employees(name='Satya')

employees(name='Vivek')


 If we run the above program we'll get the following output -






In both the calls only argument provided is 'Satya' and 'Vivek' so it is matched up with the first parameter in the definition, name. Because no argument is provided for work, Python uses the default value 'Programmar'.

If we call the function as employees(name='Chris', work='Editor') we'll get the following output-




Because an explicit argument for work is provided, Python will ignore the parameter’s default value.

In our next post we shall explore functions with return values. Till then keep practicing and learning as Python is easy to learn!

Share:

0 comments:

Post a Comment