Functions in Python
What is Function in Python:
Function is a code block which is used to perform a
specific task. Functions in Python are defined by using ‘def’ keyword which is
followed by function name and pair of parenthesis which can have list of
parameters.
There are two main categories of functions. One is
built-in or library functions and second is user defined functions.
1.
Built-in Functions:
These are the functions which are already
available in language. These functions are predefined and precompiled. In Python
there are list of built-in functions. Built-in functions are also called as
library functions. Following are some built-in functions
Print(), count(), len(), range(), format(),
isinstance() etc.
2.
User Defined Functions:
User defined functions are the functions
defined by the user. User can give the name of functions as per his choice.
These functions are created to perform different tasks.
What are Advantages of Functions:
1.
Reusability of Code:
Once functions are created it can be used inside or
outside of program as per requirement for multiple times. This feature helps to
avoid writing of same task repeatedly and automatically code writing time,
extra memory space can be saved. Reusability of code also help to increase the
processing speed.
2.
Decomposition of Program:
Function helps us to decompose our large size program
into sub parts or smaller programs. This feature helps to increase the
readability of program. This also helps to avoid the complexity of problem.
How to Create Functions in Python:
Syntax:
def function_name(list of arguments):
function
body
return
statement
In the syntax,
def keyword is
used to declare or define the user defined function in Python.
Function_name is the name of the user defined function. The name is
given by user. By giving the name to function user has to follow variable
declaration rules.
List of arguments are the variables used to perform operations. Through
the arguments the values are passed to the function.
: colon is used to terminate the function header.
Body of function contains some valid python statements. All these
statements has to be followed by the indentation. Indentation usually means
four spaces.
return statement is a statement used to return values to function. Return
statement is optional.
For Example,
def addition(a,b):
# Function Declaration
sum=a+b
return
sum # Function return
In above example def keyword is used to declare the
user defined function. Addition is the name of user defined function. In the parenthesis
of addition function a,b two arguments are passed. The addition operation is
stored in sum variable and this sum variable is returned to the function.
But remember function body has no any effect unless
and until you call your function. Statements written in the function will
execute unless it is called.
Function Calling:
Syntax:
Function_name( )
function_name
is the name of user defined function it is called.
For example,
Python function to display addition of two numbers
# Function to print addition of two numbers
# Function Declaration
def addition(a,b):
sum=a+b
return
sum # Function return
# Function call
result=addition(10,30)
print("The addition is:",result)
Output:
The addition is: 40
In above program function name is addition with two
arguments a and b declared with def keyword. Addition of two variables is
stored in sum variable. The sum is returned.
Function is called and two values 10 and 30 are passed
in function call. The function call process is stored in result variable. These two values are given through result
variable to the function and result is displayed on screen. The above function
is declared with argument and with return.
When function is called the control of program goes to
the function definition. The all statements written in function definition are
executed.
If we create the functions using the arguments then we
have to call the function by passing the values to it.
Function Arguments:
The information can be passed to the function through
the arguments. Arguments are declared in function declaration in the
parenthesis of function. You can pass as many as arguments as you want but each
one of the argument is separated by comma. Arguments are the variables declared
in function declaration which takes values to perform the task or operations.
Function with No Argument and No Return Value:
#
Function Declaration
def
arith():
add=a+b
sub=a-b
mult=a*b
div=a/b
mod=a%b
print("The addition is:",add)
print("The subtraction is:",sub)
print("The Multiplication
is:",mult)
print("The division is:",div)
print("The remainder is:",mod)
# User Input
a=int(input("Enter
first number"))
b=int(input("Enter
second number"))
#
Function Call
arith()
Output:
Enter first number20
Enter second number50
The addition is: 70
The subtraction is: -30
The Multiplication is: 1000
The division is: 0.4
The remainder is: 20
Function With
Argument But No Return:
# Function with argument and with no return
def arith(a,b):
add=a+b
sub=a-b
mult=a*b
div=a/b
mod=a%b
print("The addition is:",add)
print("The subtraction is:",sub)
print("The Multiplication is:",mult)
print("The division is:",div)
print("The remainder is:",mod)
# User Input
n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
# Function Call
arith(n1,n2)
Output:
Enter first number20
Enter second number30
The addition is: 50
The subtraction is: -10
The Multiplication is: 600
The division is: 0.6666666666666666
The remainder is: 20
Function with
Argument and With Return:
# Function with argument and with return
def arith(a,b):
add=a+b
return add
# User Input
n1=int(input("Enter first number"))
n2=int(input("Enter second number"))
# Function Call
result=arith(n1,n2)
print("The addition is :",result)
Output:
Enter first number20
Enter second number20
The addition is : 40
Function without Argument and with Return
def arith():
add=a+b
return add
# User Input
a=int(input("Enter first number"))
b=int(input("Enter second number"))
# Function Call
result=arith()
print("The addition is :",result)
Output:
Enter first number20
Enter second number50
The addition is : 70
Default Argument:
When you call your function without any argument then
compiler will take default value for operation that is declared in function
declaration.
For example,
def
new_function(Name="Rohan"):
print("My Name is:"+ Name)
new_function("Isha")
new_function()
new_function("Sahil")
new_function("Soham")
new_function("Sagar")
Output:
My
Name is:Isha
My
Name is:Rohan
My
Name is:Sahil
My
Name is:Soham
My
Name is:Sagar
In above example new_function is declared with
argument name and its value is Rohan. This argument is default argument. The
new_function is called with different values but one time it is called it with
no argument in this case compiler will take for this function the default
argument declared in function declaration i.e. Rohan.
Arbitrary Argument:
When you don’t know about how many values you are
going to pass in function call, in this situation we can add * before the
parameter name in the function definition. This argument is arbitrary argument.
This will help you to pass as many
argument as you want. This will receive tuple of argument and accessed
accordingly.
For example,
def new_function(*subjects):
print("The Subjects are:",subjects )
new_function("DBMS","C++","PHP","Java")
Output:
The Subjects are: ('DBMS', 'C++', 'PHP', 'Java')
In above program new_function is declared with one
parameter and before declaring subjects parameter * is used so this is
arbitrary argument. This argument will help to pass many values. Through the
arbitrary argument compiler will return the tuple arguments.
Keyword Arguments:
If you don’t know about how many keyword arguments are
passed in your function you can use keyword arguments i.e. key=value argument
by using ** before the keyword argument in the function definition.
For example,
def new_function(**name):
print("The
largest number is:" + name["middle"])
new_function(fname="Sanoya",middle="Manohar",lname="patil")
Output:
The largest number is:Manohar
In above example in the new_function parenthesis name
argument is used with ** diuble star. So this will help to take many key=value
in function call.
0 टिप्पण्या
कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