Function in Python
Function in Python
1.What is a Function?
2.Function Call
3.Parameters &
Arguments
4.Return Statement
5.Documentation string
-prepared by
Priyanka Patel
What is Function ?
A function is a block of organized,
reusable code that is used to perform a
single, related action. Functions provide
better modularity for your application
and a high degree of code reusing.
-prepared by Priyanka
Patel 2
Function Call
Once the function is definition and structured correctly, we have to call the function to
execute it statement otherwise your function does nothing. For example,
my_first_function() in the below program is a function call. A function can be even
called multiple times in a program.
-prepared by Priyanka
Patel 3
Parameters & Argument
Function Arguments
You can call a function by using the following types of Exaplm
# :Function definition is here
e
formal arguments − def printme( str ):
"This prints a passed string into this
• Required arguments function"
• Keyword arguments print str return;
• Default arguments
• Variable-length arguments: # Now you can call printme function
printme()
-prepared by Priyanka
Patel 5
Parameters & Argument
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives an
idea on default arguments, it prints default age if it is not passed −
-prepared by Priyanka
Patel 6
Parameters & Argument
Variable-length arguments
You may need to process a function for more arguments than you specified while
defining the function. These arguments are called variable-length arguments and
are not named in the function definition, unlike required and default arguments.
# Function definition is here
def printinfo( arg1, *vartuple ): Output is: 10
"This prints a variable passed
arguments“
Output is: 70 60
print "Output is: "
print arg1 for var in vartuple: 50
print var return;
-prepared by Priyanka
Patel 7
Return Statement
The return statement returns with a value from a function instead of printing
it out. It allows us to assign the output of the new function to a new variable.
It is the last statement to be executed inside the function, meaning the return
statement exits the function.
# A Python program to return multiple
# values from a method using class
class Test:
def __init__(self):
self.str = “Priyanka Patel" Output:
self.x = 20
Priyanka Patel
# This function returns an object of Test
def fun(): 20
return Test()
print(square.__doc__)
Output:
-prepared by Priyanka
9
Patel
thank you
Priyanka Patel
20SOECE11109
ppatel879@rku.ac.in