0% found this document useful (0 votes)
2 views33 pages

Python Unit IV

The document covers key concepts in Python programming, including modular design, file handling, and data structures like dictionaries and sets. It explains the use of modules for code reuse, various file operations such as reading and writing data, and the characteristics of dictionaries. Additionally, it describes how to create, access, update, and delete dictionary entries.

Uploaded by

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

Python Unit IV

The document covers key concepts in Python programming, including modular design, file handling, and data structures like dictionaries and sets. It explains the use of modules for code reuse, various file operations such as reading and writing data, and the characteristics of dictionaries. Additionally, it describes how to create, access, update, and delete dictionary entries.

Uploaded by

Shaik Subhani
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ANNAMACHARYA UNIVERSITY

MCA-PYTHON

UNIT-IV

MODULAR DESIGN: Modules, Top-Down Design, Python Modules. TEXT FILES:


Using Text Files, String Processing, Exception Handling. DICTIONARIES AND
SETS: Dictionary Type in Python, Set Data Type.

MODULES

If we need to reuse the code in python then we can define functions , but if we
need to reuse number of functions then we have to go for modules concept. A
module is nothing but a file with extention of .py , which may contains methods ,
variables & also classes. In Python , Every python file itself is known as a
module . Modules of python .py files that concists of python code. Any python
file can be referenced as a [Link] order to use the properties of one module
into another module we use the "import" statement.

syntax : import required_moduleName

Modules are three types

1) Standard / predefined / built-in modules


2) User defined Modules.
3) 3rd party modules.
1) Predefined modules

These modules are already defined and kept in python software. So when we
install python then automatically these standard modules will install in our
[Link] example,math, calender, os , sys, json , datetime, ....

2) User defined Modules.

These modules are defined by users as per their requirement . So here User
defined module is nothing but the .py file which contains methods, variables, and
also [Link] example: [Link], [Link] , [Link](), [Link]

3) 3rd party modules.

These modules are already defined by some other people and kept in [Link]
we can download and install in our machines by using "pip" (Python Installer
Package ).PIP is a package management system used to install and manage
software packages written in python like pymysql , cx_oracle.In python, modules
are accessed by using "import" [Link] our current file needed to use
the code which is already existed in other files we can import that
file(modules)When python import a module called as "Mymodule" for example ,
the interpreter will first search for a built-in module called [Link] a built-in
module is not found , the python interpretor will then search for a file named
[Link] in a list of directories that it receives from the [Link]
[Link] can import modules in 3 diffrent ways ,
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

1) import <module_name>

import math

print([Link](2,4))

It is not recomended way in real time programs. Because when importing module
name directly then this module contains all members like functions,variables anc
[Link] if we want to use only one member of this module then remaining all
members are loading not good. here every time we need to use module name
when we want to use member of this module. to overcome this problem we can
use another way of importing.

2 ) from <module_name> import *

from math import *

print(pow(2,4)) # 16

here we can import all members of required module at a time. we can use these
members directly without module name.

3 ) from <module_name> import *

from math import pow

print(pow(2,4)) # 16

here we can directly importing required module name only what we want. we
can use this member directly.

Example:

[Link] file

x = 100
def f1():
print("in f1 of mod1")
def f2():
print("in f2 of mod1")
[Link] file

import [Link]
print(module1.x)
module1.f1()
module1.f2()
print("end")
output:

100

in f1 of mod1
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

in f2 of mod2

end

Note: Whenever we import one module into another module then imported
module file will be generated and stored that file into computer hard disc
[Link] generating the compiled file for python module with out
sharing the .py file of that module, we can import that module into other module.

Example:

[Link]

def add(a,b):
return a+b
def sub(a,b):
return a-b
def abs(a):
if a >= 0:
return a
else:
return (-a)
[Link]
import mod3
sum = [Link](30,20)
print(sum)
sub = [Link](30,20)
print(sub)
pr = [Link](-10)
print(pr)
output:

50
10
10
Renaming a module at the time of importing :

When ever we import a module , to access the properties of that module then
compulsary we have to use [Link] .If we rename a
module at the time of importing, we can access the propterties of that module by
using [Link]
For Example:
We can import the "math" module by using alias name , which is providing all
mathematicl properties
import math as m

print("the value of pi is " , [Link])

Output: the value of pi is 3.14159265359


from ... import … :
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Inorder to import the specific properties of one module into another module we
use
from <module_name> import <property_name>
Example:
[Link]
from math import pi,e
print("the value of pi is",pi)
print("the value of e is",e)
Output:
the value of pi is 3.14159265354
FILE HANDLING

In any programming languages, program memory allocation takes place in RAM


area atthe time of execution of program .RAM is a volatile, so that after
execution of the program the memory is going to [Link]
programming languages programs are good at processing the data but they can
notstore data in permanent mannerAfter processing the data , we have to store
the data in perminent [Link] the data is stored in permanent manner, we can
use the data whenever we [Link] can store the data in permanent manner by
using [Link] is a named location on disk , which is used to store the related data
inpermanent manner in the hard [Link] using a python programs, we can put
the data into a file , we can get the datafrom a file & we can modify the data of
the [Link] going to read or write or modify the data of the file, we have to
open the file.
 By using open() , we can open the file.
 At the time of opening the file, we have to specify the file modes.
 Mode of the file indicates what purpose we are going to open the file.

Syntax: file_object = open( '[Link]' , 'r' )

here open() method taking file_name as first parameter and required file_mode
assecond [Link] Properties of File Object:Once we opend a file and
we got file object, we can get various details related to that file by using its
properties.
name : Name of opened file
mode : Mode in which the file is opened
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

