0% found this document useful (0 votes)
7 views23 pages

Unit 3 (First)

The document provides an overview of functions in Python, explaining their definition, types (standard library and user-defined), and how to declare and call them. It details various types of arguments (default, keyword, variable length, and positional) and demonstrates their usage with examples. Additionally, it covers concepts such as recursion, the map function, and the distinction between passing by value and call by reference in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views23 pages

Unit 3 (First)

The document provides an overview of functions in Python, explaining their definition, types (standard library and user-defined), and how to declare and call them. It details various types of arguments (default, keyword, variable length, and positional) and demonstrates their usage with examples. Additionally, it covers concepts such as recursion, the map function, and the distinction between passing by value and call by reference in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Function

• Functions
• A function is a block of code that performs a specific task. Dividing a
complex problem into smaller chunks makes our program easy to
understand and reuse.
• A function runs only when it is called.
• They are defined using the def keyword
• They can be called multiple times.
• Types of function(2 types)
• Standard library functions - These are built-in functions in Python
that are available to use.
• User-defined functions - We can create our own functions based on
our requirements.
• Function Declaration
• syntax
– def function_name(arguments):
– # function body
– return
• def add(x,y):
• z=x+y
• return z

• a=10
• b=20
• add(a,b)
• #print(result)
• #print ("a = {} b = {} a+b = {}".format(a, b,
result))
• # via input box
• def add():
• n=int(input("Enter the FNo"))
• b=int(input("Enter the SNo"))
• print(n+b)
• add()
• Arguments : An argument is a value that is
accepted by a function.
Information can be passed into functions
as arguments . Arguments are specified after
the function name, inside the parentheses.
You can add as many arguments as you want.
4 types of arguments that can provide in a
function :
1. Default Arguments
2. Keyword Arguments
3. Variable length Arguments
4. Required Arguments or positional
• #passing argument / parameter
• def add(y):
– X=10
– C=x+y
• print(c)
• add(50)

• #no argument but use return


• def add():
• n=int(input("Enter the FNo"))
• b=int(input("Enter the SNo"))
• return(n+b)
• x=add()
• print(x)
• # find the square of n numbers

• def get_square(num):
• return num * num

• for i in [1,2,3,4,7,9]:
• # function call
• result = get_square(i)
• print('Square of',i, '=',result)
• # argument and return
• def add(x,y):
• return(x+y)
• z=add(10,20)
• print(z)

• Note :
– A parameter is the variable listed inside the
parentheses in the function definition.
– An argument is the value that is sent to the
function when it is called.
• #factorial of any number

• def fact(x):
• i=1
• f=1
• while x>=i:
• f=f*i
• i=i+1
• print(f)
• fact(5)
Types of Actual Arguments

• 4 types :
– Positional Arguments
– Keyword Arguments
– Default Arguments
– Variable Length Arguments
• Positional Arguments
– These arguments are passed to the function in correct
positional order.
– The number of arguments and their positions in the
function definition should be equal to the number and
position of the argument in the function call.
• # Positional Arguments or actual arguments
• def pw(x,y):
• z=x**y
• print(z)
• pw(5,3)
• Default Argument :
– Default values indicate that the function argument will take
that value if no argument value is passed during function
call. The default value is assigned by using assignment (=)
operator.
• Eg :
– def defa(name,location="Janakpuri"):
– print(f"name:{name} location: {location}")
– defa("MSI")
• Variable Length Arguments, *args
– Variable length argument is an argument that can accept any number of
values. The variable length argument is written with * symbol.
– It stores all value in a tuple.
• Eg :the user doesn’t know in advance how many no of arguments
will pass, them the *args will help it.
– Def calcval(*args):
– # Print(args)
– totalval=sum(args)
– return(totalval)
– ## call the fun
– Calcval(10,30,40,80,90,100,45)

• Eg : # using slicing
– def fun(*kids):
– print("The youngest child is ", kids[1:3])

– fun("hello","I","love","Python")
• Eg : # show only index value
– def fun(*kids):
– print("The programming is ", kids[3])

– fun("hello","I","love","Python")

• Eg :
– # show all values
– def fun(*kids):
– print("The programming is ", kids)

– fun("hello","I","love","Python")
Keyword Argument

• These arguments are passed to the function


with “name-value pair”. the keyword
arguments name and formal arguments name
must match.
• Note : number of argument must be equal in
formal and actual argument, not more not
less.
• Eg :
– def show(name,age):
– # print(name,age)
– print(f"Name:{name} Age:{age}")
– show(name="Sam Uncle",age=23)
• Keyword Variable Length Arguments
(**kwargs) :
– Is an argument that can accept any number of
values in form of “KEY-VALUE” pair.
– The keyword variable length argument is written
with ** symbol.
– It stores all the value in a dictionary in the form of
key-value pair.
• def add(**num):
• z=num['a']+num['b']+num['c']
• print("Addition is : ",z)
• add(a=10,b=20,c=30)
• Eg :
– # pass any variable
– def add(x,**num):
– z=x+num['a']+num['b']
– print("Addition is : ",z)
– add(40,a=10,b=20)
• map()
– The map() function applies a given function to
each element of an iterable (list, tuple etc.) and
returns an iterator containing the results.
– Syntax :
• Map(function,iterable,….)
• map() Return Value
– The map() function returns an object of map class.
The returned value can be passed to functions like
– list() - to convert to list
– set() - to convert to a set, and so on.
• def make_even(num):
• if num%2==0:
• return num+1
• else:
• return num


• x=[551,663,523,842,954,781,630,546]
• y=list(map(make_even,x))
• print(y)
• Eg :
– def calculateSquare(n):
– return n*n

– numbers = (1, 2, 3, 4)
– result = map(calculateSquare, numbers)
– print(result)

– # converting map object to set


– numbersSquare = set(result)
– print(numbersSquare)
Recursion
• A function calling itself again and again to compute a value is referred to
recursive or recursion.
• eg :
– # a Recursive function can call itself only 1000 times in IDLE in python, but in
jupyter its limit is 3000
– def myfun():
– print("Recursion")
– myfun()
– myfun()
• ### to check the Limit
• import sys
• print(sys.getrecursionlimit())

• # ### to set the Limit


• import sys
• sys.setrecursionlimit(500)
• print(sys.getrecursionlimit())
• #to print fibonacci series
• n=int(input("enter Number"))
• x=0
• y=1
• z=0
• while(z<=n):
• print(z)
• x=y
• y=z
• z=x+y
• Eg : through Recursion
– def fibo(i):
– if i<=1:
– return i
– else:
– return fibo(i-1)+fibo(1-2)

– #main code
– for i in range(10):
– print(fibo(i),end=',')
• # factorial of no

• def fact(num):
• if num==1:
• return num
• return num*fact(num-1)
• number=int(input("Enter a number : "))
• result=fact(number)
• print("factorail of ",number," is ",result)

• #program to find of a list of numbers using recursion


• def sum_list(nums):
• if len(nums)==0:
• return 0
• return nums[0]+sum_list(nums[1:])
• numbers=[]
• n=int(input("Enter how many number are there in a list : "))
• for a in range(n):
• num=int(input("Enter a number : "))
• numbers.append(num)
• print("List is ",numbers)
• print("sum of list is ",sum_list(numbers))
Pass by value / Call by Reference

• In python neither of these two concepts is


applicable rather the values are sent to
functions by means of object reference.
• When we pass value like number, strings,
tuples or list to function the reference of these
objects are passed to function.

You might also like