Module 2
Module 2
PYTHON PROGRAMMING
Functions in Python
A group of related statements to perform a specific task is known as a function. Functions helpto break the
program into smaller units. Functions avoid repetition and enhance code reusability.
Functions provide better modularity in programming. Python
provides two types of functions
• built in function
• User defined function
Functions like input(), print() etc..are examples of built in functions. Code of these functions are already
defined. We can create our own functions to perform a particular task. These functions are called user
defined functions.
1. FUNCTION DEFINITION
▪ Function block or function header begins with a keyword def followed by the
function name and parentheses ( ( ) ).
▪ Any input parameters or arguments should be placed within these parentheses. Wecan also
define parameters inside these parentheses.
▪ The first string after the function header is called the doc string and is short for
documentation string. It is used to explain in brief, what a function does. Althoughoptional,
documentation is a good programming practice.
▪ The code block within every function starts with a colon ( : ) and is indented.
▪ The return statement [ expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as returnNone.
Syntax
def functionname( parameters ):
“ function_docstring”
Function_suite Return [
expression ]
Example program
def sum_of_two_numbers(a,b):
sum = a + b
Return sum
2. FUNCTION CALLING
After defining a function, we can call the function from another function or directly from python prompt. The
order of the parameters specified in the function definition should be preserved in function call also.
Example program
a= int(input(“enter the first number:”)) b=int(input(“enter the
second number:”)) s=sum_of_two_numbers(a,b)
print(“sum of"a,”and”,b,”is",s)
1
Output
Enter the first number:4
Enter the second number:3
Sum of 4 and 3 is 7
All the parameters in Python are passed by reference. It means if we change a parameter which refers to within
a function, the change also reflects back in the calling function.
Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope.
Lifetime of a variable is the period throughout which the variable exists inthe memory. The lifetime of
variables inside a function is as long as the function executes. All variables in a program may not be accessible
at all locations in that program. This depends on where we have declared a variable. The scope of a variable
determines the portion of the program where we can access a particular identifier. They are destroyed once
we return from the function. Hence, a function does not remember the value of a variablefrom its previous
calls.
Example program
def value_change (a) : #Function Header
a=10
Print (value inside function=" ,a) #prints the value of a inside function return
#Main Program Code
a =int (input ( "Enter a number: ")
value_change (a) #Function calling
print ( "Value outside function=", a) #prints value or a outside function
output
enter a number: 3
value inside function:10
value outside function:3
3. FUNCTION ARGUMENTS
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.
Example program
a=10
return
Output
Enter a number:4
KEYWORD ARGUMENTS
When we use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows us 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.
Example program
#Function definition
def studentinfo(rollno, name, course="UG") :
“This prints a passed info into this function" print
("Roll Number: ", rollno)
print ("Name: ", name) print
("Course: ", course)
#Function calling
▪ Roll Number: 50
Name: Jack
Course: UG
Roll Number: 51
Name: Tom Course:
UG
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 shows how default arguments areinvoked.
3
Example program
#Function definition
def studentinfo(rollno, name, course="UG") :
“This prints a passed info into this function" print
("Roll Number: ", rollno)
print ("Name: ", name) print
("Course: ", course)
#Function calling
output
Roll Number: 50
Name: Jack
Course: UG
Roll Number: 51
Name: Tom Course:
UG
Syntax
"function_docstring"
function_statements
return [expression]
Example program
#Function definition
def variablelengthfunction(*argument) :
4
for i in argument: print (i)
In Python, anonymous function is a function that is defined without a name. While normal functions are
defined using the def keyword, in Python anonymous functions are defined using the lambda keyword.
Hence, anonymous functions are also called lambda functions.
CHARACTERISTICS
▪ Lambda functions can take any number of arguments but return only one value in the
form of an expression.
▪ It cannot contain multiple expressions.
▪ It cannot have comments.
▪ A lambda function cannot be a direct call to print because lambda requires an
expression.
▪ Lambda functions have their own local namespace and cannot access variables other
than those in their parameter list and those in the global namespace.
Example program
#Lambda Function definition
square=lambda x:x*x #Usage of lambda function
n=int (input (" Enter a number : ") )
print ( Square of", n, "is" , square (n) ) #Lambda function call
Output
Enter a number: 5
Square of 5 is 25
5.RECURSIVE FUNCTIONS
5
▪ Recursion is the process of defining something in terms of itself.
▪ A function can call other functions. It is possible for a function to call itself. This is
known as recursion.
Example Program
Output
Enter a number: 5
The factorial of 5 is 120
EXPLANATION
▪ When we call this function with a positive integer, it will recursively call itself by
decreasing the number.
▪ Each function call multiplies the number with the factorial of number-1 until thenumber is
equal to one.
▪ This recursive call can be explained in the following steps. Our recursion ends when the
number reduces to 1. This is called the base condition.
▪ Every recursive function must have a base condition that stops the recursion or elsethe
function calls itself infinitely.
Example Program
7.Modules Introduction
Modules refer to a file containing Python statements and definitions. A module is a Python object with
arbitrarily named attributes that we can bind and reference. We use modules to break down large programs into
small manageable and organized files. Further, modules provide reusability of code. A module can define
functions, classes and variables. A module can also include runnable code. Python has a lot of standard modules
(built-in modules) available. A full list
of Python standard modules is available in the Lib directory inside the location where you installed Python.
CREATING MODULES
We can define our most used functions in a module and import it, instead of copying their definitions into
different programs. A file containing Python code, for e.g.: prime.py, is called a module and its module name
would be prime. The Python code for a module named test normally resides in a file named test.py.
7
Let us create a module for finding the sum of two numbers. The following code creates a module in Python.
Type the code and save it as test.py.
Example
#Python Module example “””This
program adds two numbers and return
the result"""
Here we have a function sum() inside a module named test. The function takes in two numbers
and returns their sum.
8.IMPORT STATEMENT
We can use any Python source file as a module by executing an import statement in some other Python source
file. User-defined modules can be imported the same way as we import built-in modules.
We use the import keyword to do this. The import has the following syntax.
When the interpreter encounters an import statement, it imports the module if the module ispresent 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 test.py, you need to put the following command at the top of the script.
Example
import test
print (test.sum (2,3))
Output
We can import built-in or user-defined modules with an alias name. The following code shows how the built-in
module math can be imported using an alias name.
Example Program
import math as m
print ("The value of pi is", m.pi)
Output
The value of pi is 3.141592653589793
8
FROM...IMPORT STATEMENT
We can import specific names from a module without importing the module as a whole. The module math
contains a lot of built-in functions. But if we want to import only the pi function, the from...import statement
can be used. The following example illustrates importing pi from math module.
Example Program
from math import pi
print ("The value of pi is:", pi)
Output
The value of pi is: 3.14159265359
We can import all names(definitions) from a module using the following construct. The following example shows
how all the definitions from the math module can be imported.This makes all names except those beginning with an
underscore, visible in our scope.
Example Program
from math import *
print (The value of pi is:", pi)
print(“The square root of 4 is: ", sqrt (4))
Output
The value of pi is: 3.14159265359The square
root of 4 is: 2.0
LOCATING MODULES
When we import a module, the Python interpreter searches for the module in the following sequence.
2. If the module isn't found, Python then searches each directory in the shell variable
PYTHONPATH.
3. If the above two mentioned fails, Python checks the default path. On UNIX, 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.
Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys)
and their corresponding objects (values). A Python statement can access variables in a local namespace and in
the global namespace. If a local and a global variable have the same name, the local variable shadows
the global variable.
9
Each function has its own local namespace. Python makes certain guesses on whether variables are local or
global. It assumes that any variable assigned a value in a function is local. Therefore, in order to assign a value
to a global variable within a function, you must first use the global statement. The statement global
variable_name tells Python variable_name is a global variable. Once a variable is declared global, Python
stops searching the local namespace for that variable. Consider the following example.
Example Program
Add ( ):
a= a + l print
(a)
Output
Traceback (most recent call last):
File "main.py" line 5, in <modules>Add(
)
File "main.py"1ine 3, in Adda=a + l
UnboundLocalError: Local variable „a‟ referenced before assignment
When we run the above program, the output is listed above with errors. The reason is that weare trying to add 1 to
a before a is assigned a value. This is because even though a is assigneda value 10, its scope is outside the function
Add( ). Further Python always searches for variables in the local namespace.
Example Program
Output
[ „ builtins ‟ ,‟ doc ‟,‟ file ‟,‟ name ‟,‟ package ‟,‟ Sum ']
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
10
again. The syntax of the reload() function is as follows. reload (
module_name)
Here, module_name is the name of the module we want to reload and not the string containing the module name.
For example, to reload test module, do the following:
reload (test)
12.PACKAGES IN PYTHON
A package is a hierarchical file directory structure that defines a single Python application environment that
consists of modules and subpackages and so on. As our application program grows larger in size with a lot of
modules, we place similar modules in one package and
in different packages. This makes a project (program) easy to manage and different modules conceptually
clear. Similar, as a directory can contain sub-directories and files, a Python can have sub-packages and
modules. A directory must contain a file named init .py in order for Python to consider it as a package. This
file can be left empty but we generally place the code.
Create a folder names Pack outside your working folder. Now, Consider a file Asample.pyavailable in pack
directory. This file has following line of source code.
def a( ):
print (This is from A")
Similarly we have two more files Bsample.py and Csample.py available in pack directorywith the
following codes.
Bsample. py def
b( ):
print (This is from B")
Csample.py def
c( ):
print (This is from C")
Now we have three files in the same directory pack. To make all of our functions availablewhen we are
importing pack, we need to put explicit import statements in init .py as follows.
Import Pack.Asample
ImportPack.Bsample Import
Pack.Csample
After adding these lines to init .py, we have all of these functions available when we are import the pack
package. The following code shows how the package pack can be imported.
import pack.
11
import Pack.Asample as Asam Import
Bsam.b( )
Csam.c( )
13.FILE HANDLING
File is a named location on disk to store related information. It is used to permanently storedata in a non-volatile
memory (e.8. hard disk). Since, random access memory (RAM) is volatile which loses its data when computer
is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to be
closed, so that resources that are tied with the file are freed. Hence, in Python, afile operation takes place in
the following order.
a. Open a file
We have been reading and writing to the standard input and output. Now, we will see how touse actual data
files. Python provides basic functions and methods necessary to manipulate files by default. We can do most of
the file manipulation using a file object.
14.OPENING A FILE
Before we can read or write a file, we have to open it using Python's built-in open()function.This function
returns a file object, also called a handle, as it is used to read or modify the file accordingly.
We can specify the mode while opening a file. In mode, we specify whether we want to read „r‟, write 'w‟ or
append 'a' to the file. We also specify if we want to open the file in text modeor binary mode. The default is
reading in text mode. In this mode, we get strings when reading from the file. On the other hand, binary
mode returns bytes and this is the mode to beused when dealing with non-text files like image or exe files.
The following shows the syntaxfor opening a file.
Syntax
12
Example
In the above example, the file abc.txt is opened in the current working directory in read modeand sample.txt is
opened in read mode inside C: \Python33 folder.
1. 'r‟- Opens a file for reading only. The file pointer is placed at the beginning of the file. Thisis
the default mode.
2. „rb‟-Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file.
3. 'r+'- Opens a file for both reading and writing. The file pointer is placed at the beginning ofthe
file.
4. 'rb+‟ - Opens a file for both reading and writing in binary format. The file pointer is placedat
the beginning of the file.
5. 'w‟-Opens a file for writing only. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
6. 'wb'- Opens a file for writing only in binary format. Overwrites the file if the file exists. Ifthe
file does not exist, creates a new file for writing.
7. 'w+‟- Opens a file for both writing and reading. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
8. 'wb+' - Opens a file for both writing and reading in binary format. Overwrite the existingfile
if the file exists. If the file does not exist, creates a new file for reading and writing.
9. 'a‟ - Opens a file for appending. The file pointer is at the end of the file if the file exists.That
is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
10. „ab‟-open a file for appending in binary format. The file pointer is at the end of the file if the
file exists. That is, the file is in the append mode. If the file does not exist, it creates a newfile for
writing.
15.CLOSING A FILE
When we have finished the operations to a file, we need to properly close it. Python has a garbage collector
to clean up unreferenced objects. But we must not rely on it to close the file. Closing a file will free up the
resources that were tied with the file and is done using theclose( ) method. The following shows the syntax
for closing a file.
Syntax
fileObject.close ()
Example Program
# Open a file for writing in binary formatto = open
("bin.txt", "wb")
13
print (Name of the file: ",to.name)#
Close opened file
to.close ()
print ("File Closed")
Output
Name of the file: bin. txtFile
Closed
16.WRITING TO A FILE
In order to write into a file we need to open it in write 'w, append 'a or exclusive creation 'x‟ mode. We need
to be careful with the 'w‟ node as it will overwrite into the file if it already exists. All previous data will be
erased.
Writing a string or sequence of bytes (tor binary files) is done using write( ) method. This method returns the
number of characters written to the file. The write( ) method does not add a newline character ("\n”) to the end
of the string. The following shows the syntax of write( )method.
Syntax
fileobject.write (string)
Here, passed parameter string is the content to be written into the opened file
Example Program
Open ("test.txt",”w”)
fo. write("Programming with Python is Fun. \nLet' s try Python!\n”) # Close
opened file
fo.close ()
print (“Flle", fo.name, "closed.")
Output
In the above program, we have opened a file test.txt in writing mode. The string to be writtenis passed to
the write ( ) method.
To read the content of a file, we must open the file in reading mode. The read ( ) method reads a string
from an open file. It is important to note that Python strings can have binarydata, apart from text data. The
following gives the syntax for reading from a file.
14
Syntax
fileObject.read ([size])
Here, the passed parameter size is the number of bytes to be read from the opened file. This
method starts reading from the beginning of the file and if size is missing, then it tries to readas much as
possible, maybe until the end of file. The following example shows how to read from the file test.txt which we
have already created.
Example Program
Output
18.FILE METHODS
file.close( )
file.fileno( ) : Returns an integer number (file descriptor) of the file.
Example Program
Output
The file number is: 3
19.RENAMING A FILE
The os module Python provides methods that help to perform file-processing operations, such as renaming and
deleting files. To use this os module, we need to import it first and then we can call any related functions. To
rename an existing file, we can use the rename( ) method. This method takes two arguments, current filename
and new filename. The following shows the syntax for rename method.
15
Syntax
os.rename (current file _name, new_file_name)
Example Program
import os
#Rename a file from test.txt to Newtest.txt
os.rename ("test.txt", "Newtest.txt")
print (“File renamed.")
Output
File renamed.
20.DELETING A FILE
We can delete a file by using the remove( ) method available in os module. This method receives one
argument which is the filename to be deleted. The following gives the syntaxfor remove() method.
Syntax
os.remove (filename)
Output
File Deleted.
21.DIRECTORIES IN PYTHON
All files will be saved in various directories, and Python has efficient methods for handling directories and files.
The os module has several methods that help to create, remove and change directories.
4. mkdir() method
The mkdir( ) method of the os module is used to create directories in the current directory. We need to supply
an argument to this method which contains the name of the directory to be created. The following shows the
Syntax
os.mkdir(“dirname”)
Example
import os
mkdir ("Fruits")
To change the current directory, we can use the chdir( ) method. The chdir ( ) method takes an argument,
which is the name of the directory that we want to make the current directory. The following shows the
Syntax
os.chdir("dirname")
Example
import os
("/home/abc")
6. getcwd( ) method
The getcwd( ) method displays the current working directory. The following shows the syntax of getcwd( )
method.
Syntax
os.getcwd( )
Example
import os
os.getcwd( )
7. rmdir() method
The rmdir( ) method deletes the directory, which is passed as an argument in the method.
Syntax
os.rmdir ("dirname")
Example
import os
Os.rmdir(“Fruits”)
It is intended to give the exact path of a directory. Otherwise it will search the current working directory.
17