Function In Python
In this we will lean about the function and it's important in programmimg and also created different function to undestanding all in details.
simply, function is the piece of code which is wirtten to perform a particular task .
syntax of function look like :
#syntax of function
def function_name(argument_list):
local_variable
block_of_statement
return (variable or expression)
There are two type of function in programmimg language
1.Built in function
These are the function which are provided by programming language for a common ,difficult task . example like int(),upper(),type() and many more.
2.User define function
Thesea re the function which are written by the programmer according to the requirements.
Example :
#nested function
def add(a,b):
def sub(a,b):
return a-b
print(sub(a,b))
return a+b
print(add(10,5))
"""
5
15
"""
#pass function as a parameter
def greet(my_fun):
return "hello"+" "+my_fun()
def name():
return "Amrit"
print(greet(name))
# hello Amrit
#function return another function
def greet():
print("hello")
def name():
return "Amrit"
return name
my_fun=greet()
print(my_fun())
"""
hello
Amrit
"""
Actual and Formal argument
function call arguments are actual arguments
function defination parameters are called formal arguments
def add(a,b):
# these a and b are formal arguments
return a+b
add(5,7) #actual arguments
Actual Arguments type
1.positional arguments -> maintain position,arguments number should be same
2.keyword arguments -> arguments are passed in the form of key value pair,name must be match,position can be change
3.default arguments
#default argument
def show(name='amrit',age=24):
pass
show("amrit")
show("amrit",age=23) #priority while defining here is high
4.variable length arguments
It is an arguments that can accepts any number of values.The variable length argument is written with * symbol. it store all the value in tuple.
#variable length arguments
def add(*num):
sum=0
for i in range(len(num)):
sum+=num[i]
print(sum)
add(1,2,3,4,5,6,7,8,9,10)
#55
def add(first,*num):
print(first)
print(*num)
add(1,2,3,4,5,6,7,8,9,10)
"""
1
2 3 4 5 6 7 8 9 10
"""
5.keyword variable length arguments
It sis an arguments that can accepts any number of values passed in the form of key-value pair. The key word variables arguments are written with **symbol. it store all the value in the form of dictionary.
#key-word variable length arguments
def add(**num):
# print(**num)
return num['a']+num['b']+num['c']
fun=add(a=1,b=2,c=3)
print(fun)
#6
Anonymous function or lambda function
A function without a name is called as anonymous functuion . it is also knows as lambda function. it is not define using the def keyword rather than using lambda keyword.
syntax: lambda argument-list: expression
example" lambda x,y:x+y
properties:
1.lambda function doesnot have any name
2.it return a function
3.can take zero or any number of arguments but cantains only one expression
#lambda function
add_sub=lambda x,y:(x+y,x-y)
add,sub=add_sub(10,5)
print(add)
print(sub)
"""
10
15
"""
#example-2
add=lambda x,y=5:x+y
print(add(5))
#10
Nested lambda function
when we write lambda function inside another lambda function that is nested lambda function
#nested lambda function
add=lambda x=10:(lambda y:x+y)
a=add() # "a" is a function variable where the expression lie
print(a(20)) #inside "a" there is y:x+y
#8
# returning lambda function from a function
def add():
y=20
return (lambda x:x+y)
a=add()
print(a(10))
#30
IIFE(immediately invoked function expression)
# IIFE
x=(lambda x:x+1) (10)
y=(lambda x,y:x+y) (2,3)
print(x)
print(y)
#11
#5
Scope of variable
1.local variable
variable which sre define inside the function is called local variable. it's scope is limited only inside to that function where it is created.
2.global variable
when a variable is define outside the function , it become global variable . these variable are available to all the functions which are written after it.
i=0
def my_fun():
i=i+1
print(i)
my_fun()
#erroor
#UnboundLocalError: local variable 'i' referenced before assignment
it will used the local variable "i" not global .
global keyword
if local variable and the global variable has a same name, then function by default refers the local variable and ignore the global variable. it means global variable is not accessible inside the function but possible to access outside of function.
In this situation, if we need to access global variable inside the function we can access it using keyword global followed by variable name..
i=0
def my_fun():
global i
i=i+1
print(i)
my_fun()
print(i) #global variable is modefied entire in the program
#1
#1
global function
This function returns a table of current global variable in the form of dictionary.
a=50
def show():
a=10
print(a)
x=globals()['a']
x=30 #this modified is not global value
print(x)
show()
print(a)
#10
#30
#50
Recursion
A function calling itself again and again to compute a value is refers to as a recursive function or recursion.
#recursion function
i=0
def show():
global i
i+=1
print(i)
show()
# show()
#by default in python it will run 1000 time
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(10)
print(sys.getrecursionlimit())
print("############################")
show()
call/pass by object reference
In c,jaav and other programming we pass a value to a function either by a value or by reference widely khown as "pass by value" and "pass by reference".
In python , neither of these two concept is applicable rather the value are sent to functions by means of object reference.
def val(x):
x=15
print(x,id(x))
x=10
val(x)
print(x,id(x))
"""
15 140196604543664
10 140196604543504
"""
A new object is created in memory for x=15, because integer object is not immutable.
def val(lst):
lst.append(4)
print(x,id(x))
x=[1,2,3]
val(x)
print(x,id(x))
"""
[1, 2, 3, 4] 139825902642496
[1, 2, 3, 4] 139825902642496
"""
So when a list is created then new list is not made new object but it will be togeher the same object with modified values. A new object is not create din memory because list is mutable (modifiable) so it simply add new element to the same object.
Conclusion
-> In python , avalue are passed to function by object reference.
-> If object is immutable, then the modified value is not available outside the function.
-> if object is mutable thn the modified value is available outside the function.
Note:
immutable objects: integer,float,string,tuple
mutable objects: list,dictionary