0% found this document useful (0 votes)
3 views

python part 5

The document provides an overview of list operations in Python, including basic operations like indexing, slicing, and various list methods such as append, extend, insert, pop, remove, reverse, and sort. It also discusses mutability, aliasing, cloning lists, passing lists as parameters, and introduces list comprehensions for creating lists concisely. Additionally, it briefly touches on tuples, highlighting their immutability and efficiency compared to lists.

Uploaded by

mkhandsettask
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)
3 views

python part 5

The document provides an overview of list operations in Python, including basic operations like indexing, slicing, and various list methods such as append, extend, insert, pop, remove, reverse, and sort. It also discusses mutability, aliasing, cloning lists, passing lists as parameters, and introduces list comprehensions for creating lists concisely. Additionally, it briefly touches on tuples, highlighting their immutability and efficiency compared to lists.

Uploaded by

mkhandsettask
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

PYTHON PROGRAMMING III YEAR/II SEM MRCET

List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership

Basic List Operations:

Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.

Python Expression Results Description

len([1, 2, 3]) 3 Length

[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation

['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition

3 in [1, 2, 3] True Membership

for x in [1, 2, 3]: print x, 123 Iteration

Indexing, Slicing, and Matrixes

Because lists are sequences, indexing and slicing work the same way for lists as they do for
strings.
Assuming following input −
L = ['mrcet', 'college', 'MRCET!']

Python Expression Results Description

L[2] MRCET Offsets start at zero

79
PYTHON PROGRAMMING III YEAR/II SEM MRCET
L[-2] college Negative: count from the right

L[1:] ['college', 'MRCET!'] Slicing fetches sections

List slices:

>>> list1=range(1,6)
>>> list1
range(1, 6)
>>> print(list1)
range(1, 6)
>>> list1=[1,2,3,4,5,6,7,8,9,10]
>>> list1[1:]
[2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list1[:1]
[1]
>>> list1[2:5]
[3, 4, 5]
>>> list1[:6]
[1, 2, 3, 4, 5, 6]
>>> list1[1:2:4]
[2]
>>> list1[1:8:2]
[2, 4, 6, 8]
List methods:
The list data type has some more methods. Here are all of the methods of list objects:
 Del()
80
PYTHON PROGRAMMING III YEAR/II SEM MRCET
 Append()
 Extend()
 Insert()
 Pop()
 Remove()
 Reverse()
 Sort()
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
------------
>>> del(x)
>>> x # complete list gets deleted
Append: Append an item to a list
>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 3, 6, 9, 1]
Insert: To add an item at the specified index, use the insert () method:

>>> x=[1,2,4,6,7]

81
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.insert(2,10) #insert(index no, item to be inserted)

>>> x

[1, 2, 10, 4, 6, 7]

-------------------------

>>> x.insert(4,['a',11])

>>> x

[1, 2, 10, 4, ['a', 11], 6, 7]

Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.

>>> x=[1, 2, 10, 4, 6, 7]

>>> x.pop()

>>> x

[1, 2, 10, 4, 6]

-----------------------------------

>>> x=[1, 2, 10, 4, 6]

>>> x.pop(2)

10

>>> x

[1, 2, 4, 6]

Remove: The remove() method removes the specified item from a given list.

>>> x=[1,33,2,10,4,6]

>>> x.remove(33)

>>> x

82
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[1, 2, 10, 4, 6]

>>> x.remove(4)

>>> x

[1, 2, 10, 6]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

-----------------------

>>> x=[10,1,5,3,8,7]

>>> x.sort()

>>> x

[1, 3, 5, 7, 8, 10]

List loop:

Loops are control structures used to repeat a given section of code a certain number of times
or until a particular condition is met.

Method #1: For loop

#list of items

list = ['M','R','C','E','T']
83
PYTHON PROGRAMMING III YEAR/II SEM MRCET
i=1

#Iterating over the list


for item in list:
print ('college ',i,' is ',item)
i = i+1
Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T

Method #2: For loop and range()


In case we want to use the traditional for loop which iterates from number x to number y.
# Python3 code to iterate over a list
list = [1, 3, 5, 7, 9]

# getting length of list


length = len(list)

# Iterating the index


# same as 'for i in range(len(list))'
for i in range(length):
print(list[i])

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/listlooop.py
1
3
5
7
9
Method #3: using while loop

# Python3 code to iterate over a list


list = [1, 3, 5, 7, 9]

# Getting length of list


84
PYTHON PROGRAMMING III YEAR/II SEM MRCET
length = len(list)
i=0

# Iterating using while loop


while i < length:
print(list[i])
i += 1

Mutability:

A mutable object can be changed after it is created, and an immutable object can't.

Append: Append an item to a list


>>> x=[1,5,8,4]
>>> x.append(10)
>>> x
[1, 5, 8, 4, 10]
Extend: Append a sequence to a list.
>>> x=[1,2,3,4]
>>> y=[3,6,9,1]
>>> x.extend(y)
>>> x
Delete: Delete a list or an item from a list
>>> x=[5,3,8,6]
>>> del(x[1]) #deletes the index position 1 in a list
>>> x
[5, 8, 6]
Insert: To add an item at the specified index, use the insert () method:

>>> x=[1,2,4,6,7]

>>> x.insert(2,10) #insert(index no, item to be inserted)

85
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x

[1, 2, 10, 4, 6, 7]

-------------------------

>>> x.insert(4,['a',11])

>>> x

[1, 2, 10, 4, ['a', 11], 6, 7]

Pop: The pop() method removes the specified index, (or the last item if index is not
specified) or simply pops the last item of list and returns the item.

>>> x=[1, 2, 10, 4, 6, 7]

>>> x.pop()

>>> x

[1, 2, 10, 4, 6]

-----------------------------------

>>> x=[1, 2, 10, 4, 6]

>>> x.pop(2)

10

>>> x

[1, 2, 4, 6]

Remove: The remove() method removes the specified item from a given list.

>>> x=[1,33,2,10,4,6]

>>> x.remove(33)

>>> x

[1, 2, 10, 4, 6]

86
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x.remove(4)

>>> x

[1, 2, 10, 6]

Reverse: Reverse the order of a given list.


>>> x=[1,2,3,4,5,6,7]
>>> x.reverse()
>>> x
[7, 6, 5, 4, 3, 2, 1]
Sort: Sorts the elements in ascending order
>>> x=[7, 6, 5, 4, 3, 2, 1]

>>> x.sort()

>>> x

[1, 2, 3, 4, 5, 6, 7]

-----------------------

>>> x=[10,1,5,3,8,7]

>>> x.sort()

>>> x

[1, 3, 5, 7, 8, 10]

Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2. If the data is immutable, aliases don’t matter because the data can’t change.
3. But if data can change, aliases can result in lot of hard – to – find bugs.
4. Aliasing happens whenever one variable’s value is assigned to another variable.

For ex:
a = [81, 82, 83]
87
PYTHON PROGRAMMING III YEAR/II SEM MRCET
b = [81, 82, 83]
print(a == b)
print(a is b)
b=a
print(a == b)
print(a is b)
b[0] = 5
print(a)
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/alia.py
True
False
True
True
[5, 82, 83]

Because the same list has two different names, a and b, we say that it is aliased. Changes
made with one alias affect the other. In the example above, you can see that a and b refer to
the same list after executing the assignment statement b = a.
Cloning Lists:

If we want to modify a list and also keep a copy of the original, we need to be able to make a
copy of the list itself, not just the reference. This process is sometimes called cloning, to
avoid the ambiguity of the word copy.

The easiest way to clone a list is to use the slice operator. Taking any slice of a creates a new
list. In this case the slice happens to consist of the whole list.

Example:

a = [81, 82, 83]

b = a[:] # make a clone using slice

print(a == b)

print(a is b)

b[0] = 5

print(a)

print(b)
88
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/clo.py

True
False
[81, 82, 83]
[5, 82, 83]
Now we are free to make changes to b without worrying about a

List parameters:

Passing a list as an argument actually passes a reference to the list, not a copy of the list.
Since lists are mutable, changes made to the elements referenced by the parameter change
the same list that the argument is referencing.

# for example, the function below takes a list as an argument and multiplies each element in
the list by 2:

def doubleStuff(List):

""" Overwrite each element in aList with double its value. """

for position in range(len(List)):

List[position] = 2 * List[position]

things = [2, 5, 9]

print(things)

doubleStuff(things)

print(things)

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/lipar.py ==

[2, 5, 9]

[4, 10, 18]

89
PYTHON PROGRAMMING III YEAR/II SEM MRCET

List comprehension:

List:

List comprehensions provide a concise way to create lists. Common applications are to make
new lists where each element is the result of some operations applied to each member of
another sequence or iterable, or to create a subsequence of those elements that satisfy a
certain condition.

For example, assume we want to create a list of squares, like:

>>> list1=[]

>>> for x in range(10):

list1.append(x**2)

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

(or)

This is also equivalent to

>>> list1=list(map(lambda x:x**2, range(10)))

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

(or)

Which is more concise and redable.

>>> list1=[x**2 for x in range(10)]

>>> list1

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


90
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Similarily some examples:

>>> x=[m for m in range(8)]


>>> print(x)
[0, 1, 2, 3, 4, 5, 6, 7]

>>> x=[z**2 for z in range(10) if z>4]


>>> print(x)
[25, 36, 49, 64, 81]

>>> x=[x ** 2 for x in range (1, 11) if x % 2 == 1]


>>> print(x)
[1, 9, 25, 49, 81]

>>> a=5
>>> table = [[a, b, a * b] for b in range(1, 11)]
>>> for i in table:
print(i)

[5, 1, 5]
[5, 2, 10]
[5, 3, 15]
[5, 4, 20]
[5, 5, 25]
[5, 6, 30]
[5, 7, 35]
[5, 8, 40]
[5, 9, 45]
[5, 10, 50]

Tuples:

A tuple is a collection which is ordered and unchangeable. In Python tuples are written
with round brackets.
 Supports all operations for sequences.
 Immutable, but member objects may be mutable.
 If the contents of a list shouldn’t change, use a tuple to prevent items from

91
PYTHON PROGRAMMING III YEAR/II SEM MRCET
accidently being added, changed, or deleted.
 Tuples are more efficient than list due to python’s implementation.

We can construct tuple in many ways:


X=() #no item tuple
X=(1,2,3)
X=tuple(list1)
X=1,2,3,4

Example:
>>> x=(1,2,3)
>>> print(x)
(1, 2, 3)
>>> x
(1, 2, 3)
-----------------------
>>> x=()
>>> x
()
----------------------------
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
-----------------------------
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)

Some of the operations of tuple are:


 Access tuple items
 Change tuple items
 Loop through a tuple
 Count()
 Index()
 Length()

92
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Access tuple items: Access tuple items by referring to the index number, inside square
brackets
>>> x=('a','b','c','g')
>>> print(x[2])
c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples
are unchangeable.

>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same

Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)

