Python - 1 Year - Unit-4
Python - 1 Year - Unit-4
by C. RAJEEV
C. RAJEEVAssistant Professor,
Assist. Prof.Department of CSE,
Dept. of. CSE,
MRECW
MRECW.
UNIT IV
Python Functions, Advantage of Functions in Python, Creating a Function, Function
Calling, Parameters in Function, Call by Reference in Python, Types of Arguments,
Required Arguments, Keyword Arguments, Default Arguments, Variable-Length
Arguments, Scope of Variables, Python Built-in Functions, Python Lambda Functions,
String with Functions, Strings Indexing and Splitting, String Operators, Python
Formatting Operator, Built-in String Functions, Python File Handling, Opening a File,
Reading the File, Read Lines of the File, Looping through the File, Writing the File,
Creating a New File Using with Statement with Files, File Pointer Position, Modifying
File Pointer Position Renaming the File & Removing the File, Writing Python Output
to the Files File Related Methods, Python Exceptions, Common Exceptions, Problem
without Handling Exceptions, except Statement with no Exception, Declaring Multiple
Exceptions, Finally Block, Raising Exceptions, Custom Exception,
1. Functions in Python
A function is a set of statements that take inputs, 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.
Python also provides built-in functions like print(), etc. but we can also create your own
functions. These functions are called user-defined functions.
2. Creating a function:
We can create function using def keyword
Syntax of Function
def function_name(parameters):
"""docstring""“
statement(s)
Above shown is a function definition that consists of the following components.
A function name to uniquely identify the function. Function naming follows the
Parameters (arguments) through which we pass values to a function. They are optional.
One or more valid python statements that make up the function body. Statements
Example of a function
def greet(name):
""" This function greets to the person
passed in as a parameter """
print("Hello Good morning!")
Docstrings
The first string after the function header is called the docstring and is short for
documentation string. It is briefly used to explain what a function does.
In the previous example, we have a docstring immediately below the function header. We
generally use triple quotes so that docstring can extend up to multiple lines. This string is
available to us as the __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
the person passed in as
a parameter
3.Function calling
How to call a function in python?
Once we have defined a function, we can call it from another function, program or even the
Python prompt. To call a function we simply type the function name with appropriate
parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Ex:
def greet(name):
""" This function greets to the
person passed in as a parameter """
print("Hello, " + name + ". Good morning!")
greet('Paul')
The return statement
The return statement is used to exit a function and go back to the place from where it was
called.
Syntax of return
return [expression_list]
This statement can contain an expression that gets evaluated and the value is
returned.
If there is no expression in the statement or the return statement itself is not present
inside a function, then the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value since greet() directly prints the name and no return statement is
used.
Example of return How Function works in Python?
def absolute_value(num):
"""This function returns the
absolute value of the entered
number""“
if num >= 0:
return num
else:
return –num
print(absolute_value(2))
print(absolute_value(-4))
Output
2
4
4. Parameters in Function:
In Python, you can define a function that takes variable number of arguments.
Ex:
def greet(name, msg):
"""This function greets to
the person with the provided
message"""
print("Hello", name + ', ' + msg)
Here, the function greet() has two parameters. Since we have called this function with two
arguments, it runs smoothly and we do not get any error.
If we call it with a different number of arguments, the interpreter will show an error
message.
Below is a call to this function with one and no arguments along with their respective error
messages.
•On the other hand, the parameter msg has a default value of "Good morning!". So, it is
optional during a call. If a value is provided, it will overwrite the default value.
•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.
•This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:
For example, in the above function greet(), when we called it as greet("Bruce", "How do
you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do
you do?" to msg. Python allows functions to be called using keyword arguments.
When we call functions in this way, the order (position) of the arguments can be
changed. Following calls to the above function are all valid and produce the same result.
Program:
# 2 keyword arguments
greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
greet(msg = "How do you do?",name = "Bruce")
1 positional, 1 keyword argument
greet("Bruce", msg = "How do you do?")
Output:
Hello Bruce, How do you do?
Hello Bruce, How do you do?
Hello Bruce, How do you do?
As we can see, we can mix positional arguments with keyword arguments during a function
call. But we must keep in mind that keyword arguments must follow positional arguments.
Below is a call to this function with one and no arguments along with their respective error
messages.
In the function definition, we use an asterisk (*) before the parameter name to denote
this kind of argument.
Here is an example.
def greet(*names):
"""This function greets all the
person in the names tuple.""“ Output:
# names is a tuple with arguments Hello Monica
for name in names: Hello Luke
print("Hello", name) Hello Steve
greet("Monica", "Luke", "Steve", "John") Hello John
7. Variable-Length Arguments in Python:
Some functions have no arguments, others have multiple. There are times we have
functions with arguments we don't know about beforehand.
We may have a variable number of arguments because we want to offer a flexible API to
other developers or we don't know the input size.
With Python, we can create functions to accept any amount of arguments. These
functions can accept an unknown amount of input, either as consecutive entries or named
arguments.
In the following Python program we are calling a function and passing two integer values
and it is returning back the sum.
# func
def sum(x, y):
return x + y
result = sum(10, 20)
print(result) # 30
So, the above code will print 30 as output.
Now, imagine we want to create a sum function that can take any number of arguments (like 2,
3, 4 ...).The problem with above sum function is that we can only pass two arguments.
Python allows us to create functions that can take multiple arguments. So, lets create multi-
argument functions.
Following is the syntax to create a function that can take variable length arguments.
def func(*args):
# body of the function
Where, func is the name of the function and *args holds variable length arguments.
Passing multiple arguments:
In the following Python program we are recreating the sum function but this time we are
modifying it to take multiple arguments and print them.
Program: Output:
So, we can see that the args variable is of type tuple and we are also able to print all the values
that were passed to the function as a tuple.
Accessing multiple arguments:
Since the multiple arguments passed to the function are tuple so we can access them using
for loop. In the following Python program we are printing out the individual argument.
Program:
def sum(*args):
The above code will given us the following output.
for arg in args: sum(10, 20)
print(arg) 10
20
print('sum(10, 20)') sum(10, 20, 30)
sum(10, 20) 10
20
print('sum(10, 20, 30)') 30
sum(10, 20, 30) sum(10, 20, 30, 40)
10
print('sum(10, 20, 30, 40)') 20
sum(10, 20, 30, 40) 30
40
So, now that we are able to access the individual argument passed to the function let's go ahead
and modify the sum function that we are working on to return us the sum of the arguments.
Multiple arguments sum function:
Program:
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
Output:
30
60
5. Call by reference in Python :
Python uses a mechanism, which is known as "Call-by- reference ", sometimes also called
"Call by Object Reference" or "Call by Sharing“ or call by object
In Python, call by reference means passing the actual value as an argument in the function.
In Python language, all parameters (arguments) are passed by reference. It means if you
change what a parameter refers to within a function, the change also reflects back in the calling
function.
In Python, data objects are stored in memory, and a variable is just a label for its easy access.
For example ,
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4])
print("Values inside the function: ", mylist)
return
# Now you can call change me function
mylist = [10,20,30]
changeme(mylist)
print("Values outside the function: ", mylist)
•Here, we are maintaining reference of the passed object and appending values in the same
object.
•So, this would produce the following result −
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
If actual and formal arguments involved in a function call, they have same id value.
Example:
def myfunction(arg): #formal argument
print ("value received {} has id {}".format(arg, id(arg)))
x=100
print ("value sent {} has id {}".format(x, id(x)))
myfunction(x) # actual argument
Output
value sent 100 has id 140717823786336
value received 100 has id 140717823786336
Any object is passed to a function by reference, a function's changes are reflected only in the
case of mutable objects and not in immutable objects
If the actual argument variable represents an immutable object such as int, float, tuple, or a
string, any modification inside function will result in creating a different and not affect the
original variable.
Example:
def myfunction(arg):
print ("value received {} has id {}".format(arg, id(arg)))
arg=arg+10
print ("value changed {} has id {}".format(arg, id(arg)))
x=100
print ("value sent {} has id {}".format(x, id(x)))
myfunction(x)
print ("value after function call {} has id {}".format(x, id(x)))
Output
value sent 100 has id 140717823786336
value received 100 has id 140717823786336
value changed 110 has id 140717823786656
value after function call 100 has id 140717823786336
if a mutable object such as a list is passed to function, modification inside a function will be
reflected after function call as in the following function.
Example
def myfunction(arg):
print ("list received {} has id {}".format(arg, id(arg)))
arg.append(40)
print ("list changed {} has id {}".format(arg, id(arg)))
x=[10,20,30]
print ("list sent {} has id {}".format(x, id(x)))
myfunction(x)
print ("list after function call {} has id {}".format(x, id(x)))
Output
list sent [10, 20, 30] has id 1864061271048
list received [10, 20, 30] has id 1864061271048
list changed [10, 20, 30, 40] has id 1864061271048
list after function call [10, 20, 30, 40] has id 1864061271048
Finally , we can conclude that even though any object is passed to a function by reference, a
function's changes are reflected only in the case of mutable objects and not in immutable
objects
8. Scope of Variables:
A variable is only available from inside the region it is created. This is called scope.
There are 3 basic scopes of variables in Python
1. Global Variables
2. Local Variables
3. Nonlocal Variables
1. Global Variables:
In Python, a variable declared outside of the function or in global scope is known as a global
variable. This means that a global variable can be accessed inside or outside of the function.
Example : Create a Global Variable
x = "global”
def foo():
print("x inside:", x) //inside
foo()
print("x outside:", x) //outside
In the above code, we created x as a global variable and defined a foo() to print the global
What if you want to change the value of x inside a function?
x = "global"
def foo():
x=x*2
print(x)
foo()
Output:
UnboundLocalError: local variable 'x' referenced before assignment
The output shows an error because Python treats x as a local variable and x is also not
defined inside foo().
2. Local Variables:
A variable declared inside the function's body or in the local scope is known as a local
variable.
Output:
NameError: name 'y' is not defined
The output shows an error because we are trying to access a local variable y in a global
scope whereas the local variable only works inside foo() or local scope.
Global and local variables
Let's take a look at the earlier problem where x was a global variable and we wanted to
modify x inside foo().
Here, we will show how to use global variables and local variables in the same code.
Example : Using Global and Local variables in the same code
x = "global "
def foo():
global x Output:
x=x*2 local
print(x)
In the above code, we declare x as a global and y as a local variable in the
print(y)
foo(). Then, we use multiplication operator * to modify the global variable x
foo()
and we print both x and y. After calling the foo(), the value of x becomes
#print(x)
global global because we used the x * 2 to print two times global. After that,
we print the value of local variable y i.e local.
Example : Global variable and Local variable with same name
x=5
Output:
def foo():
local x: 10
x = 10
global x: 5
print("local x:", x)
foo()
print("global x:", x)
In the above code, we used the same name x for both global variable and local variable. We
get a different result when we print the same variable because the variable is declared in both
scopes, i.e. the local scope inside foo() and global scope outside foo().
When we print the variable inside foo() it outputs local x: 10. This is called the local scope of
the variable.
Similarly, when we print the variable outside the foo(), it outputs global x: 5. This is called the
global scope of the variable.
3. Nonlocal Variables:
Nonlocal variables are used in nested functions whose local scope is not defined. This
means that the variable can be neither in the local nor the global scope.
We use nonlocal keywords to create nonlocal variables.
Example : Create a nonlocal variable
def outer():
x = "local"
Output:
def inner():
inner: nonlocal
nonlocal x
outer: nonlocal
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
outer()
In the above code, there is a nested inner() function. We use nonlocal keywords to create a
nonlocal variable. The inner() function is defined in the scope of another function outer().
9. Python Anonymous/Lambda Function:
In Python, an 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.
Lambda functions can have any number of arguments but only one expression.
The expression is evaluated and returned. Lambda functions can be used wherever function
objects are required.
Here is an example of lambda function that doubles the input value.
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
In the above program, lambda x: x * 2 is the lambda function. Here x is the argument and x *
2 is the expression that gets evaluated and returned.
This function has no name. It returns a function object which is assigned to the identifier
double.
double = lambda x: x * 2
In indexing, for accessing the individual character we can use slice operator [ ], inside that
specify index number.
str[0]=‘H’
str[3]=‘L’
str[1]=‘E’
str[4]=‘O’
str[2]=‘L’
if we try to access a character out of index range then interpreter will raise an IndexError.
>>> str[5]
Traceback (most recent call last): The index must be an integer if we try to
File "<pyshell#1>", line 1, in <module> access the data with non-integer indexes
str[5]
IndexError: string index out of range values then interpreter raises an TypeError.
Slicing means taking elements from one given index to another given index.
In slicing, by using the slice operator [ ] we can access the range of characters of the string.
Inside square bracket[ ] we can use the : operator to access the substring.(positive indexing).
We pass slice instead of index like this: [start:end].
If we don't pass start its considered 0
If we don't pass end its considered length of string.
str=“HELLO”
H E L L O
Forward indexing 0 1 2 3 4
Python allows negative indexing for its sequence. The index of -1 refers to the last
item, -2 refers to last 2nd item. This is called backward indexing
str=‘hello’
h e l l o
-5 -4 -3 -2 -1
>>> str[-1]
Backward indexing
'o'
>>> str[-3]
'l‘
>>> str[:-3]
'he'
>>> str[-3:]
'llo‘
>>> str[-3:-2]
'l‘
>>> str[-2:-2] # return empty strings.
‘'
>>> str[2:2] # return empty strings.
‘'
String splitting:
split()
split() method breaks up a string at the specified separator and returns a list of strings.
syntax of split() is:
str.split(separator)
separator (optional)- It is a delimiter. The string splits at the specified separator. If the separator is not
specified, any whitespace (space) string is a separator.
Ex:
text='hello python programming'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread' Output:
# splits at ','
[‘hello',‘python', ‘programming']
print(grocery.split(', '))
['Milk', 'Chicken', 'Bread']
grocery1 = 'Milk, Chicken: Bread:coffee'
['Milk, Chicken, Bread, coffee']
# Splitting at ':'
print(grocery1.split(':'))
11.String Operators:
In python, String operators represent the different types of operations that can be employed on
the program’s string type of variables. Python allows several string operators that can be applied
on the python string are as below:
1. Assignment operator: “=.”
2. Concatenate operator: “+”
3. String repetition operator: “*”
4. String slicing operator: “[]”
5. String comparison operator: “==” & “!=”
6. Membership operator: “in” & “not in”
7. Escape sequence operator: “\”
8. String formatting operator: “%”
1. Assignment Operator “=”
Python string can be assigned to any variable with an assignment operator “= “.
Python string can be defined with either single quotes [‘ ’], double quotes[“ ”] or triple
quotes[‘’’ ‘’’]. var_name = “string” assigns “string” to variable var_name.
Code:
string1 = "hello"
string2 = 'hello'
string3 = '''hello'''
print(string1)
print(string2)
print(string3)
Output:
2. Concatenate Operator “+”
Two strings can be concatenated or join using “+” operator in python, as explained in the
below example code:
Code:
string1 = "hello"
string2 = "world "
string_combined = string1+string2
print(string_combined)
Output:
3.String Repetition Operator “*”
The same string can be repeated in python by n times using string*n as explained in the
below example.
Code:
string1 = "helloworld "
print(string1*2)
print(string1*3)
print(string1*4)
print(string1*5)
Output:
4. String slicing operator “[]”
Characters from a specific index of the string can be accessed with the string[index]
operator. The index is interpreted as a positive index starting from 0 from the left side
and a negative index starting from -1 from the right side.
String H E L L O W O R L D
Positive 0 1 2 3 4 5 6 7 8 9
index
Negativ -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
e index
•string[a]: Returns a character from a positive index a of the string from the left side as
displayed in the index graph above.
•string[-a]: Returns a character from a negative index a of the string from the right side as
displayed in the index graph above.
•string[a:b]: Returns characters from positive index a to positive index b of the as displayed in
index graph above.
•string[a:-b]: Returns characters from positive index a to the negative index b of the string as
displayed in the index graph above.
•string[a:]: Returns characters from positive index a to the end of the string.
•string[:b] Returns characters from the start of the string to the positive index b.
•string[-a:]: Returns characters from negative index a to the end of the string.
•string[:-b]: Returns characters from the start of the string to the negative index b.
•string[::-1]: Returns a string with reverse order.
Code:
string1 = "helloworld"
print(string1[1])
print(string1[-3])
print(string1[1:5])
print(string1[1:-3])
print(string1[2:])
print(string1[:5])
print(string1[:-2])
print(string1[-2:])
print(string1[::-1])
Output:
5. String Comparison Operator “==” & “!=”
The string comparison operator in python is used to compare two strings.
•“==” operator returns Boolean True if two strings are the same and return Boolean False if two strings
are not the same.
•“!=” operator returns Boolean True if two strings are not the same and return Boolean False if two
strings are the same.
These operators are mainly used along with if condition to compare two strings where the decision is to
be taken based on string comparison.
Code:
string1 = "hello"
string2 = "hello, world"
string3 = "hello, world"
string4 = "world"
print(string1==string4) Output:
print(string2==string3)
print(string1!=string4)
print(string2!=string3)
6. Membership Operator “in” & “not in”:
Membership operator is used to searching whether the specific character is part/member of a
given input python string.
“a” in the string: Returns boolean True if “a” is in the string and returns False if “a” is not in
the string.
“a” not in the string: Returns boolean True if “a” is not in the string and returns False if “a”
is in the string.
A membership operator is also useful to find whether a specific substring is part of a given
string.
Code:
string1 = "helloworld"
print("w" in string1)
print("W" in string1) Output:
print("t" in string1)
print("t" not in string1)
print("hello" in string1)
7. Escape Sequence Operator “\.”
To insert a non-allowed character in the given input string, an escape character is used.
An escape character is a “\” or “backslash” operator followed by a non-allowed
character.
An example of a non-allowed character in python string is inserting double quotes in the
string surrounded by double-quotes.
Output:
2. Example of non-allowed double quotes with escape sequence operator:
Code:
string = "Hello world I am from \"India\""
print(string)
Output:
8. String Formatting Operator “%.”
String formatting operator is used to format a string as per requirement. To insert another
type of variable along with string, the “%” operator is used along with python string.
“%” is prefixed to another character indicating the type of value we want to insert along
with the python string.
Please refer to the below table for some of the commonly used different string formatting
specifiers:
Code:
name = "india"
age = 19
marks = 20.56
string1 = 'Hey %s' % (name)
print(string1)
string2 = 'my age is %d' % (age)
print(string2)
string3= 'Hey %s, my age is %d' % (name, age)
print(string3)
string3= 'Hey %s, my subject mark is %f' % (name, marks)
print(string3)
Output:
12. What is a file?
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. 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.
If you are working in a large software application where they process a large number of data,
then we cannot expect those data to be stored in a variable as the variables are volatile in
nature.
As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk
How Python Handle Files?
If you are working in a large software application where they process a large number of
data, then we cannot expect those data to be stored in a variable as the variables are
volatile in nature.
As files are non-volatile in nature, the data will be stored permanently in a secondary
device like Hard Disk.
r: Opens the file in read-only mode. Starts reading from the beginning of the file and is
the default mode for the open() function.
w: Opens in write-only mode. The pointer is placed at the beginning of the file and this
will overwrite any existing file with the same name. It will create a new file if one with the
same name doesn't exist.
a: Opens a file for appending new information to it. The pointer is placed at the end of
the file. A new file is created if one with the same name doesn't exist.
r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.
ab+: Opens a file for both appending and reading in binary mode
Ex:
>>> f=open(“fdp.txt","w“)
>>> f
<_io.TextIOWrapper name='demo.txt' mode='w' encoding='cp1252'>
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()
Then open fdp.txt file in your path.
We need to be careful with the w mode, as it will overwrite into the file if it already
exists. Due to this, all the previous data are erased.
How to append new data in to existing file:
>>> f=open(“fdp.txt","a")
>>> f.write(" \n This is file concepts in python\n")
35
>>> f.write(" \nThis is append method")
23
>>> f.close()
Note: open fdp txt file in your path and see the text
3.Reading a Text File in Python:
If you need to extract a string that contains all characters in the file.
Syntax:
fileobject.read()
Ex;
>>> f=open(“fdp.txt","r")
>>>a= f.read()
>>>print(a) // to print all characters in the file
Ex:
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose , if we want to get a character ,then use slicing concept
>>> f=open("fdp.py","r")
>>> a=f.read()
>>> print(a[2])
i
>>> print(a[0:])
this is first line
This is file concepts in python
This is append method
this is writelines function
previous function is write function
For suppose, I want to read a file is to call a certain number of characters.
>>> f=open(“fdp.txt","r")
>>> a=f.read(22)
>>>print(a)
Ex:
this is first line
Thi
We can also specify bytes in readline(),which returns specified bytes from first line.
Return only the five first bytes from the first line:
>>>f = open(“fdp.txt", "r")
>>>print(f.readline(5))
this
readlines():
If you want to read a data line by line from file, then you use the readlines() function
Ex: #Displaying first line from file #Displaying second line from file
>>> f=open(“fdp.txt","r")
>>> f=open(“fdp.txt","r") >>> a=f.readlines()
>>> a=f.readlines() >>>print(a[1])
>>> print(a[0]) This is file concepts in python
this is first line
>>> f=open(“fdp.txt","r")
>>> a=f.readlines()
>>>print(a[-1])
previous function is write function
4. Python Close File
In order to close a file, we must first open the file. In python, we have an in-built method
called close() to close the file which is opened.
Whenever you open a file, it is important to close it, especially, with write method.
Because if we don’t call the close function after the write method then whatever data we
have written to a file will not be saved into the file.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
my_file.close()
5. Python Rename():
Python provides us with an “os” module which has some in-built methods that
would help us in performing the file operations such as renaming and deleting the
file.
In order to use this module, first of all, we need to import the “os” module in our
program and then call the related methods.
rename() method:
This rename() method accepts two arguments i.e. the current file name and the new
file name.
Syntax:
os.rename(current_file_name, new_file_name)
Ex:
>>> import os
>>> os.rename("fdp1.txt","fdp2.txt")
6. Python remove() method:
We use the remove() method to delete the file by supplying the file name or the file
location that you want to delete.
Syntax:
os.remove(file_name)
Example :
import os
os.remove("fdp2.txt")
14. Looping through the File:
We can iterate through the file handle, no need to call readlines().on large files, you
don't have to read all the lines (that's what readlines() does) at once.
In a with-statement, use open(file, mode) with mode as "r" to open file for reading.
Inside the with-statement, use a for-loop to iterate through the lines. Then, call str.strip() to
strip the end-line break from each line.
SAMPLE.TXT
This is
an existing file.
-----------------------------------
with open("sample.txt", "r") as a_file:
for line in a_file: OUTPUT
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
>>> print(f.readline()) #output: ‘This is file concepts in python\n‘
17. File Built-in Methods
1. close()
2. fileno()
3. read()
4. readable()
5. readline( )
6. readlines()
7. seek()
8. seekable()
9. tell()
10.truncate()
11.writable()
12.write()
13.writelines()
14.detach
1. close() in Python
With close(), we close a file to free up the resources held by it.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("this is first line\n")
18
>>> f.close()
2. fileno() in Python
t is used to get the file number i.e. the file descriptor as an integer of the stream.
It may return an error if an operating system does not use a file descriptor of the file is closed.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.fileno()
4
3. read() in Python
The read() method returns the specified number of bytes from the file.
Syntax:
file.read(size)
Where size is the number of bytes to be read from the file.
Ex:
>>> f=open("abc.txt","r")
>>> a=f.read()
>>> print(a)
4. readable() in Python
This returns True if the object is readable
Ex:
>>> f=open("abc.txt",”r")
>>> f.readable()
True
>>> f=open("abc.txt","w")
>>> f.readable()
False
>>> f=open("abc.txt","a")
>>> f.readable()
False
5. readline( ) in Python:
The readline() method returns first line from the file.
Syntax
file.readline(size)
Ex:
>>> f=open("abc.txt","r")
>>> a=f.readline()
>>>print(a)
welcome to python programming
You can also specified how many bytes from the line to return, by using the size
parameter.
Return only the five first bytes from the first line:
>>>f = open("demofile.txt", "r")
>>>print(f.readline(5))
6. readlines() in Python:
readlines() method returns a list containing each line in the file as a list item.
Ex:
>>> f=open("demo.txt","r")
>>> a=f.readlines()
>>> print(a)
['hi...hello...python‘,’welcome to python world']
7. seek() in python:
The seek() method sets the current file position in a file stream.
Syntax
file.seek(offset)
Where offset is a number representing the position to set the current file stream position.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
8. seekable() in Python
This returns whether file allows us to change the file position
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seekable()
True
9. tell() in Python
tell() tells us the current position of the cursor.
Ex:
>>> f=open(“fdp.txt","r")
>>> f.seek(20)
20
>>> print(f.readline())
This is file concepts in python\n'
>>> print(f.tell())
10. truncate():
This method truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.
The size defaults to the current position
This method would not work in case file is opened in read-only mode.
Syntax:
fileObject.truncate( [ size ])
Example:
>>> f=open(“fdp.txt","w")
>>> #fdp.txt size is 139bytes
>>> f.truncate()
0
>>> #fdp.txt size is 0 bytes
11. writable() in Python
This returns True if the stream can be written to.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.writable()
True
>>> f=open(“fdp.txt","r")
>>> f.writable()
False
12. write(s) in Python
This method takes string ‘s’, and writes it to the file. Then, it returns the number of
characters written.
Ex:
>>> f=open(“fdp.txt","w")
>>> f.write("truncate function")
17
13. writelines():
The method writelines() writes a sequence of strings to the file.
The sequence can be any iterable object producing strings, typically a list of strings.
There is no return value.
Syntax:
fileObject.writelines( sequence)
# Where sequence − This is the Sequence of the strings.
Ex:
>>> f=open(“fdp.txt","w")
>>> a=f.writelines(["this is writelines function\n","previous function is write function"])
>>>f.close()
Note: open new.txt file in your path and see the text
14. detach( ):
This detaches the underlying binary buffer from TextIOBase and returns raw stream
from buffer.
syntax:
f.detach()
Ex:
>>> f=open("ab.txt","r")
>>> f.detach()
<_io.BufferedReader name='ab.txt'>
>>> f.read()
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
f.read()
ValueError: underlying buffer has been detached
18. Python file Built-in attributes:
Ex:
>>> f=open("new.txt","w")
>>> print("Name of the File:",f.name)
Name of the File: new.txt
>>> print("Mode of the File:",f.mode)
Mode of the File: w
>>> print("closed?:",f.closed)
closed?: False
>>> f.close()
>>> print("closed?:",f.closed)
closed?: True
>>> print("Encoding of the File:",f.encoding)
Encoding of the File: cp1252
Encoding in Files
File encoding represents converting characters into a specific format which only a
machine can understand.
Different machines have different encoding format as shown below.
Microsoft Windows OS uses ‘cp1252’ encoding format by default.
Linux or Unix OS uses ‘utf-8’ encoding format by default.
Apple’s MAC OS uses ‘utf-8’ or ‘utf-16’ encoding format by default.
19. Error and Exceptions
Errors are the problems in a program due to which the program will stop the execution.
On the other hand, exceptions are raised when the some internal events occur which
changes the normal flow of the program.
In the context of software, errors are either syntactical or logical in nature.
1. Syntax errors indicate errors with the construct of the software and cannot be executed by
the interpreter or compiled correctly.
These errors must be repaired before execution can occur.
Once programs are semantically correct, the only errors that remain are logical.
2. Logical errors/ Run time errors can either be caused by lack of or invalid input, or by
the inability of the logic to generate, calculate, or otherwise produce the desired results
based on the input.
Run time errors are also called Exceptions
These errors are sometimes known as domain and range failures.
20. Common Exceptions:
An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
Whenever an exception occurs, the program halts the execution, and thus the further code
is not executed. Therefore, an exception is the error which python script is unable to tackle
with.
Python provides us with the way to handle the Exception so that the other part of the
code can be executed without any disruption. However, if we do not handle the exception,
the interpreter doesn't execute all the code that exists after the that..
SyntaxError exceptions are the only ones that do not occur at run-time.
They indicate an improperly constructed piece of Python code which cannot execute
until corrected.
These errors are generated at compile-time, when the interpreter loads and attempts
to convert your script to Python bytecode
5. IndexError: request for an out-of-range index for sequence
>>> aList = []
>>> aList[0]
Traceback (innermost last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
IndexError is raised when attempting to access an index that is outside the valid range of a
sequence.
6. KeyError: request for a non-existent dictionary key
>>> aDict = {'host': 'earth', 'port': 80}
>>> print aDict['server']
Traceback (innermost last):
File "<stdin>", line 1, in ?
KeyError: server
Mapping types such as dictionaries depend on keys to access data values. Such values are
not retrieved if an incorrect/nonexistent key is requested.
7.IOError: input/output error
>>> f = open("blah")
Traceback (innermost last):
File "<stdin>", line 1, in ?
IOError: [Errno 2] No such file or directory: 'blah‘
If the python program contains suspicious code that may throw the exception, we must place
that code in the try block.
The try block must be followed with the except statement which contains a block of code that
will be executed if there is some exception in the try block.
When an error occurs with in try block .python looks for matching except block to handle it ,if
Ex:
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/b
print("the result is",c)
except:
print("error occured“)
C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value0
error occured
C:\Users\ajee\Desktop\py>exception.py
enter a value4
enter b value2
The result is 2
2.Type error:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value5
>>> c=a/'b'
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
c=a/'b'
TypeError: unsupported operand type(s) for /: 'int' and 'str‘
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/'b'
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>typeerror.py
enter a value3
enter b value 4
error occured
3. NameError:
Ex:
>>> a=eval(input("enter a value"))
enter a value4
>>> b=eval(input("enter b value"))
enter b value6
>>> c=a/d
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
c=a/d
NameError: name 'd' is not defined
a=int(input("enter a value"))
b=int(input("enter b value"))
try:
c=a/d
print("the result is",c)
except:
print("error occured")
C:\Users\ajee\Desktop\py>nameerror.py
enter a value2
enter b value3
error occured
22. Declaring multiple exceptions (or )except Statement with
Multiple Exceptions
The python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.
Ex:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:0
please enter non-zero for denimoniator
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/'b';
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:2
please use proper types only
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/d;
print("a/b = %d"%c)
except ZeroDivisionError:
print("please enter non-zero for denimoniator")
except NameError:
print("please use defined names only")
except TypeError:
print("please use proper types only")
C:\Users\ajee\Desktop\py>except.py
Enter a:4
Enter b:6
please use defined names only
some of the exception errors
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file.')
except ImportError:
print "NO module found"
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
except:
print('An error occurred.')
We can also declare the multiple exceptions with the except clause in one statement.
Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.
Syntax
try:
#block of code
except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
#block of code
Ex
try:
#block of code
except (Zerodivisionerror, valueerror,import error>...<EOFerror>)
#block of code
24. Handling All Exceptions:
Python exception hierarchy or standard exceptions:
24. Handling All Exceptions:
If you really want to handle all errors, you can still do that too, but use BaseException
try:
except BaseException, e:
- BaseException
# handle all errors
|- KeyboardInterrupt
or
|- SystemExit
try:
|- Exception
except Exception, e:
|- (all other current built-in exceptions)
# handle real errors
25. else block:
We can also use the else statement with the try-except statement in which, we can place the
code which will be executed in the scenario if no exception occurs in the try block.
Ex:
a = int(input("Enter a:"))
C:\Users\ajee\Desktop\py>else.py
b = int(input("Enter b:"))
Enter a:4
try:
Enter b:0
c = a/b
can't divide by zero
print("a/b = %d"%c)
except:
C:\Users\ajee\Desktop\py>else.py
print("can't divide by zero")
Enter a:4
else:
Enter b:2
print("Hi I am else block")
a/b = 2
Hi I am else block
26. Finally block
a = int(input("Enter a:"))
b = int(input("Enter b:"))
try:
c = a/b
print("a/b = %d"%c)
except :
print("please enter non-zero for denimoniator")
else:
print("Hi I am else block")
finally:
print("Thank you")
C:\Users\ajee\Desktop\py>except.py
C:\Users\ajee\Desktop\py>except.py Enter a:4
Enter a:4 Enter b:0
Enter b:3 please enter non-zero for denimoniator
a/b = 1 Thank you
Hi I am else block
Thank you
27. Assert statement in python:
Syntax:
assert <condition>,<error message>
Here error message is optional
Ex:
x = "hello”
assert x == "hello“
print(x)
#if condition returns False, AssertionError is raised
assert x == "goodbye", "x should be 'hello‘“
o/p:
hello
Traceback (most recent call last):
File "main.py", line 17, in <module>
assert x == "goodbye", "x should be 'hello‘”
28. User defined exception or custom exception :
User can also define exceptions to indicate something is going wrong in your
program ,those are called customized exception or programmatic exception.
The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user.
x = "hello”
if not type(x) is int:
raise TypeError("Only integers are allowed")