Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Functions

Function without arguments and without return value

def print_hello():
print ( "hello vit")

Function with arguments and without return value

def print_hello_msg( msg ):


print(msg)
Function without arguments and with return value

def print_return_msg():
return "hello students -:)"

Function with arguments and with return value

def print_sum( a , b ):
return a + b
s = input()
print_hello_msg(s)
m = print_return_msg()
print(print_return_msg())
print(m)
print_hello()
a = int(input())
b = int(input())
s = print_sum(a,b)
print(s)
print("over")

Function – Pass by value

def print_pass_value( a , b ):
a = a + 5
b = b + 5
print ("The changed argument inside the print_pass_value()",a)
print ("The changed argument inside the print_pass_value()",b)
n = 10
n1 = 30
print_pass_value( n , n1 )
print ("The no change in actual argument in main",n)
print ("The no change in actual argument in main",n1)

Function – Pass by reference

def list_pass_by_ref( l1 ):
for i in range(len(l1)) :
l1[i] = l1[i] + 5
print ("Formal argument l1 is changed\t",l1)

l = [ 1,2,3,4,5]

1 |Functions, !850,10164,Puviarasi
print ( " The inital list value before passing to function
list_pass_by_ref")
print(l)
list_pass_by_ref( l )
print ("actual argument l is changed is\t",l)

Functions with default arguments and keyword arguments


Example 1 – default arguments

def fun( a , b =10):


return a + b
print(fun( 5 , 6 ))
print(fun(10))

Keyword argument
def key_val( k , v ):
print ( k )
print (v)

key_val( v=10, k =9)


v=16
k = 17
key_val( v , k )

Example 3 – Default and keyword arguments

def india(place,state='Tamil
Nadu',capital='Chennai',national_lang='Hindi'):
print ( capital,end= ' ')
print ( place,end=' ')
print ( national_lang,end= ' ' )
print ( state)

india("vellore")
india(national_lang = 'Kanada', place = "Banglore")
india('Hyderabad', state = 'Telugana')
india('Pune', 'Maharastra', 'Mumbai')

Explanation

'''india() # required argument


missing
india(place="Delhi", 'Delhi') # non-keyword argument
following keyword
india("Maharastra", place="Banglore") # duplicate value for
argument
india(dance='Bharatha Natyam') # unknown keyword'''

Function defined inside if block

n = int(input())
if n == 1:

2 |Functions, !850,10164,Puviarasi
def display():
print ("hello")
else:
def display():
print ("have a good day")
display()

Functions for fibanocci series and length of each words stored in list

def fibo_series( n , l ):
l.append(0)
l.append(1)
a = 0
b = 1
for i in range( n ):
c = a + b
l.append(c)
a = b
b = c
l = []
fibo_series( 10 , l )
print(l)
def count_len( l ):
l1 = list(map(len , l))
print(l1)
return max(l1)

choice = int ( input("Enter the choice\t:"))


if choice == 1:
fibo_series(10)
print l
elif choice == 2:
l = ['Akila','Anitha','Ramya','Sumathi']
res = count_len(l)

Functions called through function reference

def one():
print('one')
def two():
print('two')
def three():
print('three')
a = 3
if a == 1:
call_Func=one
elif a == 2:
call_Func=two
else:
call_Func=three
call_Func()

Function Linear Search

3 |Functions, !850,10164,Puviarasi
def linearSearch( l , se ):
for ele in l:
if ele == se:
return True
return False

num_terms = int( input ( ) )


list_elements = [ int(input() ) for i in range(num_terms)]
search_element = int(input())
if ( linearSearch ( list_elements , search_element )):
print ( "Element found in list")
else:
print ( "Element not found in list")

Function Binary Search

def binary_search( l , se ,low , high ):


while low <= high :
mid = (low + high )//2
if l[ mid ] == se:
return True
elif se > l[ mid ]:
low = mid + 1
else:
high = mid - 1
return False

n = int(input("enter the number of elements\t:"))


l = [ int(input("enter the element in the list\t:")) for i in
range(n)]
l = sorted(l)
con = 1
while con == 1:
se = int(input("enter the search element\t:"))
ser = binary_search( l , se , 0 , len(l)-1)
if ser :
print ("successful")
else:
print ("not successful")

con = int(input("To continue enter 1\t:"))

Function Bubble Sort

def bubbleSort( l1 ):
flag = False
i = 0
while i < len(l ) - 1 and flag != True :
flag = True
j = 0
while j < len(l) - i - 1 :
if l[ j ] > l[ j + 1] :
l[ j ] , l[ j + 1 ] = l[ j + 1 ],l[ j ]
flag = False;
j = j + 1
print ("The unsorted\t:",l[:j])

4 |Functions, !850,10164,Puviarasi
print ("The sorted\t:",l[j:])
i = i + 1

#l = [5,4,3,2,1]
n = int(input())
l = [ int(input()) for i in range(n) ]
bubbleSort(l)
print ("The Final sorted order\t:", l )

Function Selection Sort

def selectionSort( a ):
for i in range ( len(a) ) :
smallest = i;
for j in range (i + 1,len(a)):
if (a[j] < a[smallest]):
smallest = j
if smallest != i :
a[i] , a[smallest] = a[smallest] ,a[i]
else:
break

print ( a )

l = [ 1,2,3,4,5]
selectionSort(l)
print ( l )

Function Insertion Sort

def insertionSort( A ):
for j in range ( 1 , len(A)):
key = A[j];
i = j-1;
while(i>=0 and A[i]>key):
A[i+1] = A[i];
i=i-1;

A[i+1] = key;
print(A)

l = [ 36,24,10,6,12]
insertionSort(l)
print ( l )

Explanation – Insertion sort


'''
pass 1 : j = 1 & i = 0

5 |Functions, !850,10164,Puviarasi
key = A[ 1 ] i.e key = 24
A[ 0 ] is 36
36 > 24 and 0 == 0 condition satisfied
A[ 1 ] = A[ 0 ] i.e A[1]= 36

i = i - 1 , so i = - 1
-1 ! >= 0 ,condition fails
A [ -1 + 1 ] = key i.e A[ 0 ]= 24 [ 24,36,10,6,12 ]

Pass 2 : j = 2 & i = 1
key = A[2] , i.e key = 10
36 > 10 and i > 0 condition satisfied
A[ i + 1 ] i.e A[ 2 ] = A[ 1 ] which is A[2]= 36
i = i - 1 i.e i = 0
A[ 0 ] > key , i.e 24 > 10
A[ 1 ] = A[ 0 ] which is A[ 1 ] =24
i = i - 1 i.e i = -1
A[ 0 ] = 10 [ 10,24,36,6,12 ]==>[ 6,10,24,36,12]

J=4&i=3
36 > 12 => [ 6,10,24,36,36],[6,10,24,24,36] => [ 6,10,12,24,36] '''

Recursion

def gcd( a , b ):
print ("dividend=",a)
print ("divisor=",b)
if b == 0:
return a
else:
return gcd( b , a % b )

print(gcd(18, 7))

Recursion Factorial

def factorial(n):
print("factorial has been called with n = " + str(n))
if n <= 0: #base condition
return 0
elif n == 1: #base condition
return 1
else:
res = n * factorial(n-1)

6 |Functions, !850,10164,Puviarasi
print("intermediate result for ", n, " * factorial("
,n-1, "): ",res)
return res

print(factorial(5))

n = int(input())
f = factorial(n)
print(f)
print(factorial(1))
print(factorial(-1))

7 |Functions, !850,10164,Puviarasi

You might also like