closed : Returns boolean value indicates that file is closed or not


readable(): Retruns boolean value indicates that whether file is readable or not
writable(): Returns boolean value indicates that whether file is writable or not.
f=open("[Link]",'w')
print("File Name: ",[Link])
print("File Mode: ",[Link])
print("Is File Readable: ",[Link]())
print("Is File Writable: ",[Link]())
print("Is File Closed : ",[Link])
[Link]()
print("Is File Closed : ",[Link])
OUTPUT:

File Name: [Link]


File Mode: w
Is File Readable: False
Is File Writable: True
Is File Closed : False
Is File Closed : True

MODES OF FILE

[Link]. Modes & Description


1 r
Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
2 r+
Opens a file for both reading and writing. The file pointer placed
at the beginning of the file.
3 w
Opens a file for writing only. Overwrites the file if the file exists. If
the file does not exist, creates a new file for writing.
4 w+
Opens a file for both writing and reading. Overwrites the existing
file if the file exists. If the file does not exist, creates a new file for
reading and writing.
5 a
Opens a file for appending. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the file
does not exist, it creates a new file for writing.
6 a+
Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing.
7 x
open for exclusive creation, failing if the file already exists

syntax : x = open( "fileName" , "modes of the file")


ANNAMACHARYA UNIVERSITY
MCA-PYTHON

 After executing the open function, it will create a file object with the
specified modes like x.
 BY calling the methods on the file object, we can read the data from the
file , we can write into file or update the data of a file.
 After performing the operations on the file object we have to close the file
object.
 By using close() we can close the file object .

READ DATA:

 To read the data from file object , in python we have read(), readline() and
readlines() methods.
 Using empty read() method we can read entire file object data from where
a file_pointer is available and it returns in the form of string type object.

Note: Create a file with name [Link] with some content

python is easy language


python is more powerfull language
python is dynamic
Q) Write a python program to read the data from the file?

file_object = open("[Link]" , "r" )


print ("file object is opened")
print(file_object)
data = file_object.read()
print(data)
read(count_number)
read() will take the ‘int’ value as input and It reads given integer number of
characters of the file and return as a string format.

file_object = open("[Link]")
print ("file is opened")
print(file_object)
data = file_object.read(10)
print(data)
readline():

 Python facilitates to read the file line by line by using a function readline()
method.
 The empty readline() method reads the current line of the file from the file
pointer location, i.e., if we use the readline() method two times, then we
can get the first two lines of the file.
 It is used to Read the entire single line of file where our file pointer is
available.
 Consider the following example which contains a function readline() that
reads the first line of our file "[Link]" containing three lines.

Q) Write a python program to read the first line data from the file ?
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

file_object = open("[Link]")
print ("file is opened")
print(file_object)
data = file_object.readline()
print(data)
readline(count_number)
 The readline(int) will reads the given specified number of charecters only
from the file pointer location but not upto end of the line.
 If given integer value is more than given file data length then readline(int)
will read the data which is available length in a file.

fileObject = open('[Link]', 'r')


data = [Link](2)
print(data) # 'py'
readlines()
 Is used to Read the entire all lines of file where our file pointer is available.
 It returns output as a list of items, where each line is a new string of list
format.

fileObject = open('[Link]', 'r')


data = [Link]() # ['line1' , 'line2' , 'line3']
print(data)
Output : [ 'python is easy language\n' , 'python is more powerfull language\n' ,
'python is
dynamic' ]
Writing Data to Text Files:
We can write character data to the text files by using the following 2 methods.
write(str)
writelines(list of lines)
f=open("[Link]",'w')
[Link]("Krishna\n")
[Link]("Software\n")
[Link]("Solutions\n")
print("Data written to the file successfully")
[Link]()
writelines():
f=open("[Link]",'w')
list=["sunny\n","bunny\n","vinny\n","chinny"]
[Link](list)
print("List of lines written to the file successfully")
[Link]()
The seek() and tell() Methods:
tell(): We can use tell() method to return current position of the cursor(file
pointer) from
beginning of the [Link] position(index) of first character in files is zero just like
string index.
f=open("[Link]","r")
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

print([Link]())
print([Link](2))
print([Link]())
print([Link](3))
print([Link]())
seek():
We can use seek() method to move cursor (file pointer) to specified location
[Link](offset, fromwhere) ------>offset represents the number of positions
data="All Students are GOOD"
f=open("[Link]","w")
[Link](data)
with open("[Link]","r+") as f:
text=[Link]()
print(text)
print("The Current Cursor Position: ",[Link]())
[Link](17)
print("The Current Cursor Position: ",[Link]())
[Link]("GEMS!!!")
[Link](0)
text=[Link]()
print("Data After Modification:")
print(text)

DICTIONARY-DATA TYPE
A Python dictionary is a data structure that allows us to easily write very efficient
codePython dictionaries allow us to associate a value to a unique key, and then
to quickly access this value. Dictionaries contains set of key/value pairs which
are enclosed between curly braces separated by comma. Here keys are unique.A
pair of curly braces creates an empty dictionary: { }The main operations on a
dictionary are storing a value with some key andextracting the value with given
[Link] keys are not allowed duplicates but dictionary values are
[Link] can use homogeneous and heterogeneous elements for
both keys [Link] order is not [Link] keys are only
immutable and values are mutable | [Link] will not allow indexing
and [Link] are indexed by keys, which can be any immutable types
likestrings and numbers can always be keys But Tuples can be used as keys if
they contain only strings, numbers, or tuples.

We can create dictionary in different ways, ----->> using {} , dict()


1. Creating empty dictionary and adding key : value pairs.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

dic1 = {}
print(dic1)
type(dic1)
dic1['a']=10
dic1['b']=20
dic1['c']=30
dic1['a']=10
dic1['a']=50
print(dic1)
2. Creating a dictionary with dict() function:
dic1=dict( [ ( 'a ', 10 ) , ( 'b' , 20 ) , ( 'c' , 30 ) , ( 'd' , 40 ) ] )
print(dic1)
type(dic1)
3. Creating a dictionary with "curly braces" including "key:value" pairs.
dic1={'a':10,'b':20,'c':30,'d':40}
print(dic1)
type(dic1)
Access Data from the Dictionary: We can access data by using keys.
d = {100:'krishna',200:'milky', 300:'Tillu'}
print(d[100])
print(d[300])
If the specified key is not available then we will get KeyError
Update Dictionaries
d[key] = value
If the key is not available then a new entry will be added to the dictionary with
the specified key-value pair if the key is already available then old value will be
replaced with new value.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
d[400]="veena"
print(d)
d[100]="sweety"
print(d)
Output
{100: 'krishna', 200: 'milky’, 300: 'Tillu'}
{100: 'krishna', 200: 'milky', 300: 'Tillu', 400: 'veena'}
{100: 'sweety', 200: 'milky', 300: 'Tillu', 400: 'veena'}
Delete Elements from Dictionary
del d[key]
 It deletes entry associated with the specified key.
 If the key is not available then we will get KeyError.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
del d[100]
print(d)
del d[400]
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Output
{100: 'krishna', 200: 'milky', 300: 'Tillu'}
{200: 'milky', 300: 'Tillu'}
KeyError: 400
2) [Link]()
To remove all entries from the dictionary.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
[Link]()
print(d)
Output
{100:"krishna",200:"milky",300:"Tillu"}
{}
del d
To delete total [Link] we cannot access d.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d)
del d
print(d)
Output
{100:"krishna",200:"milky",300:"Tillu"}
NameError: name 'd' is not defined
update():
 The update() method updates the dictionary with the elements from