4
5
6
7
2
aa

Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2)
4

Index (): Searches the tuple for a specified value and returns the position of where it
was found

93
PYTHON PROGRAMMING III YEAR/II SEM MRCET
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2)
1

(Or)

>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y)
1

Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y)
12

Tuple Assignment

Python has tuple assignment feature which enables you to assign more than one variable at a
time. In here, we have assigned tuple 1 with the college information like college name, year,
etc. and another tuple 2 with the values in it like number (1, 2, 3… 7).

For Example,

Here is the code,

 >>> tup1 = ('mrcet', 'eng college','2004','cse', 'it','csit');

 >>> tup2 = (1,2,3,4,5,6,7);

 >>> print(tup1[0])

 mrcet

 >>> print(tup2[1:4])

 (2, 3, 4)

Tuple 1 includes list of information of mrcet

Tuple 2 includes list of numbers in it


94
PYTHON PROGRAMMING III YEAR/II SEM MRCET
We call the value for [0] in tuple and for tuple 2 we call the value between 1 and 4

Run the above code- It gives name mrcet for first tuple while for second tuple it gives
number (2, 3, 4)

Tuple as return values:


A Tuple is a comma separated sequence of items. It is created with or without (). Tuples are
immutable.

# A Python program to return multiple values from a method using tuple

