Unit - Iv: UNIT - IV Syllabus: Functions - Defining Functions, Calling Functions, Passing
Unit - Iv: UNIT - IV Syllabus: Functions - Defining Functions, Calling Functions, Passing
Unit - Iv: UNIT - IV Syllabus: Functions - Defining Functions, Calling Functions, Passing
UNIT – IV
FUNCTIONS :
A function is a block of organized, reusable code that is used to perform
a single, related action. Functions provide better modularity for our application and
a high degree of code reusing.
Python supports both built-in functions such as print() and user-defined functions.
Defining a Function:
We can define functions to provide the required functionality. Here are simple rules
to define a function in Python.
1. Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
2. Any input parameters or arguments should be placed within these parentheses.
You can also define parameters inside these parentheses.
3. The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
4. The code block within every function starts with a colon (:) and is indented.
5. The statement return [expression] exits a function, optionally passing back an
expression to the caller. A return statement with no arguments is same as return
None.
Syntax :
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in
the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on standard
screen.
def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it
from another function or directly from the Python prompt. Following is the example
to call printme() function:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function");
When the above code is executed, it produces the following result:
I'm first call to user defined function!
Again second call to the same function
Passing arguments:
A function can be called in one of the two methods . which are
1. Pass by value
2. Pass by reference
There is one more example where argument is being passed by reference and the
reference is being overwritten inside the called function.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
#"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this
would produce the following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Example3:
>>> def func1(list):
... print list
... list = [47,11]
... print list
...
>>> fib = [0,1,1,2,3,5,8]
>>> func1(fib)
[0, 1, 1, 2, 3, 5, 8]
[47, 11]
>>> print fib
[0, 1, 1, 2, 3, 5, 8]
>>>
This changes drastically, if we include something in the list by using +=. To
show this, we have a different function func2() in the following example:
>>> def func2(list):
... print list
... list += [47,11]
... print list
...
>>> fib = [0,1,1,2,3,5,8]
>>> func2(fib)
[0, 1, 1, 2, 3, 5, 8]
[0, 1, 1, 2, 3, 5, 8, 47, 11]
Required Arguments:
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
For Example:
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme();
When the above code is executed, it produces the following result:
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword Arguments:
Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters
For Example:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme( str = "My string");
When the above code is executed, it produces the following result:
My string
example : the order of parameters does not matter.
#!/usr/bin/python
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
When the above code is executed, it produces the following result:
Name: miki
Age 50
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, prints
default age if it is not passed:
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name;
print "Age ", age;
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" );
printinfo( name="miki" );
When the above code is executed, it produces the following result:
Name: miki
Age 50
Name: miki
Age 35
1. Lambda forms can take any number of arguments but return just one value in
the form of an expression. They cannot contain commands or multiple expressions.
2. An anonymous function cannot be a direct call to print because lambda requires
an expression.
3. Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
4. Although it appears that lambda's are a one-line version of a function, they are
not equivalent to inline statements in C or C++, whose purpose is by passing
function stack allocation during invocation for performance reasons.
Syntax :
The syntax of lambda functions contains only a single statement, which is as
follows:
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works:
#!/usr/bin/python
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result:
Value of total : 30
Value of total : 40
MODULES :
Modules in Python are simply Python files with the .py extension, which implement a set
of functions. Modules are imported from other modules using the import command.
If we want to import the module urllib, which enables us to create read data from
URLs, we simply import the module:
We can look for which functions are implemented in each module by using
the dir function:
>>> import urllib
>>> dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener',
'__all__', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '__version__', '_ftperrors', '_get_proxies',
'_get_proxy_settings', '_have_ssl', '_hexdig', '_hextochr',
'_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog',
'_passwdprog', '_portprog', '_queryprog', '_safe_map',
'_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener',
'_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo',
'addinfourl', 'always_safe', 'basejoin', 'c', 'ftpcache', 'ftperrors',
'ftpwrapper', 'getproxies', 'getproxies_environment',
'getproxies_macosx_sysconf', 'i', 'localhost', 'main', 'noheaders',
'os', 'pathname2url', 'proxy_bypass', 'proxy_bypass_environment',
'proxy_bypass_macosx_sysconf', 'quote', 'quote_plus', 'reporthook',
'socket', 'splitattr', 'splithost', 'splitnport', 'splitpasswd',
'splitport', 'splitquery', 'splittag', 'splittype', 'splituser',
'splitvalue', 'ssl', 'string', 'sys', 'test', 'test1', 'thishost',
'time', 'toBytes', 'unquote', 'unquote_plus', 'unwrap',
'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve']
When we find the function in the module we want to use, we can read about it more
using the help function, inside the Python interpreter:
help(urllib.urlopen)
Creating modules: Writing Python modules is very simple. To create a module of your
own, simply create a new .py file with the module name, and then import it using the
Python file name (without the .py extension) using the import command.
A module allows us to logically organize our Python code. Grouping related code
into a module makes the code easier to understand and use. A module is a Python
object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define functions,
classes and variables. A module can also include runnable code.
Example:
The Python code for a module named aname normally resides in a file named
aname.py. Here is an example of a simple module, support.py
def print_func( par ):
print "Hello : ", par
return
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path. A search path is a list of directories that the
interpreter searches before importing a module. For example, to import the module
hello.py, you need to put the following command at the top of the script:
#!/usr/bin/python
# Import module support
import support
# Now you can call defined function that module as follows
support.print_func("Zara")
When the above code is executed, it produces the following result:
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple
imports occur.
This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table
of the importing module.
Locating Modules:
When you import a module, the Python interpreter searches for the module in the
following sequences:
1. The current directory.
2. If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
3.If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory, PYTHONPATH, and
the installation-dependent default.
ThePYTHONPATHVariable:L
The PYTHONPATH is an environment variable, consisting of a list of directories. The
syntax of PYTHONPATH is the same as that of the shell variable PATH.
Here is a typical PYTHONPATH from a Windows system:
set PYTHONPATH=c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python
For example, we define a variable Money in the global namespace. Within the
functionMoney, we assign Money a value, therefore Python assumes Money as a
local variable. However, we accessed the value of the local variable Money before
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
When the module is imported into a script, the code in the top-level portion of a
module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use the
reload()function. The reload() function imports a previously imported module again.
The syntax of the reload() function is this:
reload(module_name)
Here, module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do the
following:
reload(hello)
Packages in Python
Creating packages:
Packages are namespaces which contain multiple packages and modules themselves.
They are simply directories, but Each package in Python is a directory
which MUST contain a special file called __init__.py. This file can be empty, and it
indicates that the directory it contains is a Python package, so it can be imported the
same way a module can be imported.
If we create a directory called foo, which marks the package name, we can then create
a module inside that package called bar. We also must not forget to add
the __init__.py file inside the foo directory.
In the first method, we must use the foo prefix whenever we access the module bar. In
the second method, we don't, because we import the module to our module's
namespace.
The __init__.py file can also decide which modules the package exports as the API,
while keeping other modules internal, by overriding the __all__ variable, like so:
__init__.py:
__all__ = ["bar"]
To make all of your functions available when you've imported Phone, you need to
put explicit import statements in __init__.py as follows:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available
when you import the Phone package.
#!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result:
I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
The above example contains a single functions in each file, but we can keep
multiple functions in our files. we can also define different Python classes in those
files and then you can create our packages out of those classes.