another dictionary object or from an iterable of key/value pairs.
 The current dictionary will be updated with the all key:value pairs
fromanother dictionary.
stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle','Python']}
stuDetails1={'id':1000,'name':'nani'}
[Link](stuDetails1)
print(stuDetails)
{'Id': 100, 'Name': 'Sai', 'subjects': ['SQL Server', 'Oracle', 'Python'], 'id':
1000,'name': 'nani'}
Dictionary functions:
dict():
To create a dictionary
d = dict() =It creates empty dictionary
d = dict({100:"krishna",200:"ravi"}) =====>It creates dictionary with specified
elements
d = dict([(100,"krishna"),(200,"milky"),(300,"Tillu")]) It creates dictionary with
the given list of tuple elements
2) len()
Returns the number of items in the dictionary.
dict1 = {101: 'krishna', 102:'milky'};
dict2 = {1001: 'milky', 1002:'19' ,1003:'Tillu'};
print("Length of dict1",len(dict1))
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

print("Length of dict2",len(dict2))
output:
Length of dict1 2
Length of dict2 3
3) clear():
To remove all elements from the dictionary.
4) get():
To get the value associated with the key
[Link](key)
If the key is available then returns the corresponding value otherwise returns
None
5)[Link](key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns
default
value.
d={100:"krishna",200:"milky",300:"Tillu"}
print(d[100]) #krishna
print(d[400]) # KeyError:400
print([Link](100)) #krishna
print([Link](400)) #None
print([Link](100,"Guest")) #krishna
print([Link](400,"Guest")) #Guest
6) pop():
[Link](key)
It removes the entry associated with the specified key and returns the
corresponding value.
If the specified key is not available then we will get KeyError.
d={100:"krishna",200:"milky",300:"Tillu"}
print([Link](100))
print(d)
print([Link](400))
Output
krishna
{200: 'milky', 300: 'Tillu'}
KeyError: 400
7) popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
d={100:"durga",200:"milky",300:"Tillu"}
print(d)
print([Link]())
print(d)
Output
{100: 'durga', 200: 'milky', 300: 'Tillu'}
(300, 'Tillu')
{100: 'durga', 200: 'milky'}
If the dictionary is empty then we will get KeyError
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

d={}
print([Link]()) ==>KeyError: 'popitem(): dictionary is empty'
8) keys():
It returns all keys associated eith dictionary.
d={100:"durga",200:"milky",300:"Tillu"}
print([Link]())
for k in [Link]():
print(k)
Output
dict_keys([100, 200, 300])
100
200
300
9) values():
It returns all values associated with the dictionary.
d={100:"durga",200:"milky",300:"Tillu"}
print([Link]())
for v in [Link]():
print(v)
Output
dict_values(['durga', 'milky', 'Tillu'])
durga
milky
Tillu
10) items():
It returns list of tuples representing key-value pairs.
[(k,v),(k,v),(k,v)]
d={100:"durga",200:"milky",300:"Tillu”}
for k,v in [Link]():
print(k,"--",v)
Output
100 -- durga
200 -- milky
300 -- Tillu
Q)Merging two Dictionaries into a New Dictionary using ** symbol OR
Create a Python program to merging two dictionaries

Method-one: Using the | Operator


dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
print(dict_1 | dict_2)
OR
Using copy() and update()
dict_1 = {1: 'a', 2: 'b'}
dict_2 = {2: 'c', 4: 'd'}
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