# This function returns a tuple


def fun():
str = "mrcet college"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)
# Driver code to test above method
str, x = fun() # Assign returned tuple
print(str)
print(x)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/tupretval.py
mrcet college
20

 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:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/functupretval.py
(62.8318, 314.159)
95
PYTHON PROGRAMMING III YEAR/II SEM MRCET
------------------------------
def f(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return (y0, y1, y2)

Tuple comprehension:
Tuple Comprehensions are special: The result of a tuple comprehension is special. You
might expect it to produce a tuple, but what it does is produce a special "generator"
object that we can iterate over.

For example:
>>> x = (i for i in 'abc') #tuple comprehension
>>> x
<generator object <genexpr> at 0x033EEC30>

>>> print(x)
<generator object <genexpr> at 0x033EEC30>

You might expect this to print as ('a', 'b', 'c') but it prints as <generator object <genexpr>
at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a
generator. The only thing that you need to know now about a generator now is that you
can iterate over it, but ONLY ONCE.
So, given the code

>>> x = (i for i in 'abc')


>>> for i in x:
print(i)

a
b
c
Create a list of 2-tuples like (number, square):
>>> z=[(x, x**2) for x in range(6)]
>>> z
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
96
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Set:
Similarly to list comprehensions, set comprehensions are also supported:

>>> a = {x for x in 'abracadabra' if x not in 'abc'}


>>> a
{'r', 'd'}

>>> x={3*x for x in range(10) if x>5}


>>> x
{24, 18, 27, 21}

Dictionaries:

A dictionary is a collection which is unordered, changeable and indexed. In Python


dictionaries are written with curly brackets, and they have keys and values.
 Key-value pairs
 Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)

