Functions
Functions
FUNCTIONS
Functions
Function Arguments
Lambda Functions
• Package up and parameterize functionality
• Function Types:
Global functions # accessible in same module (.py file)
Local functions # defined inside other functions as helper
lambda functions # expressions; created at the point of use
Recursive functions
• Syntax:
def <function-name> ( parameters ):
function-suite comma-separated identifiers
return [expression]
#1
def sum_of_numbers(x,y):
'''This function finds the
sum of 2 numbers''' # function docString
return x+y
Result 1 : -50
result = abs(maxim(l2))
Result 2 : 10
print('Result 2 : ',result)
Result 3 : 0 1 2 3 4
print('Result 3 : ',end=' ')
for i in range( maxim(l1) ):
print(i, end=' ')
def shorten(text, length = 15, indicators = '...' ): # Default Arguments
if len(text) >= length:
text = text[:length - len(indicators)] + indicators
return text
Winnie
# Function calls ---
print(shorten('Winnie the Pooh', 10, '---')) # Positional Arguments Winn...
print(shorten(length = 7, text = 'Winnie the Pooh')) # Keyword Arguments
print(shorten('Winnie the Pooh', indicators='&', length = 10)) Winnie
# Positional and Keyword arguments th&
print(shorten('Winnie the Pooh')) # Positional Argument Winnie the
P...
# Variable no. of Positional Arguments
def listings ( a, b, *l ):
print('List : ', end = ' ')
for i in l:
print( i ,end = ',')
List : 123,1234,12345,
List : 3,4,5,
l1 = [1,2,3,4,5]
listings(*l1) #unpacking operator
# Variable no. of Keyword Arguments
def print_digits(n):
for d in n:
print( diction[int(d)], end=' ' )
<expression> - no branches
no loops 5 files processed
no return statement
(3) s = lambda x: ' 'if x==1 else 's'
Eg: (1) square = lambda x : x * x print('{0} file{1} processed'. format(5,s(5)))
print(square(2)) 4
(4) x = lambda a : a + a * 0.1
print(x(10))
(2) sum = lambda x,y : x + y 11.0
30
print(sum(10,20))
Use of lambda functions: (b) old = [2, 31, 42, 11, 6, 5, 23, 44]
new = list( filter( lambda x: x%2!=0, old))
(a) def myfn(n): print(new)
[31, 11, 5, 23]
return lambda a: a*n
n1 = int(input('Number 1 : '))
n2 = int(input('Number 2 : '))
s,d,p,v = calculate(n1,n2)
print('Sum = ',s)
print('Difference = ',d)
print('Product = ',p)
print('Division = ',v)
Viva Questions – 1.12.2021
1. Predict the output:
‘-‘.join(‘12345’)
‘-‘.join([‘984’,’749’,’6143’])
2. What is slicing in Python?
3. Why do we need membership operator?
4. How to remove leading whitespaces from a string in Python?
5. What is negative index in Python?