dict_3 = dict_2.copy()
dict_3.update(dict_1)
print(dict_3)
OR
d1 = {1:10, 2:20}
d2 = {2:100, 3:30}
d3 = {**d1, **d2}
d3
{1: 10, 2: 100, 3: 30}
Explanation :
 This is generally considered a trick in Python where a single expression is
used to merge two dictionaries and stored in a third dictionary.
 The single expression is **. This does not affect the other two dictionaries.
 ** implies that an argument is a dictionary. Using ** [double star] is a
shortcut that allows you to pass multiple arguments to a function directly
using a dictionary.
 For more information refer **kwargs in Python. Using this we first pass all
the elements of the first dictionary into the third one and then pass the
second dictionary into the third. This will replace the duplicate keys of the
first dictionary.
Q)Discuss the following methods on dictionary i) index() ii) sorted() iii)
max()
A dictionary is a data structure that consists of key and value pairs. We can sort
a dictionary using two criterias
Sort by key : The dictionary is sorted in ascending order of its keys. The values
are not taken care of.
Sort by value : The dictionary is sorted in ascending order of the values.
Sort the dictionary by key
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2={}
for i in sorted(dic):
dic2[i]=dic[i]
print(dic2)
output: {1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
Sort dictionary by values
============================
dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2=dict(sorted([Link](),key= lambda x:x[1]))
print(dic2)
Output:
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
The index() method in Python dictionaries is used to find the index or position of
a specified key within the dictionary. index() in dictionaries is not a direct
method available.
Key-Value Pairs: A dictionary in Python consists of key-value pairs. Each key is
unique and associated with a value.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Accessing Values: You can access the value associated with a key using square
brackets [].
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict['b'])
The max() function in Python is used to find the maximum value among the keys
of a dictionary. It can also accept a key function similar to sorted() to find the
maximum based on values rather than keys.
my_dict = {'c': 3, 'a': 1, 'b': 2}
max_key = max(my_dict)
print(max_key) # Output: 'c'
Dictionary Comprehension:
Comprehension concept applicable for dictionaries also.
squares={x:x*x for x in range(1,6)}
print(squares)
doubles={x:2*x for x in range(1,6)}
print(doubles)
Output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10}
Q ) How to perform arithmetic operations on the values of a dictionary?
d1={'sub1':80,'sub2':90,'sub3':70,'sub4':80}
print(d1)
{'sub1': 80, 'sub2': 90, 'sub3': 70, 'sub4': 80}
s = sum([Link]())
print(s) 320
mx = max([Link]())
print(mx) 90
mn = min([Link]())
print(mn) 70
cnt = len([Link]())
print(cnt) 4

STRING HANDLING FUNCTIONS


 A group/sequence of characters is called String.
 Python supports str data type to represent string type data.
 String objects are immutable objects that mean we can’t modify the
existing string object.
 Insertion order is preserved in string objects.
 Every character in the string object is represented with unique index.
 Python supports both forward and backward indexes.
 Forward index starts with 0 and negative index starts with -1
 Python string supports both "concatenation" and "multiplication" of string
objects.
 Strings can be created by enclosing characters inside a single quote or
double quotes. Even triple quotes can be used in Python but generally
used to represent multiline strings and docstrings.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Quotations in Python:
 Python accepts single ('), double (") and triple (''' or """) quotes to denote
string literals, as long as the same type of quote starts and ends the
string.
 Generally triple quotes are used to write the string across multiple lines.
For example1 :
word = 'word'
sentence = "This is a sentence."
Paragraph = """This is a paragraph. It is
made up of multiple lines and sentences.""
Accessing Characters By using Index:
Python supports both +ve and -ve Index.

+ve Index means Left to Right (Forward Direction)


-ve Index means Right to Left (Backward Direction)
s="krishna"
print(s[3])
print(s[0])
print(s[-2])
print(s[10])
output:
s
k
n
IndexError: string index out of range
Q) Write a Program to Accept some String from the Keyboard and
display its
Characters by Index wise (both Positive and Negative Index)
s=input("Enter Some String:")
l=len(s)
i=0
for x in s:
print("The character present at positive index {} and at Negative index {} is
{}".format(i,i-l,x))
i=i+1
output:
Enter Some String:Krishna
The character present at positive index 0 and at Negative index -7 is K
The character present at positive index 1 and at Negative index -6 is r
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

The character present at positive index 2 and at Negative index -5 is i


The character present at positive index 3 and at Negative index -4 is s
The character present at positive index 4 and at Negative index -3 is h
The character present at positive index 5 and at Negative index -2 is n
The character present at positive index 6 and at Negative index -1 is a
Accessing Characters by using Slice Operator:
Syntax: s[beginindex:endindex:step value]
Begin Index: From where we have to consider slice (substring)
End Index: We have to terminate the slice (substring) at endindex-1
Step value: Incremented Value.

s="Learning Python is very very easy!!!"


print(s[1:7:1])
print(s[1:7])
print(s[1:7:2])
print(s[:7])
print(s[7:])
print(s[:])
print(s[::])
print(s[::-1])
Output:
earnin
earnin
eri
Learnin
g Python is very very easy!!!
Learning Python is very very easy!!!
Learning Python is very very easy!!!
!!!ysae yrev yrev si nohtyP gninraeL
Mathematical Operators for String:
We can apply the following mathematical operators for Strings.
1) + operator for concatenation
2) * operator for repetition
To use + operator for Strings, compulsory both arguments should be str type.
To use * operator for Strings, compulsory one argument should be str and other
argument should be int.
len() in-built Function:
We can use len() function to find the number of characters present in the string.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