Example:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2004}

Operations and methods:

Methods that are available with dictionary are tabulated below. Some of them have already
been used in the above examples.

Method Description

clear() Remove all items form the dictionary.

97
PYTHON PROGRAMMING III YEAR/II SEM MRCET

copy() Return a shallow copy of the dictionary.

Return a new dictionary with keys from seq and


fromkeys(seq[, v]) value equal to v (defaults to None).

Return the value of key. If key doesnot exit,


get(key[,d]) return d (defaults to None).

Return a new view of the dictionary's items


items() (key, value).

keys() Return a new view of the dictionary's keys.

Remove the item with key and return its value


or d if key is not found. If d is not provided
pop(key[,d]) and key is not found, raises KeyError.

Remove and return an arbitary item (key,


value). Raises KeyError if the dictionary is
popitem() empty.

If key is in the dictionary, return its value. If


not, insert key with a value of d and
setdefault(key[,d]) return d (defaults to None).

Update the dictionary with the key/value pairs


update([other]) from other, overwriting existing keys.

values() Return a new view of the dictionary's values

Below are some dictionary operations:

98
PYTHON PROGRAMMING III YEAR/II SEM MRCET
To access specific value of a dictionary, we must pass its key,
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> x=dict1["brand"]
>>> x
'mrcet'
---------------------
To access keys and values and items of dictionary:
>>> dict1 = {"brand":"mrcet","model":"college","year":2004}
>>> dict1.keys()
dict_keys(['brand', 'model', 'year'])
>>> dict1.values()
dict_values(['mrcet', 'college', 2004])
>>> dict1.items()
dict_items([('brand', 'mrcet'), ('model', 'college'), ('year', 2004)])
-----------------------------------------------
>>> for items in dict1.values():
print(items)

mrcet
college
2004

>>> for items in dict1.keys():


print(items)

brand
model
year

>>> for i in dict1.items():


print(i)

('brand', 'mrcet')
('model', 'college')
('year', 2004)

Some more operations like:


 Add/change
99
PYTHON PROGRAMMING III YEAR/II SEM MRCET
 Remove
 Length
 Delete

Add/change values: You can change the value of a specific item by referring to its key
name

>>> dict1 = {"brand":"mrcet","model":"college","year":2004}


>>> dict1["year"]=2005
>>> dict1
{'brand': 'mrcet', 'model': 'college', 'year': 2005}

Remove(): It removes or pop the specific item of dictionary.

>>> dict1 = {"brand":"mrcet","model":"college","year":2004}


>>> print(dict1.pop("model"))
college
>>> dict1
{'brand': 'mrcet', 'year': 2005}

Delete: Deletes a particular item.

>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}


