1. FUNCTIONS AND FILE HANDLING
IN
PYTHON
SANTOSH VERMA
Faculty Development Program: Python Programming
JK Lakshmipat University, Jaipur
(3-7, June 2019)
2. Functions in Python
A function is a set of statements that do some specific
computation and produces output.
The idea is to put some commonly or repeatedly done task
together and make a function, so that instead of writing the
same code again and again for different inputs, we can call
the function. Reusability.
Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are called
user-defined functions.
Minimum error propagation due to reusability.
3. Syntax of the function:
def function_name(list of formal parameters)
Body_of_the_function
return
For example:
def maxVal(x, y):
if x>y:
return x
else:
return y
Function call/invocation syntax:
maxVal(3,4)
4. # A simple Python function to check
# whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
# Driver code
evenOdd(2)
evenOdd(3)
5. Pass by Reference or pass by value?
One important thing to note is, in Python every variable
name is a reference.
When we pass a variable to a function, a new reference to
the object is created.
Parameter passing in Python is same as reference passing in
Java.
6. # Here x is a new reference to same list lst
def myFun(x):
x[0] = 20
# Driver Code (Note that lst is modified
# after function call.
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Output:
[20, 11, 12, 13, 14, 15]
7. When we pass a reference and change the received reference to
something else, the connection between passed and received
parameter is broken.
def myFun(x):
x = [20, 30, 40]
# Driver code
lst = [10, 11, 12, 13, 14, 15]
myFun(lst);
print(lst)
Output:[10, 11, 12, 13, 14, 15]
8. Default Arguments
A default argument is a parameter that assumes a default value if a
value is not provided in the function call for that argument.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Output:
('x: ', 10)
('y: ', 50)
Like C++ default arguments,
any number of arguments in a
function can have a default
value. But once we have a
default argument, all the
arguments to its right must also
have default values.
9. Keyword arguments:
The idea is to allow caller to specify argument name with
values so that caller does not need to remember order of
parameters.
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname =‘Santosh', lastname =‘verma')
student(lastname =‘verma', firstname =‘Santosh')
10. Variable number of arguments:
We can have both normal and keyword variable number of
arguments.
def myFun(*args):
for arg in args:
print (arg)
myFun(“FDP”, “on”, “Python”,
“Programming”)
Output:
FDP
on
Python
Programming
def myFun(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
myFun(first =‘santosh', mid =‘kumar',
last=‘verma’)
Output:
last == verma
mid == kumar
first == santosh
11. Anonymous functions/ Lambda
Abstraction
Anonymous function means that a function is without a name.
As we already know that def keyword is used to define the normal
functions
While, the lambda keyword is used to create anonymous functions. A lambda
function can take any number of arguments, but can only have one
expression.
cube = lambda x: x*x*x
print(cube(7))
Output: 343
Note: It is as similar as inline functions in other programming language.
x = lambda a : a + 10
print(x(5))
Output: 15
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Output: 13
12. Recursion
Recursion is nothing but calling a function directly or in-
directly, and must terminate on a base criteria.
def factI(n):
‘’’Assumes n an int > 0
returns n!’’’
result = 1
while n>1:
result = result * n
n - = 1
return result
def factR(n):
‘’’Assumes n an int > 0
returns n!’’’
if n ==1:
return n
else:
return n*factR(n-1)
13. File Handling
Deals with long term persistence of the data. Like other programming languages,
python to supports file handling.
Python allows users to handle files i.e., to read and write files, along with many
other file handling options, to operate on files.
As compare to other programming language, python file handling is simple
and need not to import anything.
Each line of code includes a sequence of characters and they form text file. Each
line of a file is terminated with a special character, called the EOL or End of Line
characters. It ends the current line and tells the interpreter a new one has begun.
File handling is an important part of any web application.
14. The open Function
file object = open(file_name , access_mode, buffering)
file_name − name of the file that is required to be accessed.
access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append.
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the buffering
value as an integer greater than 1, then buffering action is performed with the indicated
buffer size. If negative, the buffer size is the system default(default behavior). Optional
15. File Modes
Modes Description
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.
r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
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.
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.
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.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
17. OPEN FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)
READ FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print every line one by one in the file
print (file.read())
READ FIRST ‘N’ CHAR from FILE
file = open('C:Userssantosh_homeDesktopfdp.txt', 'r')
# This will print first five characters in the file
print (file.read(5))
18. Creating a file using write() mode
file = open('C:Userssantosh_homeDesktopfdp.txt', ‘w’)
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
Working of append() mode
file = open('C:Userssantosh_homeDesktopfdp.txt’, ‘a’)
file.write("This will add this line")
file.close()
19. Using write along with with() function
# Python code to illustrate with() alongwith write()
with open("C:Userssantosh_homeDesktopfdp.txt", "w") as f:
f.write("Hello World!!!")
split() using file handling
# Python code to illustrate split() function
with open("C:Userssantosh_homeDesktopfdp.txt", “r") as file:
data = file.readlines()
for line in data:
word = line.split()
print word