Functions:: Difference Between A Function and A Method
Functions:: Difference Between A Function and A Method
FUNCTIONS:
A function is a block of organized, reusable code that is used to perform a single,
related action.
Once a function is written, it can be reused as and when required. So, functions are also
called reusable code.
Functions provide modularity for programming. A module represents a part of the
program. Usually, a programmer divides the main task into smaller sub tasks called
modules.
Code maintenance will become easy because of functions. When a new feature has to be
added to the existing software, a new function can be written and integrated into the
software.
When there is an error in the software, the corresponding function can be modified
without disturbing the other functions in the software.
The use of functions in a program will reduce the length of the program.
As you already know, Python gives you many built-in functions like sqrt( ), etc. but you can
also create your own functions. These functions are called user-defined functions.
We can return the result or output from the function using a „return‟ statement in the
function body. When a function does not return any result, we need not write the return
statement in the body of the function.
Q) Write a program to find the sum of two numbers and return the result from the
function.
def add(a,b):
"""This function sum the numbers""" c=a+b
return c print add(5,12) # 17
print add(1.5,6) #6.5
Returning multiple values from a function:
A function can returns a single value in the programming languages like C, C++ and
JAVA. But, in python, a function can return multiple values. When a function calculates
multiple results and wants to return the results, we can use return statement as:
return a, b, c
Here, three values which are in „a‟, „b‟ and „c‟ are returned. These values are returned by the
function as a tuple. To grab these values, we can three variables at the time of calling the
function as:
x, y, z = functionName( )
Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.
Example:
def calc(a,b):
c=a+b
d=a-b
e=a*b
return c,d,e
x,y,z=calc(5,8)
print "Addition=",x
print "Subtraction=",y
print "Multiplication=",z
Pass by Value:
Pass by value represents that a copy of the variable value is passed to the function and
any modifications to that value will not reflect outside the function. In python, the values are
sent to functions by means of object references. We know everything is considered as an
object in python. All numbers, strings, tuples, lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a memory block
where we can store some value. In this case, an object with the value „10‟ is created
in memory for which a name „x‟ is attached. So, 10 is the object and „x‟ is the name or tag
given to that object. Also, objects are created on heap memory which is a very huge memory
that depends on the RAM of our computer system.
Example: A Python program to pass an integer to a function and modify it.
def modify(x):
x=15
print "inside",x,id(x)
x=10
modify(x)
print "outside",x,id(x)
Output:
inside 15 6356456
outside 10 6356516
From the output, we can understand that the value of „x‟ in the function is 15 and that is not
available outside the function. When we call the modify( ) function and pass „x‟ as:
modify(x)
We should remember that we are passing the object references to the modify( ) function. The
object is 10 and its references name is „x‟. This is being passed to the modify( ) function.
Inside the function, we are using:
x=15
This means another object 15 is created in memory and that object is referenced by
the name „x‟. The reason why another object is created in the memory is that the integer
objects are immutable (not modifiable). So in the function, when we display „x‟ value, it
will display 15. Once we come outside the function and display „x‟ value, it will display
numbers of „x‟ inside and outside the function, and we see different numbers since they
are different objects.
In python, integers, floats, strings and tuples are immutable. That means their data
cannot be modified. When we try to change their value, a new object is created with the
modified value.
b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their names. For
example, the definition of a function that displays grocery item and its price can be written
as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can mention which
value is for what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another keyword „price‟ and
its value. Please observe these keywords are nothing but the parameter names which receive
these values. We can change the order of the arguments as:
grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not be any problem
as the parameter names will guide where to store that value.
def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments
Output:
item= sugar
price= 50.75
item= oil
price= 88.0
c) Default Arguments:
We can mention some default value for the function parameters in the definition.
Let‟s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But the
second argument is „price‟ and its default value is mentioned to be 40.00. at the time of
calling this function, if we do not pass „price‟ value, then the default value of 40.00
is taken. If we mention the „price‟ value, then that mentioned value is utilized. So, a
default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
Example: def grocery(item,price=40.00):
Output: print "item=",item
print "price=",price
item= sugar
grocery(item="sugar",price=50.75)
price= 50.75
grocery(item="oil")
item= oil
p rice= 40.0
d) Variable Length Arguments:
Sometimes, the programmer does not know how many values a function may receive. In that
case, the programmer cannot decide how many arguments to be given in the function
definition. for example, if the programmer is writing a function to add two numbers, he/she
can write:
add(a,b)
But, the user who is using this function may want to use this function to find sum of three
numbers. In that case, there is a chance that the user may provide 3 arguments to this function
as:
add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the programmer want to
develop a function that can accept „n‟ arguments, that is also possible in python. For
this purpose, a variable length argument is used in the function definition. a variable length
argument is an argument that can accept any number of values. The variable length argument
is written with a „*‟ symbol before it in the function definition as:
def add(farg, *args):
here, „farg‟ is the formal; argument and „*args‟ represents variable length argument. We
can pass 1 or more values to this „*args‟ and it will store them all in a tuple.
Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print "sum is",sum+farg
add(5,10)
add(5,10,20)
add(5,10,20,30)
Output:
sum is 15
sum is 35
sum is 65
Examples of reduce ( )
Determining the maximum of a list of numerical values by using reduce:
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>
Calculating the sum of the numbers from 1 to 100:
>>> reduce(lambda x, y: x+y, range(1,101))
5050
Function Decorators:
A decorator is a function that accepts a function as parameter and returns a function.
A decorator takes the result of a function, modifies the result and returns it. Thus decorators
are useful to perform some additional processing required by a function.
The following steps are generally involved in creation of decorators:
We should define a decorator function with another function name as parameter.
We should define a function inside the decorator function. This function actually modifies
or decorates the value of the function passed to the decorator function.
Return the inner function that has processed or decorated the value.
Example-1:
def decor(fun):
def inner():
value=fun()
return value+2
return inner
def num():
return 10
result=decor(num)
print result()
Output:
12
To apply the decorator to any function, we can use ‘@’ symbol and decorator name just
above the function definition.
Example-2: A python program to create two decorators.
def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def decor2(fun):
def inner():
value=fun()
return value*2
return inner
def num():
return 10
result=decor1(decor2(num))
print result()
Output:
22
Example-3: A python program to create two decorators to the same function using „@‟
symbol.
def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def decor2(fun):
def inner():
value=fun()
return value*2
return inner
@decor1
@decor2
def num():
return 10
print num()
Output:
22
Function Generators:
A generator is a function that produces a sequence of results instead of a single value.
„yield‟ statement is used to return the
value. def mygen(n):
i=0
while i < n:
yield i
i += 1
g=mygen(6)
for i in g:
print i,
Output:
012345
Note: „yield‟ statement can be used to hold the sequence of results and return it.
Modules:
A module is a file containing Python definitions and statements. The file name is the
module name with the suffix.py appended. Within a module, the module‟s name (as a
string) is available as the value of the global variable __name . For instance, use your
favourite text editor to create a file called fibo.py in the current directory with the following
contents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
>>> import fibo
This does not enter the names of the functions defined in fibo directly in the current symbol
table; it only enters the module name fibo there. Using the module name you can access the
functions:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo. name 'fibo'
from statement:
A module can contain executable statements as well as function definitions. These
statements are intended to initialize the module. They are executed only the first time the
module name is encountered in an import statement. (They are also run if the file is
executed as a script.)
Each module has its own private symbol table, which is used as the global symbol table by
all functions defined in the module. Thus, the author of a module can use global variables
in the module without worrying about accidental clashes with a user‟s global variables.
On the other hand, if you know what you are doing you can touch a module‟s global
variables with the same notation used to refer to its functions, modname.itemname.
Modules can import other modules. It is customary but not required to place all import
statements at the beginning of a module (or script, for that matter). The imported module
names are placed in the importing module‟s global symbol table.
There is a variant of the import statement that imports names from a module directly into
the importing module‟s symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local
symbol table (so in the example, fibo is not defined).
The requests and flask Packages are downloaded from internet. To download install the
packages follow the commands
Installation of requests Package:
Command: cd C:\Python27\Scripts
Command: pip install requests