>>> del x[5]
>>> x

Length: we use len() method to get the length of dictionary.

>>>{1: 1, 2: 4, 3: 9, 4: 16}
{1: 1, 2: 4, 3: 9, 4: 16}
>>> y=len(x)
>>> y
4
Iterating over (key, value) pairs:
>>> x = {1:1, 2:4, 3:9, 4:16, 5:25}
>>> for key in x:
print(key, x[key])

11
24
39
100
PYTHON PROGRAMMING III YEAR/II SEM MRCET
4 16
5 25
>>> for k,v in x.items():
print(k,v)

11
24
39
4 16
5 25

List of Dictionaries:

>>> customers = [{"uid":1,"name":"John"},


{"uid":2,"name":"Smith"},
{"uid":3,"name":"Andersson"},
]
>>> >>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'Andersson'}]

## Print the uid and name of each customer


>>> for x in customers:
print(x["uid"], x["name"])

1 John
2 Smith
3 Andersson

## Modify an entry, This will change the name of customer 2 from Smith to Charlie
>>> customers[2]["name"]="charlie"
>>> print(customers)
[{'uid': 1, 'name': 'John'}, {'uid': 2, 'name': 'Smith'}, {'uid': 3, 'name': 'charlie'}]

## Add a new field to each entry

>>> for x in customers:


x["password"]="123456" # any initial value

>>> print(customers)
101
PYTHON PROGRAMMING III YEAR/II SEM MRCET
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 2, 'name': 'Smith', 'password':
'123456'}, {'uid': 3, 'name': 'charlie', 'password': '123456'}]

## Delete a field
>>> del customers[1]
>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}, {'uid': 3, 'name': 'charlie', 'password':
'123456'}]

>>> del customers[1]


>>> print(customers)
[{'uid': 1, 'name': 'John', 'password': '123456'}]

## Delete all fields

>>> for x in customers:


del x["uid"]

>>> x
{'name': 'John', 'password': '123456'}

Comprehension:

Dictionary comprehensions can be used to create dictionaries from arbitrary key and
value expressions:

>>> z={x: x**2 for x in (2,4,6)}


>>> z
{2: 4, 4: 16, 6: 36}

>>> dict11 = {x: x*x for x in range(6)}


>>> dict11
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

102
PYTHON PROGRAMMING III YEAR/II SEM MRCET
UNIT – V

FILES, EXCEPTIONS, MODULES, PACKAGES

Files and exception: text files, reading and writing files, command line arguments, errors
and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module),
Explore packages.

Files, Exceptions, Modules, Packages:

Files and exception:

A file is some information or data which stays in the computer storage devices. Python gives
you easy ways to manipulate these files. Generally files divide in two categories,
text file and binary file. Text files are simple text where as the binary files contain binary
data which is only readable by computer.

 Text files: In this type of file, Each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‘\n’) in python by default.

 Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.

An exception is an event, which occurs during the execution of a program that disrupts the
normal flow of the program's instructions. In general, when a Python script encounters a
situation that it cannot cope with, it raises an exception. An exception is a Python object
that represents an error.

Text files:

We can create the text files by using the syntax:

Variable name=open (“file.txt”, file mode)

For ex: f= open ("hello.txt","w+")

 We declared the variable f to open a file named hello.txt. Open takes 2 arguments, the
file that we want to open and a string that represents the kinds of permission or
operation we want to do on the file
 Here we used "w" letter in our argument, which indicates write and the plus sign that
means it will create a file if it does not exist in library

103
PYTHON PROGRAMMING III YEAR/II SEM MRCET
 The available option beside "w" are "r" for read and "a" for append and plus sign
means if it is not there then create it

File Modes in Python:

Mode Description

'r' This is the default mode. It Opens file for reading.

'w' This Mode Opens file for writing.


If file does not exist, it creates a new file.
If file exists it truncates the file.

'x' Creates a new file. If file already exists, the operation fails.

'a' Open file in append mode.


If file does not exist, it creates a new file.

't' This is the default mode. It opens in text mode.

'b' This opens in binary mode.

'+' This will open a file for reading and writing (updating)

Reading and Writing files:

The following image shows how to create and open a text file in notepad from command
prompt

