0% found this document useful (0 votes)
23 views37 pages

Unit-III Python Notes

Uploaded by

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

Unit-III Python Notes

Uploaded by

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

www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.

in

Unit – III
Chapter-I ( Lists)
1.1 INTRODUCTION TO LIST
 The data type list is an ordered sequence which is mutable and made up of one or more
elements
 Unlike a string which consists of only characters, a list can have elements of different
data types, such as integer, float, string, tuple or even another list.
 A list is very useful to group together elements of mixed data types.
 Elements of a list are enclosed in square brackets and are separated by comma. Like
string indices, list indices also start from 0.

Example :

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.1.1 Accessing Elements in a List


The elements of a list are accessed in the same way as characters are accessed in a
string.

1.1.2 Lists are Mutable


In Python, lists are mutable. It means that the contents of the list can be changed after
it has been created.

Syntax :-
list_name[index] = new_value

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.2 Lists Operations


The data type list allows manipulation of its contents through various operations as
shown below.
1. Concatenation
2. Repetition
3. Membership
4. Slicing
1.2.1 Concatenation:
Python allows us to join two or more lists using concatenation operator depicted by
the symbol +.

If we try to concatenate a list with elements of some other data type, TypeError occurs.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.2.2 Repetition :
Python allows us to replicate a list using repetition operator depicted by symbol *

1.2.3 Membership :
Like strings, the membership operators in checks if the element is present in the list and
returns True, else returns False

The not in operator returns True if the element is not present in the list, else it returns
False.

1.2.4 Slicing :
 List slicing refers to accessing a specific portion or a subset of the list for some operation
while the original list remains unaffected.
 The slicing operator in python can take 3 parameters.
Syntax of list slicing:
list_name[start:stop:steps]
 The start represents the index from where the list slicing is supposed to begin. Its
default value is 0, i.e. it begins from index 0.
 The stop represents the last index up to which the list slicing will go on. Its default
value is (length(list)-1) or the index of last element in the list.
 The step Integer value which determines the increment between each index for
slicing.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.3 Traversing a List


We can access each element of the list or traverse a list using a for loop or a while loop.
1.3.1 List Traversing using for Loop

list1 =['Red','Green','Blue','Black']
for item in list1:
print(item)
Output :
Red
Green
Blue
Black
1.3.2 List Traversing using while Loop
list1 =['Red','Green','Blue','Black'] Output :
i = 0 Red
while i < len(list1): Green
print(list1[i])
Blue
i += 1
Black

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.4 List Methods and Built-In Functions


The data type list has several built-in methods that are useful in programming. Some of
them are listed in table.

Built-in functions for list manipulations

Method Description Example


>>> list1 = [10,20,30,40,50]
Returns the length
>>> len(list1)
len() of the list passed
5
as the argument
Creates an empty
list if no argument >>> list1 = list()
is passed >>> list1
[ ]
list() >>> str1 = 'aeiou'
>>> list1 = list(str1)
Creates a list if a >>> list1
sequence is passed ['a', 'e', 'i', 'o', 'u']
as an argument
>>> list1 = [10,20,30,40]
Appends a single >>> list1.append(50)
element passed as an
>>> list1
argument at the end[10, 20, 30, 40, 50]
append() of the list >>> list1 = [10,20,30,40]
>>> list1.append([50,60])
The single element >>> list1
can also be a list [10, 20, 30, 40, [50, 60]]

Appends each >>> list1 = [10,20,30]


>>> list2 = [40,50]
element of the list
>>> list1.extend(list2)
extend() passed as argument
>>> list1
to the end of the [10, 20, 30, 40, 50]
given list
>>> list1 = [10,20,30,40,50]
>>> list1.insert(2,25)
>>> list1
Inserts an element
[10, 20, 25, 30, 40, 50]
insert() at a particular >>> list1.insert(0,5)
index in the list >>> list1
[5, 10, 20, 25, 30, 40, 50]

>>> list1 = [10,20,10,40,10]


