Functions and Files
UNIT 11 FUNCTIONS AND FILE HANDLING Handling in Python
IN PYTHON
Structure
11.0Introduction
11.1 Objectives
11.2Function definition and calling
11.3 Function Scope
11.4 Function arguments
11.5 Returning from a function
11.6 Function objects
11.7 Lambda / Anonymous Functions
11.8 File Operations
11.9 Summary
11.0 INTRODUCTION
Python provides a way of organizing the tasks into more manageable units called
functions. Functions make the code modular which is one of the characteristics of an
object oriented programming language (OOPs). Modularity is the process of
decomposing a problem into set of sub-problems so as to reduce the complexity of a
problem. It also makes the code reusable. File handling is another important aspect
discussed in this unit. File handling includes- creation, deletion and manipulations of
files using python programming.
11.1 OBJECTIVES
After completing this unit, you will be able to
Perform functions definition and calling
Understand scope of functions
Define function objects
Create lambda fnctions
Understand basic file operations
11.2 FUCNTION DEFINITION AND
CALLING
A function is block of code that performs a specific task. When the size of a program
increases, its complexity also increases. Hence, it becomes important to organize the
program into more manageable units. Further, it makes the code reusable.
There are three types of functions in python-
279
1. Built-in functions – these are the functions which are already defined in the Funct
language. Exampleprint( ), max( ), input( ), etc. Hand
2. User Defined functions- these are the functions that can be created or
defined by the users according to their needs.
3. Anonymous functions
11.2.1 Creating user defined functions
A function can be defined using def statement and giving suitable name to a
function by following the rules of identifiers. The process of defining a function is
called function definition.
Syntax of function definition
Deffunction_name( list_of_parameters ) :
Statement (s)
Where,
function_name() - is the name of the function. A function name must be followed
by a set of parenthesis. Any name can be given to a function following the rules of
identifiers.
List_of _parameters –is an optional field which is used to pass values or inputs to a
function. It can be none or a comma separated list of variables.
Statements(s) – is a set of statements or commands within the function. Each time
the function is called, all the statements will be executed. These statements together
form the body of a function.
Even if the function is defined, it can never be executed till the time it is called.
Hence, for using a function, it must be called using function call statement. A
function can be called by its name with set of parenthesis and optional list of
arguments.
Syntax of Function Calling
function_name(list_of_arguments)
Example1. A function to display HELLO WORLD
Function needs to be defined only once, but it can be called any number of times by
using calling statements. They can not only be called in the same program, but they
can also be called in different programs. This will further be discussed in the next
chapter.
280
Another example shown below is the program having a function to calculate Functions and Files
factorial of a number. Handling in Python
Example2. A function to display factorial of a number.
11.3 FUNCTION SCOPE
Part of a code in which a variable can be accessed is called Scope of a variable.
Scope of a variable can be global or local.
Local variables are the variable created within a function’s body or function’s
scope. They cannot be accessed outside the function. Their scope is only limited to
the function in which they are created.
Global variables are the variable created outside any function. Their scope is
global, hence can be used anywhere. Global variables can also be created within
function using keyword global.
Example 3. Use of local and global variables.
In Example 3, variable created x is global, hence, can be used both inside and
outside any function. Variable y is created inside function test(), therefore, its scope
is only limited to this function and hence cannot be used outside.Global variables
can be created in functions using global keyword as shown in example 4.
281
Example 4: Program to create global variable inside function. Funct
Hand
If we create a variable inside function having same name as that of global variable,
then a separate variable of same name gets created. Function in this case can access
local variable and hence, cannot refer to global variable as shown in example 5.
Example 5: Program showing use of Local and global variables of same name.
In python, global variable can be accessed in function directly (as shown in Example
3) but they cannot be directly modified inside the function (shown in example 6).
Then how can we modify global variables inside function? Answer to this question
is throughglobal keyword. It can not only be used for creating global variables
inside functions, but it can also be used for modifying global variables inside
functions. See example 7.
Example 6: Program to show modification of global variable is not allowed inside
function
282
Functions and Files
Example 7: Program to show modification of global variable using global keyword Handling in Python
Check your Progress 1
Ex1. What are the benefits of using functions? Also differentiate between function
definition and function calling.
Ex2. What is Scope of a variable? Explain local and global variables with example.
Ex3. Write a function named patternto display the pattern given below-
1
12
123
1234
12345
11.4 FUNCTION ARGUMENTS
Arguments are a way of passing values or input to a function. Arguments are passed
to a function during function calls. Their values replace the functions parameters in
the function definition.
Python provides various mechanisms of passing arguments to a function.
1. Required arguments
2. Default arguments
3. Keyword arguments
4. Arbitrary arguments
1. Required Arguments or Positional Arguments
In required arguments, number of arguments should match number of function
parameters and should be given in same order. If number of arguments is not the
same, then error will be shown and if correct order is not followed then output can
be incorrect.
Example 8: Passing arguments to a function.
283
Funct
Hand
2. Default arguments
Default values of variables can be given in the parameters itself. So if any argument
is not given at the calling time, it will be replaced by the default value. Default
values can be given for any number of arguments. It must be taken care that default
argument must follow non-default arguments.
Example 9: Use of Default Arguments
3. Keyword Arguments
We have seen above that arguments must be given in the order in which parameters
are defined otherwise the result will be effected. Keyword arguments are one way by
which we can give arguments in any order. They are given by specifying the
parameter name with each argument during function call. In this case position does
not matter but name matters hence they are also called named arguments.
284
Example 10: Use of Keyword Arguments Functions and Files
Handling in Python
4. Arbitrary Arguments
Sometimes it is required to pass different number of arguments to a same function or
it is not known at function definition time that how many arguments could be used at
calling time. Python provides the feature of arbitrary arguments to deal with this
issue. Arbitrary arguments can be declared using * symbol.
Example11: Use of Arbitrary Arguments
11.5 RETURNING FROM A FUNCTION
As we can pass values as input to function parameters, similarly we can also return
or extract values out of a function. This can be done using return statement. By
default when we do not include return statement, value None is returned from the
function.
Syntax of returning from function
deffunction_name( arg1,arg2.... ) :
......................
......................
return value
285
Example12: Function with return statement Funct
Hand
There can be only one return statement in a function. It doesn’t mean that we can
return only one value. It means that the return statement can return only one object
and object in python can contain single (variable) or multiple values (List, tuple).
Hence, we can return multiple values with a single return statement.See example13.
Example 13: Function returning more than one value
Various benefits of using return statement -
1. Valuesreturned by function can be used again in the rest of the program.
2. They can also be passed as argument to other functions providing better
flow of control. See example 14.
3. They can also be used to break out of function in the middle.
Example 14: Function returning more than one value
286
Functions and Files
It is also possible to break out of a function in the middle of statements in function Handling in Python
using return. The statements following the return statement will never be executed.
In example 15, inside a function, there is loop ranging from 1 to 9, but it will only be
executed 4 times, since the function will return when value of i reaches 5, hence
remaining iterations will be skipped.
Example 15: Function returning in between the loop
Check your Progress 2
Ex 1. What are the various ways of passing arguments to a function?
Ex 2. Write a function which takes list of numbers as argument and returns a list of
unique elements from it.
Ex 3. Write a function to display all prime numbers between a range which is passed
as arguments.
11.6 FUNCTION OBJECTS
In python, data is represented as objects. Like Lists, Strings etc, functions are also
treated as objects. Functions in python are first class objects. Since functions are
objects,it provides various features with additional to the existing ones. These are-
1. functions can be assigned to a variable
2. functions can be used as elements of data structures
3. functions can be sent as arguments to another function
4. functions can be nested
1. Functions assigned to variable
As functions are object, they can be assigned to a variable (object). Hence, function
can then be called using variable and set of parenthesis. Assigning function to a
variable creates a reference to the same function or a function with two names. If
one function or variable is deleted, function can still be referenced by another name.
Following is the example of function assigned to a variable. (example 16)
287
Funct
Example 16: Function assigned to variable Hand
In the following console window it can be clearly seen that after deleting a
function, it cannot be accessed with the same name. But it can still be called using
another name as shown in example 17.
Example 17: Deleting reference to a function
2. Functions as element of data structure
Functions can be passed as an element to any data structure. This is very useful at
times when we want to apply different functions to same input. Below is the
example 18 to show that. We are using various built-in functions to demonstrate
that.
Example 18: Function assigned as elements to List
3. Function as argument to another function
Objects can be passed as arguments to a function. Since functions are objects in
python, they can also be passed as arguments to functions. This technique allows
application of multiple operations on a particular set of inputs. Given below is an
example of function calling another function as arguments.
Example 19: Function calling another function as argument
288
Functions and Files
Handling in Python
4. Nested function
Functions created within another function are called nested function. This is one of
the unique properties in python since functions are objects. The inner function which
is created within some outer function has access to all the variables of enclosing
scope. Inner functions can never be directly called outside outer function. Hence, it
provides security feature called Encapsulation. It can only be called by the use of
enclosing function.
Example 20: Nested function
11.7 LAMBDA / ANONYMOUS FUNCTIONS
Python allows to create functions without names called Anonymous functions. They
are not declared with def keyword, instead lambda keyword is used to create these
functions. Hence, these functions are also called lambda functions.Like other
289
functions, these functions can also contain arguments but there can be only one Funct
statement in the body of these functions. Statement is evaluated and the result is Hand
returned. There are situations when a function needs to be created for a short
operation (similar to macros in C language) or usable for a short period of time, in
that case lambda functions are best suited.
Syntax of Anonymous function
Variable = lambda arg : statement
Here,arg is one or more arguments passed to a function and statement consists of
operation performed by a function.
Given below is example 21 in which two lambda functions are created. First
function calculates cube of a given argument and second function gives addition to
two given arguments. Lambda function is then assigned to a variable (function
assigned to variable, discussed in previous section), which can then be used to call
function with arguments and set of parenthesis.
Example 21: Use of Lambda function
Lambda functions are mostly used as argument to other high-order function like map
() and filter () function.
map() function : map () is a built-in function which takes two arguments, first
argument given is function (can be lambda function), second argument is given as a
list. map () function returns a list of elements obtained by applyinggiven function to
each element of alist.
filter() function : filter() is another built-in function which takes two arguments.
First argument is a function and second is list of elements, just as map() function.
Here, given function is applied to each of the elements of list and returns a list of
items for which the function evaluates to True.
Syntax of map and filter function
map ( function , [ list ] )
filter ( function , [ list ] )
290
Example 22: Application of map() function with lambda function Functions and Files
Handling in Python
Example 22: Application of filter() function with lambda function
Check your Progress 3
Ex 1. Write a program to find cube of numbers in a list using lambda function.
Ex 2. Write a program to add two given lists using map function.
Ex 3. Write a program to display vowels from a given list of characters using filter
function.
11.8 FILE OPERATIONS
Main memory is volatile in nature, hence, nothing can be stored permanently. File
handling is a very important functionality which must be provided by any language
to deal with this problem. Inputs can be taken from files instead of users, output can
be displayed and saved permanently in files which can further be accessed later and
appended or updated. All these functionalities come under file handling. Like other
languages, python also provides various built-in functions for file handling
operations.
There are two types of files supported by python- Binary and Text.
Binary files – These are the files that can be represented as 0’s and 1’s. These files
can be processed by applications knowing about the file’s structure. Image files are
example of binary files.
291
Text files – These files are organized as sequence of characters. Here, each line is Funct
separated by a special end of line character. Hand
Any file handling operation can be performed in three steps-
1. Opening a file
2. Operating on file – read , write , append etc
3. Closing a file
1. Opening a file
A file can be opened in a Python using built-in function open(). By default the files
are opened in read text (‘r’) file mode.
Syntax of open() function
file = open ( “file_name.ext ”,’’mode_of_operation’’)
Where,
File_name.ext - is the name of the file to be opened and ext is the extension of file.
Mode_of_operation - is the mode in which file is needed to be opened.
file – is the object returned by the function. This object can be used for further
operations on file
The possible mode of operations in python –
Mode of opening file Functionality
‘r’ Opens a file for reading. It is default mode
‘w’ Opens a file for writing. Overwrites a file if already exists.
Creates new file if does not exist.
‘a’ Opens a file for appending.
‘r+’ Opens a file for both reading and writing.
‘w+’ Same as ‘r+’ but creates new file if does not exist and
overwrites if exists
‘a+’ Opens a file for appending and reading
‘x’ Creates new file. Fails if already exists. Added in python 3.
‘rb’ Opens a file for reading in binary mode.
‘wb’ Same as ‘w’ except data is in binary
‘ab’ Same as ‘a’ except data is in binary
292
Functions and Files
Handling in Python
2. Operating on file
There are various operations -
2.1 Reading from a file
There are many ways to read from a file. Given below are the functions
available for reading from a file.
In the below table assume that file is the object returned from open()
function.
Function Syntax Description
read() file.read () Returns entire file contents as a
string
file.read (n) Returns n characters from
beginning of file as string
readline() file.readline() Returnssingle line of file at a time.
First line in this case.
readlines() file.readlines() Returns a list of all lines
2.2 Writing to a file
Similar to read operations, functions are there in python to write data to
file.
Function Syntax Description
write() file.write(“text”) Writes text or string to a file
2.3 Operations on file
Python allows many other operations to be done in with files. Listed
below are some functions used for file handling.
Function Syntax Description
tell() file.tell() Returns the current cursor
position in file
seek() file.seek(pos) Places the file cursor to
the position pos
os.stat() os.stat(filename) This method is used to get
display status of the file
given as argument.
293
os.path.exists() os.path.exists(‘arg’) Returns true if the file or Funct
directory of name ‘arg’ Hand
exist
os.path.isfile() os.path.isfile(‘arg’) Returns true if the file of
name ‘arg’ exists
os.path.isdir() os.path.isdir(‘arg’) Returns true if the
directory of name ‘arg’
exists
shutil.copy() shutil.copy(src,dst) Copies a file from src to
des file.
os.path.getsize() os.path.getsize(filename) Returns the size of file
3. Closing a file
After completing all the operations on file, it must be closed properly. This step
frees up the resources and allows graceful termination of file operations.
Syntax of closing a file
file.close()
11.8.1 Reading data from a file
There are various ways to read a file by following the steps explained in the above
section. For reading data from the file, it must be existing. Below is given the
program (Example 23) to read a file named “first.txt” in the directory files within the
present directory.
Example 23: Program to display file contents
It may be noted that the file that we want to read or write, may be present in some
other directory or folder. In that case, we can give absolute or relatative path of that
294 file along with its name, shown in the example below. The path separated by \ must
be proceeded by one more \ (backslash) to turn-off special feature of this character. Functions and Files
If the file to be read or written is in the same folder, in which python program is Handling in Python
present, we need not give its path.
11.8.2 Creating a file
For creation of new file, the file can be opened in ‘w’ mode. If the file already
exists, the contents can be overwritten. Also, if we want to be sure that no existing
file gets overwritten, then ‘x’ mode can be used to create new file. If the file already
exists, it will show error message. Given below is the example to open a file and
write contents to it.
Example24 : Program to create file and add contents to it.
After executing this program a file name second.txt gets created in the mentioned
drive with the added contents.
Reading, writing, appending with with statement
The methods of dealing with files used in the above section may not be safe
sometimes. It may happen that an exception occurs as a result of operations on file
and the code exits without closing the file. To make it more convenient python
introduced another statement called with statement which ensures that file is closed
when the code within with is exited. Call to close() function is not required
explicitly. The syntax of how to use with statement for reading, writing and
appending file is given below.
295
Syntax of read,write and append with with statement: Funct
Hand
11.8.3 Copying a file
To copy a file from one to another various methods can be used. One such way of
copying file is by importing a module named ‘shutil’ which contains a built-in
function to create copy of a file.
Example 25 : Program to copy a file from ‘second.txt’ to ‘third.txt’.
11.8.4Deleting a file or folder
A file can be deleted using remove() function from os module. Before using this
function you should move to the directory in which the file to be removed exists.
Similarly, to delete a folder or directory, os.rmdir() function can be used. The
directory to be removed must be empty or otherwise error will be shown. In the
example given below, we want to delete a file name “delete_123.py”. os.listdir()
function is used to display the list of files present in a directory.
Example 26: Deleting a file.
Check your Progress 4
Ex 1. Write a program to display frequency of each word in a file.
296 Ex 2. Write a program to display first n lines from a file, where n is given by user.
Functions and Files
Ex 3. Write a program to display size of a file in bytes. Handling in Python
11.9 SUMMARY
A Function is a block of code that performs a specific task. In this chapter, we
have discussed various aspects of functions such as how to create functions,
their scope, passing arguments to function, andLambda functions. In addition
to these topics, file handling operations are also discussed in detailssuch as
how to interact with file, copying, deleting, etc.
SOLUTIONS TO CHECK YOUR PROGRESS
Check your Progress 1
Ex 1. The various benefits of using functions are –
i) It decomposes a larger problem into more manageable units
ii) It allows reusability of code
iii) It reduces duplication
iv) It makes code easy to understand, use and debug
The process of defining a function is called function definition. It actually
describes the working of a function. It includes – function name, list of
arguments and function body.
Syntax deffunction_name():
….. # body of function
……
Even if the function is defined, it can never be executed till the time it is called.
Hence, for using a function, it must be called using function call statement.
Calling of a function includes function name and list of arguments (no function
body).
Syntax function_name()
Ex 2. Part of a code in which a variable can be accessed is called Scope of a
variable.
Local variables are the variable created within a function’s body or function’s
scope. They cannot be accessed outside the function. Their scope is only
limited to the function in which they are created.
Global variables are the variable created outside any function. Their scope is
global, hence can be used anywhere. Global variables can also be created
within function using keyword global.
deff():
s =1 # s is local variable
print(s)
r ="IGNOU" # r is global variable
f() 297
print(
(r) Fu
Ex 3. Ha
Check you
ur Progress 2
Ex 1.Pythonn provides vaarious mechannisms of passiing arguments to a functionn.
11. Requiredd arguments
2
2. Default arguments
a
3
3. Keywordd arguments
4
4. Arbitraryy arguments
Ex 2.
Ex 3.
Check you
ur Progress 3
Ex 1.
298
8
Ex
x 2. Functions aand Files
Handling in
n Python
Ex
x 3.
Ch
heck your Progress
P 4
Ex
x 1.
Ex
x 2.
Ex
x 3.
299