104
PYTHON PROGRAMMING III YEAR/II SEM MRCET

(or)

Hit on enter then it shows the following whether to open or not?

Click on “yes” to open else “no” to cancel

# Write a python program to open and read a file

a=open(“one.txt”,”r”)
print(a.read())
105
PYTHON PROGRAMMING III YEAR/II SEM MRCET
a.close()

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/filess/f1.py
welcome to python programming

(or)

Note: All the program files and text files need to saved together in a particular file then
only the program performs the operations in the given file mode

f.close() ---- This will close the instance of the file somefile.txt stored

# Write a python program to open and write “hello world” into a file?

f=open("1.txt","a")

f.write("hello world")

f.close()

Output:

106
PYTHON PROGRAMMING III YEAR/II SEM MRCET

(or)

Note: In the above program the 1.txt file is created automatically and adds hello world
into txt file

If we keep on executing the same program for more than one time then it append the data
that many times

# Write a python program to write the content “hi python programming” for the
existing file.

f=open("1.txt",'w')

f.write("hi python programming")

f.close()

Output:

In the above program the hello txt file consist of data like

107
PYTHON PROGRAMMING III YEAR/II SEM MRCET
But when we try to write some data on to the same file it overwrites and saves with the
current data (check output)

# Write a python program to open and write the content to file and read it.

fo=open("abc.txt","w+")

fo.write("Python Programming")

print(fo.read())

fo.close()

Output:

(or)

Note: It creates the abc.txt file automatically and writes the data into it

108
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Command line arguments:

The command line arguments must be given whenever we want to give the input before the
start of the script, while on the other hand, raw_input() is used to get the input while the
python program / script is running.

The command line arguments in python can be processed by using either ‘sys’ module,
‘argparse’ module and ‘getopt’ module.

‘sys’ module :

Python sys module stores the command line arguments into a list, we can access it
using sys.argv. This is very useful and simple way to read command line arguments as
String.
sys.argv is the list of commandline arguments passed to the Python program. argv represents
all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program

>>> sys.modules.keys() -- this prints so many dict elements in the form of list.

# Python code to demonstrate the use of 'sys' module for command line arguments

import sys

# command line arguments are stored in the form


# of list in sys.argv
argumentList = sys.argv
print(argumentList)

# Print the name of file


print(sys.argv[0])

# Print the first argument after the name of file


#print(sys.argv[1])

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py

['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py']
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/cmndlinarg.py

109
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Note: Since my list consist of only one element at ‘0’ index so it prints only that list
element, if we try to access at index position ‘1’ then it shows the error like,

IndexError: list index out of range


------------------

import sys

print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py ==
<class 'list'>
The command line arguments are:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/symod.py

# write a python program to get python version.


import sys
print("System version is:")
print(sys.version)
print("Version Information is:")
print(sys.version_info)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/s1.py =
System version is:
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
Version Information is:
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)

‘argparse’ module :

Python getopt module is very similar in working as the C getopt() function for parsing
command-line parameters. Python getopt module is useful in parsing command line
arguments where we want user to enter some options too.

>>> parser = argparse.ArgumentParser(description='Process some integers.')

#---------
110
PYTHON PROGRAMMING III YEAR/II SEM MRCET
import argparse

parser = argparse.ArgumentParser()
print(parser.parse_args())

‘getopt’ module :

Python argparse module is the preferred way to parse command line arguments. It provides a
lot of option such as positional arguments, default value for arguments, help message,
specifying data type of argument etc

It parses the command line options and parameter list. The signature of this function is
mentioned below:

getopt.getopt(args, shortopts, longopts=[ ])

 args are the arguments to be passed.


 shortopts is the options this script accepts.
 Optional parameter, longopts is the list of String parameters this function accepts
which should be supported. Note that the -- should not be prepended with option
names.

-h --------- print help and usage message


-m --------- accept custom option value
-d --------- run the script in debug mode

import getopt
import sys

argv = sys.argv[0:]
try:
opts, args = getopt.getopt(argv, 'hm:d', ['help', 'my_file='])
#print(opts)
print(args)
except getopt.GetoptError:
# Print a message or do something useful
print('Something went wrong!')
sys.exit(2)

111
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py ==

['C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/gtopt.py']