Returns the number >>> list1.count(10)
of times a given 3
count()
element appears in >>> list1.count(90)
the list 0

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Returns index of the first >>> list1 = [10,20,30,20,40]


occurrence of the
>>> list1.index(20)
element in the list.
1
index() >>> list1.index(90)
If the element is not
present, ValueError ValueError: 90 is not in
is generated list
Removes the given
>>> list1 = [10,20,30,40,30]
element from the list.
>>> list1.remove(30)
If the element is present
multiple times, only the >>> list1
first occurrence is [10, 20, 40, 30]
remove()
removed.
>>> list1.remove(90)
If the element is not
ValueError:
present, then
list.remove(x):x not in
ValueError is list
generated
>>>list1 =[10,20,30,40,50,60]
Returns the element
>>> list1.pop(3)
whose index is passed as 40
parameter to this function
and also removes it from >>> list1
the list. [10, 20, 30, 50, 60]
pop()
If no parameter is given, >>>list1=[10,20,30,40,50,60]
then it returns and
>>> list1.pop()
removes the last element
60
of the list >>> list1
[10, 20, 30, 40, 50]
>>>list1= [34,66,12,89,28,99]

>>> list1.reverse()

>>> list1
[99, 28, 89, 12, 66, 34]

Reverses the order of >>>list1 = ['Tiger','Zebra',


reverse()
elements in the given list 'Lion','Cat','Elephant','Dog']

>>> list1.reverse()

>>> list1
['Dog','Elephant',
'Cat','Lion','Zebra','Tiger']

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