s = 'krishna'
print(len(s))
Checking Membership:
We can check whether the character or string is the member of another string or
not by
using in and not in operators
s = input("Enter main string:")
subs = input("Enter sub string:")
if subs in s:
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
Comparison of Strings:
We can use comparison operators (<, <=, >, >=) and equality operators (==, !
=) for
strings. Comparison will be performed based on alphabetical order.
Example: develop a python program to find substring within a given string?
s1=input("Enter first string:")
2s2=input("Enter Second string:")
if s1==s2:
print("Both strings are equal")
elif s1<s2:
print("First String is less than Second String")
else:
print("First String is greater than Second String")
find():
syntax: [Link](substring)
Returns index of first occurrence of the given substring. If it is not available then
we will
get -1.
s="Learning Python is very easy"
print([Link]("Python")) #9
print([Link]("Java")) # -1
print([Link]("r"))#3
print([Link]("r"))#21
Note: By default find() method can search total string. We can also specify the
boundaries to search.
[Link](substring,bEgin,end)
It will always search from bEgin index to end-1 index.
s="durgaravipavanshiva"
print([Link]('a'))#4
print([Link]('a',7,15))#10
print([Link]('z',7,15))#-1
Counting substring in the given String:
We can find the number of occurrences of substring present in the given string
by using
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

count() method.
1) [Link](substring) : It will search through out the string.
2) [Link](substring, begin, end) : It will search from bEgin index to end-1
index.
s="abcabcabcabcadda"
print([Link]('a'))
print([Link]('ab'))
print([Link]('a',3,7))
Replacing a String with another String:
Syntax: [Link](oldstring, newstring)
inside s, every occurrence of old String will be replaced with new String.
s = "Learning Python is very difficult"
s1 = [Link]("difficult","easy")
print(s1)
Output: Learning Python is very easy
Splitting of Strings:
We can split the given string according to specified seperator by using split()
method.
l = [Link](seperator)
The default seperator is space. The return type of split() method is List.
s="krishna software solutions"
l=[Link]()
for x in l:
print(x)
Output:
krishna
software
solutions
Joining of Strings:
We can join a Group of Strings (List OR Tuple) wrt the given Seperator.
s = [Link](group of strings)
Eg 1:
t = ('sunny', 'bunny', 'chinny')
s = '-'.join(t)
print(s)
Output: sunny-bunny-chinny
Eg 2:
l = ['hyderabad', 'singapore', 'london', 'dubai']
s = ':'.join(l)
print(s)
Output: hyderabad:singapore:london:dubai
Changing Case of a String:
We can change case of a string by using the following 4 methods.
1) upper() :To convert all characters to upper case
2) lower() :To convert all characters to lower case
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

3) swapcase() :Converts all lower case characters to upper case and all upper
case
characters to lower case
4) title() : To convert all character to title case. i.e first character in every word
should
be upper case and all remaining characters should be in lower case.
5) capitalize() :Only first character will be converted to upper case and all
remaining
characters can be converted to lower case
s = 'learning Python is very Easy'
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]())
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
Checking Starting and Ending Part of the String:
Python contains the following methods for this purpose
1) [Link](substring)
2) [Link](substring)
s = 'learning Python is very easy'
print([Link]('learning'))
print([Link]('learning'))
print([Link]('easy'))
To Check Type of Characters Present in a String:
Python contains the following methods for this purpose.
1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0
to9 )
2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to
Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces
s=input("Enter any character:")
if [Link]():
print("Alpha Numeric Character")
if [Link]():
print("Alphabet character")
if [Link]():
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

print("Lower case alphabet character")


else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif [Link]():
print("It is space character")
else:
print("Non Space Special Character")
Q) Write a Program to Reverse the given String
Input: python
Output: nohtyp
1st Way:
s = input("Enter Some String:")
print(s[::-1])
2nd Way:
s = input("Enter Some String:")
print(''.join(reversed(s)))
3rd Way:
s = input("Enter Some String:")
i=len(s)-1
target=''
while i>=0:
target=target+s[i]
i=i-1
print(target)
Write a Program to Print Characters at Odd Position and Even Position
for the given String?
1st Way:
s = input("Enter Some String:")
print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])
2nd Way:
s=input("Enter Some String:")
i=0
print("Characters at Even Position:")
while i< len(s):
print(s[i],end=',')
i=i+2
print()
print("Characters at Odd Position:")
i=1
while i< len(s):
print(s[i],end=',')
i=i+2
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

SET- DATA Type:


 A set is unordered collection of unique elements.
 Set is commonly used in membership testing, removing duplicates from a
sequence, and computing mathematical operations such as intersection,
union, difference, and symmetric difference.
 Set will not allow duplicate values.
 Insertion order is not preserved but elements can be sorted
 The major advantage of using a set is as opposed to a list, is that it has a
highly optimized method for checking whether a specific element is
contained in the set.
 Sets do not support indexing, slicing,
 Sets do not support concatenation and multiplication.
 There are currently two built-in set types,
Set:
 The set type is mutable means the contents of set can be changed using
methods like add(), update() and remove(), discard(), pop() , clear().
 Since it is mutable, it has no hash value and cannot be used as either a
dictionary key or as an element of another set.
Frozenset:
 The frozen sets are the immutable form of the normal sets, i.e., the items
of the frozen set cannot be changed and therefore it can be used as a key
in the dictionary.
 The elements of the frozen set cannot be changed after the creation. We
cannot change or append the content of the frozen sets by using the
methods like add() or remove().
 The frozenset() method is used to create the frozenset object. The iterable
