Sunday, 5 August 2018

Python :: 11 - Functions

Functions


Function:
==========
 A function is similar to a program that consists of a group of statements that are
 intended to perform a specific task. The main purpose of a function is to perform
 a specific task or work. Thus when there are several tasks to be performed, the
 programmer will write several functions.

 Built in functions : print(),sqrt(),power()
 User defined functions: Programmer can create their own functions.


Advantage of functions :
===================
1. Once function is written, it can be reused as and when required. So functions are
also called reusable code. Because of re usability , the programmer can avoid code
redundancy. It means it is possible to avoid writing the same code again and again.

2. Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated to software.

3.  When there is error in the software, the corresponding function can be modified
with out disturbing the other functions in the software.

4. The use of functions in a program will reduce the length of the program.


Difference between function and method:
=====================================

function : group of statements
method   : function inside a class.

So, please remember that a function and a method are same except their placement and
the way they are called.


Defining a function:
===================

We can define a function using keyword def followed by function name after the function name
, we should write parentheses() which may contain parameters. Consider the syntax of function
as follows.

def functionname(param1,param2...):
"""function docstring """
function statements

example :
def sum(a,b):
""" this function finds sum of two number"""
c = a + b
print(c)

def --> function specified
sum --> function name
a,b --> function parameters

After parentheses, we put a colon(:) represents the begining of the function body.

Function body contains group of statements called as 'suite'.
we should write string in first line of function body called it as 'docstring'

'docstrings' are optional.

1. Write a function that accepts two values and find their sum and return results

def sum(a,b):
""" this function find sum of two numbers"""
c = a+b
return c

x = sum(10,15)
y = sum(20,30)

2. Write a program to test whether a number is even or odd?

def even_odd(num):
 """ even number or odd number"""
if(num % 2 ==0):
print(num, "is even")
else:

print(num, " is odd")
even_odd(12)
even_odd(13)


Returning multiple values from a function :
===========================================


def sum_sub(a,b):
   c = a+b
   d = a-b
   return c,d

i,j = sum_sub(10,20)                 

print("the sum is %d and sub is %d"%(i,j))



Formal and actual arguments :
=======================

def sum(a,b):          # a,b are formal arguments
c = a+b
print(c)
x = 10
y = 15
sum(x,y)     # x,y are actual arguments


Local and Global variables :
=========================

Local : When we declare a variable inside a function, it becomes a local variable.
local variable scope is limited only to that function where it is created.
That means the local variable value is available only in that function
and not outside of the function.
Global: When a variable is declared above a function , it becomes global variable.
Such variables are available to all the functions which are written after it.


a=1  # this is global variable
def myfunction():
b =2   # this is local variable
a=10
print('a = ',a)
print('b = ',b)

myfunction()
print(a)      #available
print(b)      # Error,not available

a1
b

Recursive functions:
===================

A function that calls itself is known as 'recursive function'.

1. Python program to calculate factorial of give number

def fact(n):
if n == 0:
res = 1
else:
res = n * fact(n-1)
return res


i = 4
print('factorial of {} is {}'.format(i,fact(i)))


Anonymous function or Lambadas
==============================


A function without a name is called 'anonymous function'. So far, the functions we wrote were
defined using the keyword 'def'. But anonymous functions are not defined using  'def'. They are
defined using the keyword 'lambda' and hence they are also called 'Lambada functions'

def square(x):
return x*x

square(5)


The same function can be written as
lambda x : x * x

1. Python program that create a lambda function that return a square value of a given number

f = lambda x : x * x

value = f(5)
print('square of 5 = ',value)



Lambda function contain only one expression and they return the result implicitly.
Hence we should not write any return statement in lambda functions.
Here is lambda function that calculates sum of two numbers.

2. Python function calculate sum of two numbers.

f = lambda x,y : x+y

res = f(10,20)
print("sum is ", res)

lambdas with filter() function :
--------------------------------

The filter() is useful to filter out the elements of sequnce depending  on the
result of a function. We should supply a sequnce to filter function as:

filter(function,sequnce)