Errors and Exceptions:

Python Errors and Built-in Exceptions: Python (interpreter) raises exceptions when it
encounters errors. When writing a program, we, more often than not, will
encounter errors. Error caused by not following the proper structure (syntax) of the language
is called syntax error or parsing error

ZeroDivisionError:

ZeroDivisionError in Python indicates that the second argument used in a division (or
modulo) operation was zero.

OverflowError:

OverflowError in Python indicates that an arithmetic operation has exceeded the limits of
the current Python runtime. This is typically due to excessively large float values, as integer
values that are too big will opt to raise memory errors instead.

ImportError:

It is raised when you try to import a module which does not exist. This may happen if you
made a typing mistake in the module name or the module doesn't exist in its standard path.
In the example below, a module named "non_existing_module" is being imported but it
doesn't exist, hence an import error exception is raised.

IndexError:

An IndexError exception is raised when you refer a sequence which is out of range. In the
example below, the list abc contains only 3 entries, but the 4th index is being accessed,
which will result an IndexError exception.

TypeError:

When two unrelated type of objects are combined, TypeErrorexception is raised.In example
below, an int and a string is added, which will result in TypeError exception.
112
PYTHON PROGRAMMING III YEAR/II SEM MRCET
IndentationError:

Unexpected indent. As mentioned in the "expected an indentedblock" section, Python not


only insists on indentation, it insists on consistentindentation. You are free to choose the
number of spaces of indentation to use, but you then need to stick with it.

Syntax errors:

These are the most basic type of error. They arise when the Python parser is unable to
understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a
way to successfully execute a piece of code containing syntax errors.

Run-time error:

A run-time error happens when Python understands what you are saying, but runs into
trouble when following your instructions.

Key Error :

Python raises a KeyError whenever a dict() object is requested (using the


format a = adict[key]) and the key is not in the dictionary.

Value Error:

In Python, a value is the information that is stored within a certain object. To encounter a
ValueError in Python means that is a problem with the content of the object you tried to
assign the value to.

Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. In Python, users can define such exceptions by creating a new
class. This exception class has to be derived, either directly or indirectly,
from Exception class.

Different types of exceptions:

 ArrayIndexOutOfBoundException.
 ClassNotFoundException.
 FileNotFoundException.
 IOException.
 InterruptedException.
 NoSuchFieldException.
 NoSuchMethodException

113
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Handling Exceptions:

The cause of an exception is often external to the program itself. For example, an incorrect
input, a malfunctioning IO device etc. Because the program abruptly terminates on
encountering an exception, it may cause damage to system resources, such as files. Hence,
the exceptions should be properly handled so that an abrupt termination of the program is
prevented.

Python uses try and except keywords to handle exceptions. Both keywords are followed by
indented blocks.

Syntax:

try :

#statements in try block

except :

#executed when error in try block

Typically we see, most of the times

 Syntactical errors (wrong spelling, colon ( : ) missing ….),


At developer level and compile level it gives errors.

 Logical errors (2+2=4, instead if we get output as 3 i.e., wrong output …..,),
As a developer we test the application, during that time logical error may obtained.

 Run time error (In this case, if the user doesn’t know to give input, 5/6 is ok but if
the user say 6 and 0 i.e.,6/0 (shows error a number cannot be divided by zero))
This is not easy compared to the above two errors because it is not done by the
system, it is (mistake) done by the user.

The things we need to observe are:

1. You should be able to understand the mistakes; the error might be done by user, DB
connection or server.
2. Whenever there is an error execution should not stop.
Ex: Banking Transaction
3. The aim is execution should not stop even though an error occurs.

114
PYTHON PROGRAMMING III YEAR/II SEM MRCET

For ex:

a=5

b=2

print(a/b)

print("Bye")

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex1.py

2.5

Bye

 The above is normal execution with no error, but if we say when b=0, it is a
critical and gives error, see below

a=5

b=0

print(a/b)

print("bye") #this has to be printed, but abnormal termination

Output:

Traceback (most recent call last):

File "C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ex2.py", line


3, in <module>

print(a/b)

ZeroDivisionError: division by zero

 To overcome this we handle exceptions using except keyword

a=5
b=0
115

You might also like