sequence is passed into this method which is converted into the frozen set
as a return type of the method.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\n printing the content of frozen set...")
for i in Frozenset:
print(i);
[Link](6)
We can create a set in different ways,
1. Creating an empty set using set() and add elements to that empty
set.
Example:
set1 = set()
[Link](10)
[Link](20)
[Link](30)
[Link](10)
print(set1)
2. Creating a set with elements using set().
set2=set([1,2,4,'a',2+4j,True])
print(set2) {1, 2, 4, (2+4j), 'a'}
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

type(set2) <class 'set'>


[Link] a set with curly braces ----->> { }
set3={1,2,3,4,"krishna",True}
print(set3) {1, 2, 3, 4, 'krishna'}
type(set3) <class 'set'>
Set Functions:
Adding items to the set:
Python provides the add() method and update() method which can be used to
add some particular item to the set. The add() method is used to add a single
element whereas the update() method is used to add multiple elements to the
set.
add():
This method is used to add new elements in to existing set.
set1 = {1,2,3,4,5}
print(set1)
[Link](6)
[Link](7)
print(set1)
update():
 To add more than one item in the set, Python provides the update()
method. It accepts iterable object as an argument.
s1 = set()
[Link]([10,20,30,40])
s1
{40, 10, 20, 30}
[Link]((50,60))
s1
Removing items from the set:
remove(element): It will remove elements from the set, if that element is not
found then it will throw error like KeyError
se1={1,2,3,4,5}
print(se1)
type(se1)
[Link](5)
[Link](4)
[Link](15)
Error: KeyError: 15
discard():
 It will remove elements from the set, if that element is not found in the set
then it will do nothing. means it will not return any exception here.
se1={1,2,3,4,5}
print(se1)
[Link](7)
[Link](20)
[Link](5)
print(se1)
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

pop():
We can also use the pop() method to remove the item. Generally, the pop()
method will always remove the last item but the set is unordered, we can't
determine which element will be popped out from set.
s1 = {90,40, 10, 20, 30}
[Link]()
40
[Link]()
10
Assignment operator
By using assignment operator, if we assigning given set object in to another
object then both can share the same memory address.
set1 = {1, 2, 3, 4, 5}
set2 = set1
set1
{1, 2, 3, 4, 5}
set2
{1, 2, 3, 4, 5}
id(set1)
2693878076136
id(set3)
2693878076136
copy():
This function copies the elements of one set to another new set and also it
creates new memory value.
copy() method always creates new memory for new set object. so both
memories are different but values are same.
set1={1,2,3,4,5}
set2=[Link]() #copying se1 elements to se2
set1 {1, 2, 3, 4, 5}
set2 {1, 2, 3, 4, 5} # id values different.
id(set1)
2693878076136
id(set2)
2693878076360
clear():
By using clear() function we can clear or remove all elements from the given set
object.
se1={1,2,3,4,5}
print(se1) {1, 2, 3, 4, 5}
type(se1) <class 'set'>
[Link]() #clearing the se1, so se1 will become empty set.
print(se1) set()
Python Set Operations:
Set can be performed mathematical operation such as union, intersection,
difference, and symmetric difference. Python provides the facility to carry out
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

these operations with operators or methods. We describe these operations as


follows.
isdisjoint():
This function returns True if both are "empty sets" or if both sets "contains
non-matching" [Link] atleast one elemet matching also returns False value.
se1 = set()
se2 = set()
[Link](se2) True
se1=set(5)
se2={1,2,3}
[Link](se2) True
se1={1,2,3}
se2={1,2,3,4}
[Link](se2) False
issubset():
 [Link](y) returns True, if x is a subset of y.
 " <= " is an abbreviation for "Subset of".
se1={1,2,3,4,5}
se2={1,2,3}
[Link](se1) True
[Link](se2) False
Or
se2 <= se1 True
se1 <= se2 False
issuperset()
 [Link](y) returns True, if x is a superset of y.
 " >= " is an abbreviation for "issuperset of"
se1={1,2,3,4,5}
se2={1,2,3}
[Link](se1) False
[Link](se2) True
se2 >= se1 False
se1 >= se2 True
Membership:
 We can also check the elements whether they belong to set or not,
se1={1,2,3,"Python",3+5j,8}
4 in se1 False
1 in se1 True
"Python" in se1 True
10 not in se1 True
"krishna" not in se1 True
union():
It returns the union of two sets, that means it returns all the values from both
sets except duplicate values. The same result we can get by using ‘|’ between
two sets
Syntax: <First_Set>.union(<Second_Set>) or<First_Set> | <Second_Set>
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {1, 2, 3, 4, 5, 6, 7} or
se1|se2 {1, 2, 3, 4, 5, 6, 7}
Or
[Link](se1) {1, 2, 3, 4, 5, 6, 7}
se2|se1 {1, 2, 3, 4, 5, 6, 7}
intersection():
It returns an intersection elements of two sets, that means it returns only
common elements from both [Link] same operation we can get by sing ‘&’
operator.
Syntax: <First_Set>.intersection(<Second_Set>) or <First_Set> &
<Second_Set>
se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {1, 2, 3} or
se1&se2 {1, 2, 3}
Or
[Link](se1) {1, 2, 3}
se2&se1 {1, 2, 3}
diffferenece():
It returns all elements from first set which are not there in the second set.
Syntax: <First_set>.difference(<Secnd_Set>) or <First_Set> -
<Second_Set>
se1={1,2,3,4,5}
se2={1,2,3,6,7}
[Link](se2) {4, 5} or
se1-se2 {4, 5}
Or
[Link](se1) {6, 7} or
se2-se1 {6, 7}
intersection_update():
 The intersection_update() method removes the items from the original set