1. A Python program using filter() to filter out even numbers from a list

def is_even(n):
if n%2 == 0:
return True
else:
return false
lst = [12,21,24,31,56]

lst1 = list(filter(is_even,lst))
print(lst1)

c:\> python fun.py
[12,24,56]

2. lambda function that returns even numbers

lst = [12,21,24,31,56]

lst1 = list(filter(lambda x: (x%2==0),lst))
print(lst1)




lambdas with map() function :
--------------------------------
The map() function is similar to filter() function.but it acts on each element of the
sequence and perhaps changes the elements. The format of map() function is:

map(functoin,sequnce)

The 'function' performs a specified operation on all the elements of the sequnce and the
modified elements are returned which can be stored in another sequnce.


1. Python to find square of each element of sequnce

def squares(x):
return x*X
lst = [1,2,3,4]
lst1 = list(map(squares,lst))
print(lst1)


f = lambda x : x*x


lst = [1,2,3,4]
for i in lst:
print(f(i))

lst1 = list(map(lambda x: x*x , lst))
print(lst1)



Types of arguments:
-------------------
1.Positional arguments
2.Keyword arguments
3.Default arguments
4.Variable length arguments

1.positional arguments

These are the arguments passed to the function
in correct positional order.
Here number of arguments should be same.

def add(a,b):
return a+b
res = add(100,200)
print(res)

2. Keyword arguments

We can pass argument values by keyword i.e by parameter name

def add(a,b):
print("a value is",a)
print("b value is",b)
return a+b
res = add(10,b=30)
print(res)
res1 = add(10,40)
print(res1)
res1 = add(b=10,a=40)
print(res1)

Note : here the order is not immportant.But no.of arguments should be match.

We can take both positional arguments and keyword arguments simultaneously. But
first we have take positional arguments and keyword arguments otherwise will get
error

def add(a,b,c)
return a+b+c
res = add(10,b=20,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
result is 60


def add(a,b,c):
return a+b+c
res = add(a=20,10,c=30)
print("result is",res)

C:\Users\lenovo\Desktop>python add.py
  File "add.py", line 4
    res = add(a=20,10,c=30)
                  ^
SyntaxError: positional argument follows keyword argument

3. Default arguments

Sometimes we have to provide default values for our positional arguments

def add(a=10,b=20):
return a+b

#res = add(a=40,b=50)
res = add()
print("sum is",res)

If we are not passing any name then only default value will be considered.

Note :
After default argument we should not take any non default arguments.

def add(a=10,b):
return a+b

4. Variable length arguments

Sometimes we can pass variable number of arguments to our function, such type of
arguments are called variable length arguments.

We can declare a variable length argument with * symbol as follows

def add(*n):
total = 0
for i in n:
total = total+i
print("the sum is",total)
add()
add(10,20)
add(10,20,30)

Note :
we can mix variable length arguments and positional arguments.

def fun1(n1,*t):
print(n1)
for i in t:
print(i)
fun1(10)
fun1(10,20,30,40,50)
fun1(10,'A','B','C')

Output :
10
10
20
30
40
50
10
A
B
C
Note : After variable length argument, if we take any other arguments then
we should provide values as keyword arguments.

def fun1(*t,n1):
print(n1)
for i in t:
print(i)
fun1(10,n1=10)

output :
C:\Users\lenovo\Desktop>python def_ex.py
10
10

Note : We can declare keyword variable length arguments also.
For this we have to use **.

eg : def fun1(**n)

we can call this function by passing any number of keyword arguments.
Internally these keyword arguments will be stored inside a dictionary.

def details(**kwargs):
for k,v in kwargs.items():
print(k,v)

details(id=101,name='Phani')
details(n1=10,n2=20,n3=30)

output:
id 101
name Phani
n1 10
n2 20
n3 30

eg:
def details(id,*marks,**kwargs):
print(id)
for i in marks:
print(i)
for k,v in kwargs.items():
print(k,v)
details(101,10,20,30,40,name='Ravi',address='Hyderbad')

No comments:

Post a Comment