Python Function


When you want your program to be more efficient and easy to manage than use functions in your program.

What is Functions?

There are many situations in a program when you want to execute a same set of code many times at different positions in a code or task.

At such time if you start writing same set of code repeatedly in a same code, program becomes more complex and such codes are not easy to manage and is not a efficient solution for any task. Even you will be confused when you see your own code in future.

What is the Solution? 

So, to overcome such problem functions comes into picture.

The code that is repeated various times in your program name that code and whenever required just refer that set of code.

In technical terms a piece of code that you have named, which performs one operation is called Function.

Write this Function outside of your main code. And where ever  required refer this function. Referring a Function in main program is nothing but calling a function

The function is executed only when it is called from main program. You can call this function as many times you want.

Syntax:

def function_name ( optional_parameter):
         statement(s)
         statement(s)
print("not a part of function")


def = keyword

Every function definition has to start with keyword.

 function_name = Can be any name that you like as long as that is valid name. You can use any name other than built-in-function names. 

List of built-in-function is provided below follow that for your reference.

optional_parameter = Parameter inside parenthesis is optional. If you want to pass any input to function than you can use this parameter, if you are not passing any input to function leave it blank. This parameter is also called input parameter. 

Note: How many input parameters you're defining here, that much parameter should be passed to function when it is called. Don't pass less or more parameters, if done so program will give error.

The tabbed statements under function definition is called body of function.

The statement that are not tabbed are not included in the function body.

Example:

#function of adding
def adding_list_number(my_list):
    result=0
    for x in my_list :
        result=result+x
    return result

#main code
my_list = [1,2,3,4,5]
B = adding_list_number(my_list)
print("The result is", B)

Type the above code and see the result in IDLE. You can also input list from user by using input() function.

NOTES ON FUNCTIONS:


Most of the time we provide some arguments to a function and it returns something. However, this may not always be the case. While trying to write a function we need to decide if the function needs any arguments or not and if the function needs to return something or not.

Broadly, we can attempt to classify the combination of function parameters and their return types as follows:

  1. Nothing goes in, nothing comes out. 
  2. Nothing goes in, something comes out.
  3. Something goes in, nothing comes out. 
  4. Something goes in, something comes out. 

Nothing goes in, nothing comes out

def display_message():
   print("****   PYTHON IS GREAT   ****")
   print("=============================")
# Main Program #
radius = 5
print("The radius of the circle is: ", radius)
display_message()    # The function call
circumference = 2*3.14*radius
print("The circumference of the circle is:", circumference)
display_message()    # The function call
Note that the parentheses in the function call do not have any anything which means the function does not take any arguments. Also nothing is set equal to the function call i.e. the function call is on a line by itself which means it does not need to return anything. So basically, this function just keeps printing the same message every time it is called (Printing something is not the same as returning something). Even though, there is no return keyword in this function, it returns None by default.

Output:

The radius of the circle is:  5
****   PYTHON IS GREAT   ****
=============================
The circumference of the circle is: 31.400000000000002
****   PYTHON IS GREAT   ****
=============================

Nothing goes in, Something comes out

A great example of a function that does not receive anything but does return something is the following. 
import random
def report_random():
   my_number = random.randint(20, 100)
   return my_number
# Main Program #
a = report_random()   # return a random int and assign it to a
print("a is equal to ", a)
b = report_random()    # return a random int and assign it to b
print("b is equal to ", b)
c = report_random()    # return a random int and assign it to c
print("c is equal to ", c)
Notice that this function does not receive any arguments but each time we call this function it returns a random integer between 20 and 100 and assigns the returned value to the variable the function call was set equal to.
Output: 
a is equal to  82
b is equal to  75
c is equal to  94

Something goes in, nothing comes out

In this scenario, the function needs some arguments to do some task but it does not need to return anything.  
def calculate_area(length, breadth):
   area = length * breadth
   perimeter = 2*length + 2*breadth
   print("area is equal to", area)
   print("perimeter is equal to", perimeter)
# Main Program #
calculate_area(10, 20)
Notice that this function does receive two arguments length and breadth and when we call this function, it calculates the area and perimeter of a rectangle and prints the results but it does not return anything! And again printing something is not the same as returning some value. The return value once again for this function is None as there is no return keyword.
Output: 
area is equal to 200
perimeter is equal to 60

Something goes in, something comes out

This is probably the most meaningful scenario where the function takes some arguments and performs some task using those arguments and returns some result as well. 

def calculate_area(length, breadth):
    area = length * breadth
perimeter = 2*length + 2*breadth
    my_result = [area, perimeter]    # put results in a list
    return my_result                 # return the list

# Main Program #
my_list = calculate_area(10, 20) # two arguments are supplied
print("The resulting list looks like:", my_list)
Output: 
The resulting list looks like: [200, 60]
Note that we can return multiple things in python by separating them with a comma. For example instead of returning the results in a list we could have done the following:
return area, perimeter
In this situation, python would have returned the two values as a 'tuple', which would have looked like:
(200, 60)

Built-in-Functions:


Why to use Functions?

  1. Functions makes program easier to read and understand.
  2. Functions reduces code duplication.
  3. Functions allows the same code to reuse. i.e.; once the function written to perform a particular task you can use same function in any program in future and any number of times.
Example:

Write a function that calculates and returns the monthly payments for a loan. This function accepts three parameters in the exact order (principal, annual_interest_rate, duration):
  • principal: The total amount of loan. Assume that the principal is a positive floating point number.
  • annual_interest_rate: This is the percent interest rate per year. Assume that annual_interest_rate is a floating point number. (Notice that 4.5 means that the interest rate is 4.5 percent per year.)
  • duration: number of years to pay the loan back. Assume that duration is a positive integer.
# Function Declaration

def monthly_EMI(principal, annual_interest_rate, duration):
    principal = principal
    annual_interest_rate = annual_interest_rate
    years = duration
    n = years*12
    r = (annual_interest_rate/100)/12
    if r == 0 :
        month_EMI= principal/n
        return month_EMI
    month_EMI = principal*((r*((1+r)**n))/ (((1+r)**n)-1))
    return month_EMI

#main code

x = input("Enter principal amount") #take the input from user
principal = float(x) #convert the input value to required format, since input function gives string value
y = input("Enter annual_interest_rate")
annual_interest_rate = float(y)
z = input("Enter duration in years")
duration = int(z)
M = monthly_EMI(principal, annual_interest_rate, duration) #call function and pass the value
print("Every Month EMI will be", M)
Where:
  • r is the monthly interest rate (should be calculated by first dividing the annual_interest_rate by 100 and then divide the result by 12 to make it monthly). Notice that if the interest rate is equal to zero then the above equation will give you a ZeroDivisionError. In that case you should use the following equation:
    • MonthlyPayment=Principal / n
  • n is the total number of monthly payments for the entire duration of the loan (Notice that n is equal to loan duration in years multiplied by 12).
Type the above example into IDLE and check the output.

Thank you.



Comments

Popular Post

Python Data Types

Python String

Python List