that are not present in both the sets (all the sets if more than one are
specified).
 The intersection_update() method is different from the intersection()
method since it modifies the original set by removing the unwanted items,
on the other hand, the intersection() method returns a new set.
Syntax: <First_Set>.intersection_update(<Second_Set>)
se1={1,2,3,4,5}
se2={1,2,3,6,7}
se1.intersection_update(se2)
print(se1) {1, 2, 3}
print(se2) {1, 2, 3, 6, 7}
differenece_update():
The result of difference between two sets will in First_Set.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Syntax: <First_Set>.difference_update(<Second_Set>)
se1={1,2,3,4,5}
se2={1,2,3,6,7}
se1.difference_update(se2)
print(se1)
print(se2)

Q) Give a comparison between lists, tuples, dictionaries and sets


List Tuple Dictionary
List contains Tuple contains Whereas a dictionary contains
heterogeneous elements heterogeneous elements key-value pairs.
A List is represented by []. A Tuple is represented by A Dictionary is represented by
(). {}.
Lists in Python are These are immutable. These are mutable.
mutable.
Lists are ordered. Tuples are unordered. Dictionaries are ordered.

 The list and tuple can be created by using the elements without any
defining the key whereas the dictionary uses the key and value pairs.
 If we want to create a group of elements with some key name, then we
can go for dictionary as it accepts key and value.
 When we want to list out few elements and want to make changes later as
per our requirement we can go for list.
 When we want to combine few elements into group and don’t want to
apply any changes further then we can go for tuple. Let’s see the
combined example of the list, tuple and the dictionary.

Exception Handling
Exception definition :An exception is an event, which occurs during the
excution of a program,that disrupts the normal flow of the program instructions
We can handle the exceptions at runtime. But we cannot handle
[Link] are related to application, where as errors are related to
environment in which the application is [Link] error is a term which is used
to describe any issue that arisesunexpectedly that cause a computer do not
functioning properly.
Debugging: The process of finding and eliminating the errors is called
Debugging. In Python We have 2 types of Errors:
1 ) SyntaxError
2 ) RuntimeError
1 Syntax error :
The errors which occurs because of "invalid syntax" are known as "Syntax
errors". Interpreter will check for syntax errors when ever we run the python
program
 If syntax error is found , Then no byte code is generating.
 With out byte code, program excution is not possible.
 Developers only responsible to solve these errors.
def m1():
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

print('Hi')
Example1:
def m1():
print('Hi')
Output : SyntaxError : Expected an indented block

2) RUNTIME ERRORS :
 The errors which occurs at the time of excution of a program are known as
runtime errors.
 We get Runtime Errors because of programing logic, invalid input,memory
related issues etc...
 For every RuntimeError , Python is providing corresponding exception
class is available.
Example1: KeyError , IndexError, ValueError, NameError etc ....
 At the time of execution of a program if any Runtime Error is occur then
internally corresponding Runtime Error representation classes object will
be created
What is Exception
An unwanted and unexpected event that disturbs normal flow of program is
called exception.
Eg:
 ZeroDivisionError
 TypeError
 ValueError
 FileNotFoundError
 EOFError
It is highly recommended to handle exceptions. The main objective of exception
handling
is Graceful Termination of the program (i.e we should not block our resources
and we should not miss anything). Exception handling does not mean repairing
exception. We have to define alternative way to continue rest of the program
normally
Default Exception Handing in Python:
 Every exception in Python is an object. For every exception type the
corresponding classes are available.
 Whevever an exception occurs PVM will create the corresponding
exception object and will check for handling code. If handling code is not
available then Python interpreter terminates the program abnormally and
prints corresponding exception information to the console.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

 The rest of the program won't be executed


print("Hello")
print(10/0)
print("Hi")
D:\Python_classes>py [Link]
Hello
Traceback (most recent call last):
File "[Link]", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Customized Exception Handling by using try-except:
It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to take
risky code
inside try block. The corresponding handling code we have to take inside except
block.

Without try-except:
print("stmt-1")
print(10/0)
print("stmt-3")
Output
stmt-1
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
With try-except:
print("stmt-1")
try:
print(10/0)
except ZeroDivisionError:
print(10/2)
print("stmt-3")
Output
stmt-1
5.0
stmt-3
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Normal termination/Graceful Termination


Control Flow in try-except:
try:
stmt-1
stmt-2
stmt-3
except xxxxxxx:
stmt-4
stmt-5
Case-1: If there is no exception
1,2,3,5 and Normal Termination
Case-2: If an exception raised at stmt-2 and corresponding except block
matched
1,4,5 Normal Termination
Case-3: If an exception rose at stmt-2 and corresponding except block not
matched
1, Abnormal Termination
Case-4: If an exception rose at stmt-4 or at stmt-5 then it is always abnormal
termination.
How to Print Exception Information:
try:
print(10/0)
except ZeroDivisionError as msg:
print("exception raised and its description is:",msg)
Output exception raised and its description is: division by zero
try with Multiple except Blocks:
The way of handling exception is varied from exception to [Link] for
every exception type a seperate except block we have to provide. i.e try with
multiple except blocks is possible and recommended to use.
Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative arithmetic operation
except FileNotFoundError:
use local file instead of remote file
If try with multiple except blocks available then based on raised exception the
corresponding except block will be executed.
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except ZeroDivisionError :
print("Can't Divide with Zero")
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

