Function is a block of code which provides the reusability of code. There are two types of functions –
- Built – in function (Already created i.e. predefined)
- User defined function (Created by users according to the requirements)
Defining a Function:
A function contains following format –
def <function_name> (arg1, arg2,… argN): <statements> return <value>
1. def keyword is used to start the Function Definition
2. def is followed by function-name which is followed by parenthesis which contains the arguments passed by the user and use the colon at the end
3. Statement specify the body of function.
4. Return sends a result object back to the caller
def sum(x, y): # function name is sum contains two parameters i.e. x and y z=x + y # body of function return z # return value z
Calling of above function
sum(5,10) # arguments in parentheses
Scope of variable
Scope of program means the portion of the program where you can access a particular identifier. There are two types of scope of variable –
- Local Variable
- Global Variable
Local variables – The variables which can only accessed in that function where it is declared. Outside the function body it cannot be accessed.
def sum(x, y): z=x + y print z # print 8 return sum(2,6) print z # shows error
Variable which is declared outside the function is known as global variable. It can be accessed anywhere throughout the program.
x=20 def sum(y): z=x + y print z # print 30 return sum(10) print x # print 20
Functions which have no name is known as anonymous function which is created by using lambda. Lambda is created without using the def keyword.
lambda arg1,arg2,arg3,…,arg n :expression
sum=lambda i1: i1+i1 print "Sum is",sum(20)
Sum is 40
This blog will help you get a better understanding of Automate Your Coding with Python!