>>>list1=['Tiger','Zebra','Lio
n', 'Cat', 'Elephant' ,'Dog']

>>> list1.sort()

>>> list1
Sorts the elements of the ['Cat','Dog','Elephant',
sort() 'Lion', 'Tiger', 'Zebra']
given list in-place
>>>list1 = [34,66,12,89,28,99]

>>> list1.sort(reverse = True)

>>> list1
[99,89,66,34,28,12]
>>>list1 = [23,45,11,67,85,56]

It takes a list as parameter >>> list2 = sorted(list1)


and creates a new list
sorted() consisting of the same >>> list1
elements arranged in [23, 45, 11, 67, 85, 56]
sorted order
>>> list2
[11, 23, 45, 56, 67, 85]
Returns minimum or >>>list1 = [34,12,63,39,92,44]
min() smallest element of the
list >>> min(list1)
12
max() Returns maximum or
>>> max(list1)
largest element of the list 92

sum() Returns sum of the >>> sum(list1)


elements of the list 284

1.5 NESTED LISTS


 When a list appears as an element of another list, it is called a nested list
 To access the element of the nested list of list1, we have to specify two indices list1[i][j].
 The first index i will take us to the desired nested list and second index j
will take us to the desired element in that nested list.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.6 Copying Lists or Cloning Lists


The simplest way to make a copy of the list is to assign it to another list.

 The statement list2 = list1 does not create a new list. Rather, it just makes
list1 and list2 refer to the same list object.
 Here list2 actually becomes an alias of list1. Therefore, any changes made to
either of them will be reflected in the other list.

1.7 Aliasing
Giving a new name to an existing list is called 'aliasing'. The new name is called 'alias name'.

x = [10,20,30,40,50]
y = x # x is aliased as y
print(x)
print(y)

When we run the above code, it produces the output as follows

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.8 List as argument to a Function / List Parameters


 When you pass a list to a function, the function gets a reference to the list. If the function
modifies a list parameter, the caller sees the change.

def increment(list2):
for i in range(0, len(list2)):
list2[i] += 5

list1 = [10,20,30,40,50]
print("The list before the function call")
print(list1)
increment(list1)
print("The list after the function call")
print(list1)

When we run the above code, it produces the output as follows

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.9 Tuples

 A tuple is an ordered sequence of elements of different data types, such as integer,


float, string, list or even a tuple.
Elements of a tuple are enclosed in parenthesis (round brackets) and are separated
by commas. Like list and string, elements of a tuple can be accessed using index
values, starting from 0.
 Tuples are similar to the lists(mutable). But, the elements of a tuple are
immutable.

Creating a tuple in Python

Syntax
tuple_name = (element_1, element_2,...)
Example :-
#tuple1 is the tuple of integers
tuple1 = (1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
tuple2 =('Stats',65,'Maths',75)
#tuple3 is the tuple with list as an element
tuple3 = (10,20,30,[40,50])
#tuple4 is the tuple with tuple as an element
tuple4 = (1,2,3,4,5,(10,20))
print(tuple1)
print(tuple2)
print(tuple3)
print(tuple4)

When we run the above code, it produces the output as follows

In Python, a tuple can also be created using tuple( ) constructor.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.9.1 Accessing Elements in a Tuple


Elements of a tuple can be accessed in the same way as a list or string using indexing
and slicing.

tuple1 = (2,4,6,8,10,12) #initializes a tuple tuple1


print(tuple1[0]) #returns the first element of tuple1
print(tuple1[3]) #returns fourth element of tuple1
print(tuple1[-1]) #returns first element from right
print(tuple1[15]) #returns error as index is out of range

When we run the above code, it produces the output as follows

1.9.2 Tuple is an Immutable


 Tuple is an immutable data type. It means that the elements of a tuple cannot be
changed after it has been created. An attempt to do this would lead to an error.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.10 Tuple Operations


Like in lists, you can use the + operator to concatenate tuples together , the *
operator to repeat a sequence of tuple items, Membership and
slicing can be applied to tuples also

tuple1 = (1, 3, 5, 7, 9)
tuple2 = (2,4,6,8,10)
print(tuple1+tuple2)
tuple3 = (1,2,3,4,5)
tuple3 = tuple3 + (6,) #single element is appended to tuple3
print(tuple3)
print(tuple3[1:4]) #elements from index 1 to index 3
print(tuple3[:5]) #slice starts from zero index
tuple4 = ('Hello','World')
print(tuple4 * 3)
print('Hello' in tuple4)
print('Hello' not in tuple4)

When we run the above code, it produces the output as follows

1.11 Tuple Assignment


 Assignment of tuple is a useful feature in Python. It allows a tuple of variables on the
left side of the assignment operator to be assigned respective values from a tuple on
the right side.
 The number of variables on the left should be same as the number of elements in the
tuple.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example Program on Tuple Assignment:

(num1,num2) = (10,20)
print(num1)
print(num2)

record = ( "Pooja",40,"CS")
(name,rollNo,subject) = record
print(name,rollNo,subject)

When we run the above code, it produces the output as follows

 If there is an expression on the right side then first that expression is evaluated and
finally the result is assigned to the tuple.

(num3, num4) = (10 + 5, 20 + 5)


print(num3)
print(num4)

Output :
15
25
1.12 Tuple as return value
Functions can return tuples as return values.

def circleInfo(r):
#Return (circumference, area) of a circle of radius r
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)

print(circleInfo(10))

Output : (62.8318, 314.159)

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.13 Dictionaries :

 In Python, a dictionary is a collection of elements where each element is a pair of key


and value.
 All the elements of a dictionary must be enclosed in curly braces, each element
must be separated with a comma symbol, and every pair of key and value must be
separated with colon ( : ) symbol.

Creating a dictionary in Python

Syntax

dictionary_name = {key_1:value_1, key_2:value_2, ...}

In Python, a dictionary can also be created using the dict( ) constructor.

dict1=dict()
print(dict1)
dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict2)

When we run the above code, it produces the output as follows

1.13.1 Accessing Items in a Dictionary

The items of a dictionary are accessed via the keys rather than via their relative
positions or indices. Each key serves as the index and maps to a value

dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict2['Avanthi'])
print(dict2['Santhosh'])

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.14 Dictionaries are Mutable


 Dictionaries are mutable which implies that the contents of the dictionary can be
changed after it has been created.
 We can add a new item to the dictionary and The existing dictionary can be
modified by just overwriting the key-value pair.

dict2 = {'Santhosh':95,'Avanthi':89,'College':92}
dict2['Meena'] = 78
print(dict2)
dict2['Avanthi'] = 93.5
print(dict2)