except ValueError:
print("please provide int value only")
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 2
5.0
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: ten
please provide int value only
If try with multiple except blocks available then the order of these except blocks
is important .Python interpreter will always consider from top to bottom until
matched except block identified.
Single except Block that can handle Multiple Exceptions:
We can write a single except block that can handle multiple different types of
exceptions.
except (Exception1,Exception2,exception3,..): OR
except (Exception1,Exception2,exception3,..) as msg :
Parentheses are mandatory and this group of exceptions internally considered as
tuple.
try:
x=int(input("Enter First Number: "))
y=int(input("Enter Second Number: "))
print(x/y)
except (ZeroDivisionError,ValueError) as msg:
print("Plz Provide valid numbers only and problem is: ",msg)
D:\Python_classes>py [Link]
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
finally Block:
☕ It is not recommended to maintain clean up code(Resource Deallocating Code
or Resource Releasing code) inside try block because there is no guarentee for
the execution of every statement inside try block always.
☕ It is not recommended to maintain clean up code inside except block, because
if there
is no exception then except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be
executed always irrespective of whether exception raised or not raised and
whether exception handled or not handled. Such type of best place is nothing
but finally block.
☕ Hence the main purpose of finally block is to maintain clean up code
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

Syntax:
try:
Risky Code
except:
Handling Code
finally:
Cleanup code
The speciality of finally block is it will be executed always whether exception
raised or not
raised and whether exception handled or not handled.
Case-1: If there is no exception
try:
print("try")
except:
print("except")
finally:
print("finally")
Output
try
finally
Case-2: If there is an exception raised but handled
try:
print("try")
print(10/0)
except ZeroDivisionError:
print("except")
finally:
print("finally")
Output
try
except
finally
Types of Exceptions:

In Python there are 2 types of exceptions are possible.


1) Predefined Exceptions
2) User Definded Exceptions
1)Predefined Exceptions:

 Also known as inbuilt exceptions.


 The exceptions which are raised automatically by Python virtual machine
whenver a

particular event occurs are called pre defined exceptions.

Eg 1: Whenever we are trying to perform Division by zero, automatically Python


will raise ZeroDivisionError.
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

print(10/0)

2)User Defined Exceptions:

 Also known as Customized Exceptions or Programatic Exceptions


 Some time we have to define and raise exceptions explicitly to indicate
that something goes wrong, such type of exceptions are called User
Defined Exceptions or Customized Exceptions
 Programmer is responsible to define these exceptions and Python not
having any idea about these. Hence we have to raise explicitly based on
our requirement by using "raise" keyword.

Eg:

 InSufficientFundsException
 InvalidInputException
 TooYoungException
 TooOldException

PROGRAMS:

1. Write a Python code to search a string in the given list

l = [1, 2.0, 'milky','Tillu','krishna','Ridwa']


s = input("ener a string:")
if s in l:
print(f'{s} is present in the list')
else:
print(f'{s} is not present in the list')
2. Develop a python program to access the elements of a Nested
dictionary
In Python, a nested dictionary is a dictionary inside a dictionary. It's a
collection of dictionaries into one single dictionary.
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2'}}
Create a Nested Dictionary
people = {1: {'name': 'Tillu', 'age': '22', 'sex': 'Male'},
2: {'name': 'Milky', 'age': '22', 'sex': 'Female'}}
print(people)
Access elements of a Nested Dictionary
To access element of a nested dictionary, we use indexing [] syntax in
Python.
people = {1: {'name': 'Tillu', 'age': '22', 'sex': 'Male'},
2: {'name': 'Milky', 'age': '22', 'sex': 'Female'}}
print(people[1]['name'])
print(people[1]['age'])
print(people[1]['sex'])
3. Explain the process of how to delete dictionary from multiple
dictionaries
ANNAMACHARYA UNIVERSITY
MCA-PYTHON

mylist = [{"id" : 1, "data" : "HappY"},


{"id" : 2, "data" : "BirthDaY"},
{"id" : 3, "data" : "Tillu"}]
print("The original list is: " + str(mylist))
index = None
for i, d in enumerate(mylist):
if d['id'] == 2:
index = i
break
if index is not None:
[Link](index)
print("List after deletion of dictionary: " + str(mylist))
sample output:
The original list is: [{'id': 1, 'data': 'HappY'}, {'id': 2, 'data': 'BirthDaY'},
{'id': 3, 'data': 'Tillu'}]
List after deletion of dictionary: [{'id': 1, 'data': 'HappY'}, {'id': 3, 'data':
'Tillu'}]

How to convert list to a dictionary

pets= ['dog','cat','guinea pig', 'parrot']


# add one value to all
pets_owner = {animal:'Junnu' for animal in pets}
print(pets_owner)
sample output:
{'dog': 'Junnu', 'cat': 'Junnu', 'guinea pig': 'Junnu', 'parrot': 'Junnu'}
What is a Nested Dictionary? How is it created?
A dictionary inside the dictionary is known as a “Nested Dictionary”. For ex
dictionary1 = {
1 : {'roll': '101', 'name': 'sam'},
2 : {'roll': '102', 'name': 'ram'}
}
print(dictionary1)
Output: {1: {'roll': '101', 'name': 'sam'}, 2: {'roll': '102', 'name': 'ram'}}
The elements of nested dictionary can be accessed using
print(dictionary[1]['roll'])
Output: 101
Create a list of tuples from the dictionary
The list of tuples can be created in following way:
dict1 = { 1: 'a', 2: 'b', 3: 'c' }
lst1 = list([Link]())
print(lst1)
Output: [(1, 'a'), (2, 'b'), (3, 'c')]

You might also like