Unit-III Python Notes (1) (4)
Unit-III Python Notes (1) (4)
Chapter-I(Lists)
INTRODUCTION TO LIST
The datatype 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 datatypes.
Elements of a list are enclosed in square brackets and are separated by comma. Like
string indices, list indices also start from 0.
Example:
Accessing Elements in a List
The elements of a list are accessed in the same way as characters are accessed in a
string.
Syntax:-
list_name[index]=new_value
Lists Operations
The datatype list allows manipulation of its contents through various operations as
shown below.
1. Concatenation
2. Repetition
3. Membership
4. Slicing
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 datatype, Type Error occurs.
Repetition:
Python allows us to replicate a list using repetition operator depicted by symbol*
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.
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 upto 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.
TraversingaList
We can access each element of the list or traverse a list using a for loop or a while loop.
List Traversing using for Loop
list1=['Red','Green','Blue','Black']
for item in list1:
print(item)
Output:
Red
Green
Blue
Black
List Traversing using while Loop
list1=['Red','Green','Blue','Black'] Output:
i = 0 Red
whilei<len(list1): Green
print(list1[i])
Blue
i += 1
Black
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.
>>>list1.reverse()
>>>list1
[99, 28, 89, 12, 66, 34]
>>>list1.reverse()
>>> list1
['Dog','Elephant',
'Cat','Lion','Zebra','Tiger']
>>>list1=['Tiger','Zebra','Lio
n', 'Cat', 'Elephant' ,'Dog']
>>>list1.sort()
>>> list1
['Cat','Dog','Elephant',
Sorts the elements of the
sort() 'Lion', 'Tiger', 'Zebra']
given list in-place
>>>list1 = [34,66,12,89,28,99]
>>> list1
[99,89,66,34,28,12]
>>>list1 = [23,45,11,67,85,56]
NESTEDLISTS
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.
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 doesnot 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.
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 #xisaliasedasy
print(x)
print(y)
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)
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 datatypes
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)
Whenweruntheabovecode,itproducestheoutputasfollows
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.
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 index1 to index3
print(tuple3[:5]) #slice starts from zero index
tuple4 = ('Hello','World')
print(tuple4 * 3)
print('Hello'in tuple4)
print('Hello'notintuple4)
When we run the above code ,it produces the output as follows
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.
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 rightside 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
Tuple a sreturn 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)
Dictionaries:
Syntax
dictionary_name={key_1:value_1,key_2:value_2,...}
dict1=dict()
print(dict1)
dict2={'Santhosh':95,'Avanthi':89,'College':92}
print(dict2)
The items of a dictionaryare accessed via the keysrather 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'])
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
Dictionary Methods and Built-In Functions
Python provides many functions to work on dictionaries.
Built-in functions and methods for dictionary
>>>dict1={'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
Returns a list of
>>> dict1.keys()
keys() keys in the
dictionary dict_keys(['Mohan','Ram',
'Suhel','Sangeeta'])
>>>dict1={'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
Returns a list of
values() values in >>> dict1.values()
The dictionary
dict_values([95,89,92,85])
>>>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
>>>dict1
>>>dict1
NameError:name'dict1'isnot
defined
>>> dict1 =
{'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
Deletes or clear all
clear() the items of
>>>dict1.clear()
The dictionary
>>>dict1
{ }
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)
Syntax
list=[expression for item in list if conditional]
Chapter-2(FilesandException)
IntroductiontoFiles
File is a collection of data that stored on secondary memory like hard 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.
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
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:
• 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.
Closinga file
The Python has a built-in method close() of the file object to close the file.
file_object.close()
fPtr=open('Sample.txt','w')
fptr=open("D:Sample.txt","w")
fptr.writelines("Hello world\nWelcome to Technology")
fptr.close()
fPtr=open('D:\Sample.txt','r')
print('The updated content of Sample.txt:')
print(fPtr.readlines())
fPtr.close()
Output:
Writea 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 fileis",count_words)
fPtr.close()
Output:
The no. of words in file is 6
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.
importshutil
shutil.copyfile('sample.txt','targ.txt')
fptr=open("targ.txt","r")
print(fptr.read())
fptr.close()
output:
Python is an interpreted programming language
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('Ramugot%dMarks.'%Marks)
Output:
Ramu got 42 Marks.
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.
The Python programming language provides three keywords to handle the exceptions.
try
except
finally
try
The try keyword is used to define a block of code which may cause an exception.
Syntax:
try:
statement(s)
except
The except keyword isused to define a block of code which handles the exception.
Syntax:
except:
statement(s)
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
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")
Whenweruntheaboveexamplecode,itproducesthefollowingoutput.
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 cannot 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 cannot be handled by the above
code.
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 tocreateamodule?
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):
returna+b
Save the above code as Calci.py so that the module can be used as Calci.
import Calci
print(Calci.add(10,5))
print(Calci.sub(10,5))
print(Calci.mul(10,5))
print(Calci.div(10,5))
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
Def getStudents():
print("There are total 2500 students")
Code in fileTeachers.py
Def getTeachers():
print("There are total 70 teachers")