When we run the above code, it produces the output as follow

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.15 Dictionary Methods and Built-In Functions


Python provides many functions to work on dictionaries.
Built-in functions and methods for dictionary

Method Description Example


Returns the length >>> dict1 =
or number of {'Santhosh':95,'Avanthi':89,'C
ollege':92}
key: value pairs
len()
of the dictionary
>>> len(dict1)
passed as the 3
argument
>>> pair1 =
[('Mohan',95),('Ram',89),
('Suhel',92),('Sangeeta',85)]
Creates a
dictionary from a >>> dict1 = dict(pair1)
dict() >>> dict1
sequence of key-
value pairs
[('Mohan',95),('Ram',89),
('Suhel',92),('Sangeeta',85)]

>>>dict1 = {'Mohan':95,
'Ram':89, 'Suhel':92,
'Sangeeta':85}
Returns a list of
keys() keys in the
>>> dict1.keys()
dictionary
dict_keys(['Mohan', 'Ram',
'Suhel','Sangeeta'])

>>> dict1 = {'Mohan':95,


'Ram':89, 'Suhel':92,
Returns a list of 'Sangeeta':85}
values() values in
the dictionary >>> dict1.values()

dict_values([95, 89, 92, 85])

>>> dict1 = {'Mohan':95,


'Ram':89, 'Suhel':92,
'Sangeeta':85}
Returns a list of
items() tuples(key – value) >>> dict1.items()
pair
dict_items([( 'Mohan', 95),
('Ram',89), ('Suhel', 92),
('Sangeeta', 85)])

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Returns the value


corresponding to >>> dict1 = {'Mohan':95,
the key passed as 'Ram':89, 'Suhel':92,
the 'Sangeeta':85}
Argument
get() >>> dict1.get('Sangeeta')
85
If the key is not
present in the >>> dict1.get('Sohan')
dictionary it will >>>
return None
>>> dict1 = {'Mohan':95,
'Ram':89, 'Suhel':92,
'Sangeeta':85}

>>> dict2 =
appends the key- {'Sohan':79,'Geeta':89}
value pair of the
>>> dict1.update(dict2)
dictionary passed
update() as the argument to
>>> dict1
the key-value pair
of the given {'Mohan': 95, 'Ram': 89,
dictionary 'Suhel': 92, 'Sangeeta': 85,
'Sohan': 79, 'Geeta':89}

>>> dict2

{'Sohan': 79, 'Geeta': 89}


>>> dict1 =
{'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}

>>> del dict1['Ram']

>>> dict1

Deletes the item {'Mohan':95,'Suhel':92,


with the given key 'Sangeeta': 85}

del() To delete the >>> del dict1 ['Mohan']


dictionary from the
memory we write: >>> dict1
del Dict_name
{'Suhel': 92, 'Sangeeta': 85}

>>> del dict1

>>> dict1

NameError: name 'dict1' is not


defined

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

>>> dict1 =
{'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
Deletes or clear all
clear() the items of
>>> dict1.clear()
the dictionary
>>> dict1
{ }

Example Program on Dictionary Methods :

dict1 = {'Santhosh':95,'Avanthi':89,'College':92}
print(dict1)
print("Displays the keys :",dict1.keys())
print("Displays the values :",dict1.values())
print("Displays the items : ",dict1.items())
print("length of the dictionary :",len(dict1))
print("value corresponding to the key college
:",dict1.get('College'))
del dict1['Avanthi']
print("Values after Deleting : ",dict1)

When we run the above code, it produces the output as follow

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.16 Advanced List Processing


List Comprehension :
 List comprehension is an elegant and concise way to create new list from an existing
list in Python.
 It creates a new list in which each element is the result of applying a given operation in
a list.
 List comprehension consists of an expression followed by for statement inside
square brackets.

Syntax
list=[ expression for item in list if conditional ]

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.17 Selection Sort


Selection Sort algorithm is used to arrange a list of elements in a particular order
(Ascending or Descending).
Step by Step Process
The selection sort algorithm is performed using the following steps...
Step 1 - Select the first element of the list (i.e., Element at first position in the list).
Step 2: Compare the selected element with all the other elements in the list.
Step 3: In every comparison, if any element is found smaller than the selected element
(for Ascending order), then both are swapped.
Step 4: Repeat the same procedure with element in the next position in the list till the
entire list is sorted.

Example Program:
def Selectionsort(num):
n=len(num)
for i in range(n):
for j in range(i+1,n):
if(num[i]>num[j]):
temp=num[i]
num[i]=num[j]
num[j]=temp
print("sorted List is ", num)

Selectionsort([5,2,4,1,9])

Output : sorted List is [1, 2, 4, 5, 9]

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.18 Insertion Sort


Insertion sort algorithm arranges a list of elements in a particular order. In insertion sort
algorithm, every iteration moves an element from unsorted portion to sorted portion until all
the elements are sorted in the list.

Step by Step Process


The insertion sort algorithm is performed using the following steps...
Step 1 – Assume that first element in the list is in sorted portion and all the remaining
elements are in unsorted portion
Step 2: Take first element from the unsorted portion and insert that element into the
sorted portion in the order specified..
Step 3: Repeat the above process until all the elements from the unsorted portion are
moved into the sorted portion.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example Program on Insertion Sort

def insertionsort(num):
for i in range(len(num)):
for j in range(0,i):
if(num[i]<num[j]):
temp=num[i]
num[i]=num[j]
num[j]=temp
print("sorted List is ", num)

insertionsort([5,2,4,1,9])

Output : sorted List is [1, 2, 4, 5, 9]

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

1.19 Merge Sort


Merge sort is one of the most important sorting algorithms based on the divide and conquer
technique.

1.20 Histogram
def histogram(items):
for n in items:
output=''
num=n
while (num>0):
output += '*'
num=num-1
print(output)

histogram([2,3,5,6,4])

Output :
**
***
*****
******
****

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Chapter-2 ( Files and Exception)


2.1 Introduction to Files
 File is a collection of data that stored on secondary memory like had disk of a computer.
 File handling in Python involves the reading and writing process and many other file
handling options.
 The built-in Python methods can manage two file types,
text file and binary file.
 The Python programming language provides built-in functions to perform operations on
files.
2.2 File Operations in Python
The following are the operations performed on files in Python programming language...
o Creating (or) Opening a file
o Reading data from a file
o Writing data into a file
o Closing a file
2.2.1 Creating (or) Opening a file
 In Python, we use the built-in function open( ). This function requires two
parameters, the first one is a file name with extension, and the second parameter
is the mode of opening.
 The built-in function open( ) returns a file object. We use the following syntax to
open a file.

Syntax
file = open("file_name.extension", "mode")

There are four different modes you can open a file to:

1. “r” = If you want to read from a file.


2. “w” = If you want to write to a file erasing completely previous data.
3. “a” = If you want to append to previously written file.
4. “x” = If you want just to create a file.

Additional used modes to specify the type of file is:

1. “t” = Text file, Default value.


2. “b” = binary file. For eg. Images.

For example : fp = open("my_file.txt", "w")

This will open a file named my_file.txt in text format.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.2.2 Writing data into a file


 To perform write operation into a file, the file must be opened in either 'w' mode
(WRITE) or 'a' mode (APPEND). The Python provides a built-in method write( ) to
write into the file..
 The 'w' mode overwrites any existing content from the current position of the cursor.
If the specified file does not exist, it creates a new file and inserts from the beginning.
 The 'a' mode insert the data next from the last character in the file. If the file does not
exist, it creates a new file and inserts from the beginning.

2.2.3 Reading data from a file


 First of all, to read data from a file, you need to open it in reading mode. You can then
call any of the Python methods for reading from a file.
Three different methods have provided to read file data.
• readline():The readline( ) method of file object reads all the characters from
the current cursor position to till the end of the line. But, optionally we
can also specify the number of characters to be read.

• read():The read() method of file object reads whole data from the open file. But,
optionally we can also specify the number of characters to be read.

• readlines():The readline( ) method of file object reads all lines until file end
and returns an object list.

2.2.4 Closing a file


The Python has a built-in method close( ) of the file object to close the file.
file_object.close()

Example Program on Write and read method

fPtr = open('Sample.txt', 'w')

fPtr.write("Python is an interpreted programming language ")


fPtr.close()

fPtr = open('Sample.txt', 'r')


print('The content of Sample.txt is: ')
print(fPtr.read())
fPtr.close()

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example Program on writelines, readline and readlines Methods :

fptr=open("D:Sample.txt","w")
fptr.writelines("Hello world \n Welcome to Technology")
fptr.close()

fPtr = open('D:\Sample.txt', 'r')


print('The content of Sample.txt : ')
print(fPtr.readline())
fPtr.close()

fPtr = open('D:\Sample.txt', "a")


fPtr.writelines("\n Welcome to Python")
fptr.close()

fPtr = open('D:\Sample.txt', 'r')


print('The updated content of Sample.txt : ')
print(fPtr.readlines())
fPtr.close()

Output :

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Write a Python Program to Count the Number of Words in a Text File

fPtr = open('Sample.txt', 'w')


fPtr.write("Python is an interpreted programming language ")
fPtr.close()

fPtr = open('Sample.txt', 'r')


str = fPtr.read()
l = str.split()
count_words = 0
for i in l:
count_words = count_words + 1
print("The no.of words in file is ",count_words)
fPtr.close()

Output :
The no.of words in file is 6

Write a Python Program to Count the Number of Words in a Text File

The shutil module provides some easy to use methods using which we can remove as well
as copy a file in Python.
The copyfile() method copies the content from the source to the target file using the file
paths. It returns the target file path.
The target file path must be writeable or else an OSerror exception would occur.

import shutil
shutil.copyfile( 'sample.txt' , 'targ.txt' )

fptr=open("targ.txt","r")
print(fptr.read())
fptr.close()

output :
Python is an interpreted programming language

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.3 Format operator


 The argument of write has to be a string, so if we want to put other values in a file,
we have to convert them to strings. The easiest way to do that is with str
 An alternative is to use the format operator, %. When applied to integers, % is the
modulus operator. But when the first operand is a string, % is the format operator.
 The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted. The result is a string.
 The format sequence '%d' means that the second operand should be formatted as
an integer (d stands for “decimal”):

Example :
Marks = 42
print('Ramu got %d Marks.' % Marks)

Output :
Ramu got 42 Marks.
2.4 Errors and Exception
 Errors are the problems in a program due to which the program will stop the
execution.
 Syntax errors are detected when we have not followed the rules of the particular
programming language while writing a program. These errors are also known as
parsing errors.

 An exception is an abnormal situation that is raised during the program execution.


 In simple words, an exception is a problem that arises at the time of program execution.
 When an exception occurs, it disrupts the program execution flow. When an exception
occurs, the program execution gets terminated, and the system generates an error.
 We use the exception handling mechanism to avoid abnormal termination of program
execution.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.4.1 BUILT-IN EXCEPTIONS


Commonly occurring exceptions are usually defined in the compiler/interpreter. These are
called built-in exceptions.
Built-in exception in Python
Name of the Built-in
S. No Explanation
Exception
It is raised when there is an error in the syntax
1 SyntaxError
of the Python code
It is raised when a built-in method or operation
2 ValueError receives an argument that has the right data
type but mismatched or inappropriate values.
It is raised when the file specified in a program
3 IOError
statement cannot be opened.
It is raised when the requested module
4 ImportError
definition is not found.
It is raised when the end of file condition is
5 EOFError
reached without reading any data by input().
It is raised when the denominator in a division
6 ZeroDivisionError
operation is zero.
It is raised when the index or subscript in a
7 IndexError
sequence is out of range
It is raised when a local or global variable name
8 NameError
is not defined
It is raised due to incorrect indentation in the
9 IndentationError
program code.
It is raised when an operator is supplied with a
10 TypeError
value of incorrect data type.
2.5 Exception Handling
Exception handling is a powerful mechanism to prevent the exception during the execution of
the program.

The Python programming language provides three keywords to handle the exceptions.

 try
 except
 finally

2.5.1 try
The try keyword is used to define a block of code which may cause an exception.
Syntax:
try:
statement(s)

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.5.2 except
The except keyword is used to define a block of code which handles the exception.
Syntax:
except:
statement(s)

2.5.3 finally

The finally keyword is used to define a block of code which is to execute, regardless of
an exception occurrence.

Syntax:
finally:
statement(s)

Note : The Python allows us to use an optional else keyword that can be used with try block.
The else is used to define a block of code to be executed if no exception were raised.
The following is the general syntax of exception handling in the Python.
Syntax:

try:
# the code that may raise an exception
except:
# the code that handles an exception
else:
# the code that to be executed if no exception were raised
finally:
# the code that must be executed

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

try:
x = int(input("enter first number: "))
y = int(input("enter second number: "))
result=x/y
print("The answer of x divide by y:", result)
except:
print("Can't divide with zero")
finally:
print("finally block")

When we run the above example code, it produces the following output.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.6 Catching the specific Exception


 In Python, the except block may also catch a particular exception. In such a case, it
handles only the particularized exception, if any other exception occurs it terminates
the execution.

a = int(input('Enter a number: '))


b = int(input('Enter a number: '))
try:
c = a / b
print('Result: ', c)
except ZeroDivisionError:
print('Exception: value of b can not be zero!')

When we run the above example code, it produces the following output for the values

a = r and b = 5. Here, the exception is a ValueError which can not be handled by the
above code.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.7 Modules
In Python, a module is a python file containing functions, class, and variables. A module is
included in any python application using an import statement.

How to create a module?


In Python programming, to create a module simply define the functions, classes, and
variables that you want to place in the module and save the file with .py extension.
For example, let's create a module which performs all arithmetic operations.
def add(a, b):
return a + b

def sub(a, b):


return a - b

def mul(a, b):


return a * b

def div(a, b):


return a / b

Save the above code as Calci.py so that the module can be used as Calci.

How to use a module?


A module is used in any python application by importing it using the import keyword. Now,
let's import the Calci module and use the functions of it.

import Calci

print(Calci.add(10, 5))
print(Calci.sub(10, 5))
print(Calci.mul(10, 5))
print(Calci.div(10, 5))

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

2.8 Packages

 A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required
in a program, that package can be imported.
 In Python, a package is a directory which must contains a __init__.py file. This file
can be an empty file.
 A package in the Python can contain any file with .py extension including modules

How to create a package?


To create a package in Python, just create a directory with the package name, then create an
empty file __init__.py inside that directory. Then the directory acts as a package which can be
imported the same way a module can be imported.

How to use a package?


To use a package in python, we must import the package using import statement the same way
a module has imported in the earlier tutorials.
For example, a package with name My_Package can be imported as import My_Package.
A specific module can also be imported using the syntax
from Package_Name import Module_Name.

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Example on creating a package:

 Let us create a package with two different modules.


 Creating a directory is the first step in creating a package.
 Let’s create a directory College

The following step is to add three Python modules to the directory.

Create __init__.py file

Code in file students.py

def getStudents():
print("There are total 2500 students")

Code in file Teachers.py

def getTeachers():
print("There are total 70 teachers")

Code in file Main.py

from College.Students import getStudents


from College.Teachers import getTeachers
getStudents()
getTeachers()

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com


www.android.universityupdates.in | www.universityupdates.in | www.ios.universityupdates.in

Unit-III Questions
1. Explain about list in detail (List operations and Methods)
2. Write a short note on
(a) Aliasing
(b) cloning list
(c) list parameters
3. Explain tuple in detail
4. Explain Dictionaries in detail
5. Write a short note on advanced processing (list
comprehension)
6. Explain files in detail with an example programs
7. Exception handling (try, except and finally)
8. Write about Modules and Packages

www.android.previousquestionpapers.com | www.previousquestionpapers.com | www.ios.previousquestionpapers.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy