Thursday, October 25, 2018

Return Values and return Statements in Functions

The functions we have used to far display its output directly which isn't the case always. A function can process some data and then return a value or set of values. The value the function returns is called a return value. The return statement takes a value from inside a function and sends it back to the line that called the function.

Return values allow you to move much of your program’s menial work into functions, which can simplify the body of your program. When creating a function using the def statement, you can specify what the return value should be with a return statement. A return statement consists of the following:

• The return keyword
• The value or expression that the function should return

When an expression is used with a return statement, the return value is what this expression evaluates to. For example, the following program defines a function 'employee_detail' that returns a string 'job_description' depending on what name and work is passed as an argument.

def employee_detail(name,work):
   
    job_description = name + ' is a '+work
    return job_description
   
jd = employee_detail('Vivek','Programmar')

print(jd)


The definition of employee_detail() takes as parameters an employee name and his nature of work. The function combines these two with a string 'is a ' in between and stores the result in job_description which is then returned.

When you call a function that returns a value, you need to provide a variable where the return value can be stored. In this case, the returned value is stored in the variable 'jd'. When we run the program we get the following output -





 Return type values of function

A function can return simple values as well as data structures like lists and dictionaries.

1. Function returning a dictionary

Let's write a function which takes first name and last name of an employee and returns a dictionary representing employee.

def full_name(firstname,lastname):
   
    employee ={'first': firstname,'last':lastname}
   
    return employee
   
myemployee =full_name('Vivek','Swami')
print(myemployee)



As you can see from the code full_name() takes in a first name and last name, and packs these values into a dictionary employee. The value firstname is stored with the key 'first' and the value of lastname is stored with the key 'last'. The entire dictionary representing the person is then returned. The return value is finally printed with the original two pieces of textual information now stored in a dictionary as shown in the output below -



2. Passing a list to a Function 

It is possible to pass a list as an argument to a function. It doesn't matter whether it’s a list of
names, numbers, or more complex objects, such as dictionaries. When a list is passed to a function, the function gets direct access to the contents of the list.

Let's create a list of recently joined employees and we want to print a greeting to each of them. See the program below -


def greet_emp(enames):
   
    for name in enames:
       
        greeting = "Welcome aboard " + name + "!"
        print(greeting)
       
       
users = ["Bob","Ted", "Joey","Chris","Mac"]
greet_emp(users)


We define greet_emp() so it expects a list of names of employees , which it stores in the parameter enames. The function loops through the list it receives and prints a greeting to each user. We then create a list users, of recently joined employees. Finally we call the greet_emp() with users as an argument. When the program is run following output is obtained -



3. Passing an arbitrary number of arguments

Python allows a function to collect an arbitrary number of arguments from the calling statement. This is useful as sometimes we won’t know ahead of time how many arguments a function needs to accept.

Let's consider a function that books a ticket for a person. It needs to accept a number of persons, but you can’t know ahead of time how many persons will want to travel in the booked ticket. The function in the following example has one parameter, *passengers, but this parameter collects as many arguments as the calling line provides. See the program below -


def booking(*passengers):
   
    print(passengers)
   
booking('Vivek')
booking('Satya','Tom','Eric')





The asterisk in the parameter name *passengers tells Python to make an empty tuple called booking and pack whatever values it receives into this tuple. The print statement in the function body produces output showing that Python can handle a function call with one value and a call with three
values. It treats the different calls similarly. Note that Python packs the arguments into a tuple, even if the function receives only one value. See the output of the above program -



The below program would make more sense -

def booking(*passengers):
   
    print("\nTicket booked for: ")
    
    for passenger in passengers:
        print(passenger)
       
booking('Vivek')
booking('Satya','Tom','Eric')


In the above program we have a loop that runs through the list of passengers and describes the ticket being booked. See the output below -



4. Passing positional and arbitrary arguments

In python it is possible to pass mixed arguments to a function. But if we want a function to accept several different kinds of arguments, the parameter that accepts an arbitrary number of arguments must be placed last in the function definition as Python matches positional and keyword arguments first and then collects any remaining arguments in the final parameter. See the code below -

def booking(way,*passengers):
   
    print("\nBooking a " + way + " ticket for: ")
   
    for passenger in passengers:
        print(passenger)
       
booking('Two way','Vivek')
booking('One way','Satya','Tom','Eric')


Here we have modified our booking() which now accepts a new parameter way to specify a one way or two way ticket. This parameter must come before *passengers. Python stores the first value it receives in the parameter way . All other values that come after are stored in the tuple passengers. The function calls include an argument for the way first, followed by as many passengers as needed.

Now each ticket has a way and a number of passengers , and each piece of information is printed in the proper place, showing way first and passengers after. See the output of the program below -




 5. Passing arbitrary keyword arguments

If we want to accept an arbitrary number of arguments, but don't know ahead of time what kind of information will be passed to the function,we can write functions that accept as many key-value pairs as the calling statement provides. For example let's make a function to build student profile and we know we’ll get information about a student, but you’re not sure what kind of information we’ll receive. The function build_profile() in the following example always takes in a first and last name, but it accepts an arbitrary number of keyword arguments as well. See the program below -

def build_profile(first, last, **student_info):
   
    profile = {}
   
    profile['first_name']=first
    profile['last_name']=last
   
    for key,value in student_info.items():
       
        profile[key]=value
   
    return profile
   
student_profile = build_profile('Vivek','Swami',location ='Hyderabad',branch='IT')
   
print(student_profile)


 
The definition of build_profile() expects a first and last name, and then it allows the user to pass in as many name-value pairs as they want. The double asterisks before the parameter **student_info cause Python to create an empty dictionary called student_info and pack whatever name-value pairs it receives into this dictionary. Within the function, you can access the name-value pairs in student_info just as you would for any dictionary.

In the body of build_profile(), we make an empty dictionary called profile to hold the student’s profile. We add the first and last names to this dictionary because we’ll always receive these two pieces of information from the student. Next we loop through the additional key-value pairs in the dictionary student_info and add each pair to the profile dictionary. Finally, we return the profile dictionary to the function call line.

We call build_profile(), passing it the first name 'Vivek', the last name 'Swami', and the two key-value pairs location='Hyderabad' and branch='IT'. We store the returned profile in student_profile and print student_profile. The output is shown below:



The returned dictionary contains the student’s first and last names and, in this case, the location and branch of study as well. The function would work no matter how many additional key-value pairs are provided in the function call.

Try this function by adding some more key value pairs from your side. Functions are widely used in real world programs thus a clear understanding is beneficial. So practice more and more. In the next post we'll see how to store functions in modules.

Keep learning Python as Python is easy to learn!


 
Share:

0 comments:

Post a Comment