0% found this document useful (0 votes)
9 views20 pages

Functions 05.06.2019

The document is a faculty development program on Python programming, focusing on functions and file handling. It covers concepts such as user-defined functions, parameter passing, default arguments, keyword arguments, recursion, and various file handling operations in Python. Additionally, it explains the use of the open function, file modes, and provides examples of reading, writing, and appending to files.

Uploaded by

Bajrang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views20 pages

Functions 05.06.2019

The document is a faculty development program on Python programming, focusing on functions and file handling. It covers concepts such as user-defined functions, parameter passing, default arguments, keyword arguments, recursion, and various file handling operations in Python. Additionally, it explains the use of the open function, file modes, and provides examples of reading, writing, and appending to files.

Uploaded by

Bajrang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Faculty Development Program: Python Programming

JK Lakshmipat University, Jaipur


(3-7, June 2019)

FUNCTIONS AND FILE HANDLING


IN
PYTHON

SANTOSH VERMA
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.


 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)
# 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)
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.
# 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]


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]

When we pass a reference and change the received


reference to something else, the connection between
passed and received parameter is broken.
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): Like C++ default


print("x: ", x) arguments, any number of
print("y: ", y) arguments in a function
can have a default value.
# Driver code (We call myFun() with only But once we have a default
# argument) argument, all the
myFun(10)
arguments to its right must
also have default values.
Output:
('x: ', 10)
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')
Variable number of arguments:
 We can have both normal and keyword variable
number of arguments.
def myFun(*args): def myFun(**kwargs):
for arg in args: for key, value in kwargs.items():
print (arg) print ("%s == %s" %(key, value))

myFun(“FDP”, “on”, “Python”, # Driver code


“Programming”) myFun(first =‘santosh', mid =‘kumar',
last=‘verma’)

Output: Output:
FDP last == verma
on mid == kumar
Python first == santosh
Programming
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.
x = lambda a : a + 10
print(x(5))
cube = lambda x: x*x*x x = lambda a, b, c : a + b
print(cube(7)) Output: 15 + c
print(x(5, 6, 2))
Output: 343
Output: 13
Note: It is as similar as inline functions in other programming language.
Recursion
 Recursion is nothing but calling a function directly or
in-directly, and must terminate on a base criteria.

def factI(n): def factR(n):


‘’’Assumes n an int > 0 ‘’’Assumes n an int > 0
returns n!’’’ returns n!’’’
result = 1 if n ==1:
while n>1: return n
result = result * n else:
n - = 1 return n*factR(n-1)
return result
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.


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
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.
The file Object Attributes
OPEN FILE
file = open('C:\\Users\\santosh_home\\Desktop\\fdp.txt', 'r')
# This will print every line one by one in the file
for each in file:
print (each)

READ FILE
file = open('C:\\Users\\santosh_home\\Desktop\\fdp.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:\\Users\\santosh_home\\Desktop\\fdp.txt', 'r')
# This will print first five characters in the file
print (file.read(5))
Creating a file using write() mode
file = open('C:\\Users\\santosh_home\\Desktop\\fdp.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:\\Users\\santosh_home\\Desktop\\fdp.txt’, ‘a’)
file.write("This will add this line")
file.close()
Using write along with with() function
# Python code to illustrate with() alongwith write()
with open("C:\\Users\\santosh_home\\Desktop\\fdp.txt", "w") as f:
f.write("Hello World!!!")

split() using file handling


# Python code to illustrate split() function
with open("C:\\Users\\santosh_home\\Desktop\\fdp.txt", “r") as file:
data = file.readlines()
for line in data:
word = line.split()
print word
Thank You!

You might also like