Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Lab(19) (1)

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 342

VISION

To evolve as a centre of excellence for nurturing computer professionals with research and
innovation skills, inculcating moral values and societal concerns.

MISSION
M1: To transform students into creative computer engineers to meet global challenges.
M2: To produce competent and quality professionals by imparting computer concepts and
techniques and a zest for research and higher studies.
M3: To build entrepreneur skills and leadership qualities in the students by inculcating the
spirit of ethical values.

Program Educational Objectives


PEO 1: To excel in their career as competent software engineer in IT and allied
organizations with enriched curriculum and pedagogical initiatives.
PEO 2: To pursue higher education and to demonstrate research temper for providing
solutions to engineering problems
PEO 3: To contribute for the societal development and engage in lifelong learning by
exhibiting leadership, through professional, social and ethical values.

Program Specific Outcomes


PSO1: Apply principles and practices of computer science and Engineering to design
computational solutions.
PSO2: Develop solutions in the area of database management, software design and computing
systems using machine intelligence
IIB.Tech.I-Sem(CSE) P C
3 1.5
PYTHONPROGRAMMINGLAB(A0594193)
(CommontoallBranches)
COURSEOBJECTIVES:
 TobeabletointroducecoreprogrammingbasicsandvariousOperatorsofPython
programming language.
 TodemonstrateaboutPythondatastructureslikeLists,Tuples,Setsanddictionaries
 TounderstandaboutFunctions,ModulesandRegularExpressionsinPythonProgramming.
COURSEOUTCOMES:
 Studentshouldbeabletounderstandthebasicconceptsofscriptingandthe contributions of
scripting language.
 AbilitytoexplorepythondatastructureslikeLists,Tuples,Setsanddictionaries.
 AbilitytocreatepracticalandcontemporaryapplicationsusingFunctions,Modules and
Regular Expressions.
MAPPINGOFCOs&POs
PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
CO/PO 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 1 2 1 1 1 1
CO2 3 3 2 1 1 1 1
CO3 3 1 2 1 1 1 1

S.NO NameoftheExperiment Remarks

1 a)DemonstrateaboutBasicsofPythonProgramming.

b)DemonstrateaboutfundamentalDatatypesinPython
Programming.(i.e.,int,float,complex,boolandstring types)

c) DemonstratetheworkingoffollowingfunctionsinPython.
i) id() ii)type() iii)range()

d)WriteaPythonprogramtodemonstratevariousbase
conversionfunctions.
e)WriteaPythonprogramtodemonstratevarioustype
conversionfunctions.
2 a) DemonstratethefollowingOperatorsinPythonwith suitable
examples.
i) ArithmeticOperators ii)RelationalOperators
iii)AssignmentOperator iv)Logical Operators
v)BitwiseOperators vi)TernaryOperator
vii)MembershipOperatorsviii)IdentityOperators

3 a) WritePythonprogramstodemonstratethefollowing:
i) input() ii)print()
iii)‘sep’attribute iv)‘end’attribute
v)replacementOperator({})

b) DemonstratethefollowingConditionalstatementsin Python
with suitable examples.
i) ifstatement ii)ifelsestatement
iii)if–elif–elsestatement
c) Demonstrate the following Iterative statements in Python
with suitable examples.
i)whileloop ii)forloop

d) Demonstrate the following control transfer statements in


Python with suitable examples.
i)break ii) continue iii)pass

4 WritePythonprogramstoprintthefollowingPatterns:
i)

ii)

iii)
iv)

v)

vi)

vii)
viii)

5 a) Write a Python program to demonstrate various ways of


accessing the string.
i) ByusingIndexing(BothPositiveandNegative)
ii) ByusingSliceOperator
b) Demonstratethefollowingfunctions/methodswhich
operates on strings in Python with suitable examples:
i) len() ii)strip() iii)rstrip() iv)lstrip()
v)find() vi)rfind() vii)index() viii)rindex()

ix)count() x)replace() xi)split() xii)join()


xiii)upper() xiv)lower() xv)swapcase()xvi)title()
xvii)capitalize() xviii)startswith() xix)endswith()
6 a)Pythonprogramtoperformreadandwriteoperationson
afile.
b)Pythonprogramtocopythecontentsofafiletoanother
file.
c)Pythonprogramtocountfrequencyofcharactersinagiven file.

d)Pythonprogramtoprinteachlineofafileinreverse
order.
e)Pythonprogramtocomputethenumberofcharacters,
wordsandlinesinafile.
7 a)Demonstratethedifferentwaysofcreatinglistobjects
withsuitableexampleprograms.
b) Demonstratethefollowingfunctions/methodswhich
operates on lists in Python with suitable examples:
i) list() ii)len() iii)count()iv)index()
v)append()vi)insert() vii)extend()viii)remove()
ix)pop() x)reverse()xi)sort() xii)copy()
xiii)clear()
c) Demonstrate the following with suitable example
programs:
i)Listslicing ii)ListComprehensions
8 a)Demonstratethedifferentwaysofcreatingtupleobjects
withsuitableexampleprograms.
b) Demonstratethefollowingfunctions/methodswhich
operates on tuples in Python with suitable examples:
i) len() ii)count() iii)index() iv)sorted()
v)min()vi)max() vii)cmp() viii)reversed()
9 a)Demonstratethedifferentwaysofcreatingsetobjects
withsuitableexampleprograms.
b) Demonstratethefollowingfunctions/methodswhich
operates on sets in Python with suitable examples:
i) add() ii)update() iii)copy() iv)pop()
v)remove()vi)discard() vii)clear() viii)union()
ix)intersection() x)difference()

10 a)Demonstratethedifferentwaysofcreatingdictionaryobjects
with suitable example programs.
b) Demonstratethefollowingfunctions/methodswhich
operates on dictionary in Python with suitable examples:
i) dict() ii)len() iii)clear() iv)get()
v)pop()vi)popitem() vii)keys() viii)values()
ix)items() x)copy() xi)update()

11 a)DemonstratethefollowingkindsofParametersused while
writing functions in Python.
i) Positional Parameters ii) Default Parameters
iii)Keyword Parameters iv) Variable length
Parameters
b)WriteaPythonprogramtoreturnmultiplevaluesata
timeusingareturnstatement.
c)WriteaPythonprogramtodemonstrateLocalandGlobal
variables.
d)DemonstratelambdafunctionsinPythonwithsuitable example
programs.
12 ImplementthefollowingSearchingandSortingtechniques

inPythonbyusingfunctions.
i)LinearSearch ii)BinarySearch
iii)SelectionSort iv)BubbleSort
v)Insertion vi)MergeSort
viii)QuickSort
13 a)Demonstratethefollowingin-
builtfunctionstouseRegularExpressionsveryeasilyinourapplicat
ions.
i)compile() ii)finditer() iii)match() iv)fullmatch()
v)search() vi)findall() vii)sub() viii)subn()
ix)split()
b) WriteaRegularExpressiontorepresentallRGMlanguage
(Your own language) identifiers.
Rules:
1. Theallowedcharactersarea-z,A-Z,0-9,#.
2. Thefirstcharactershouldbealowercasealphabet symbol
from a to k.
3. Thesecondcharactershouldbeadigitdivisibleby3.
4. Thelengthofidentifiershouldbeatleast2.

Writeapythonprogramtocheckwhetherthegivenstring is RGM
language identifier or not?
c) WriteaRegularExpressiontorepresentall10digit mobile
numbers.
Rules:
1. Everynumber shouldcontains exactly10digits.
2. Thefirstdigitshouldbe7or8or9

WriteaPythonProgramtocheckwhetherthegiven number is
valid mobile number or not?
TEXTBOOKS
1. LearningPython,MarkLutz,Orielly,3Edition2007.
2. PythonProgramming:AModernApproach,VamsiKurama,Pearson,2017.
REFERENCEBOOKS
1) ThinkPython,2Edition,2017AllenDowney,GreenTeaPress
2) CorePythonProgramming,2016W.Chun,Pearson.
3) Introductionto Python,2015Kenneth A. Lambert, Cengages
4) https://www.w3schools.com/python/python_reference.asp
5) https://www.python.org/doc/
Dept. of
CSE,RGMCET(Autonomous)

Preface

ThismanualwillintroduceyoutothePythonprogramminglanguage.It’saimedatbeginningprogram
mers, but even if you’ve written programs before and just want to add Python to your list of
languages, It will get you started.

Python is a powerful high-level, object-oriented programming language created by Guido van


Rossum. It has simpleeasy-to-
usesyntax,makingittheperfectlanguageforsomeonetryingtolearncomputerprogramming for the
first time.

ThispracticalmanualwillbehelpfulforstudentsofallEngineeringstreamsforbetterunderstandingth
e course from the point of view of applied aspects.

Thoughalltheeffortshavebeenmadetomakethismanualerrorfree,yetsomeerrorsmighthavecreptin
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.
Dept. of CSE, RGMCET(Autonomous),
Nandyal

DO’S AND DONT’S

Do’s
1. Conform to the academic discipline of the department.
2. Enteryour credentials in the laboratory attendance register.
3. Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out the
experiments.
5. Shutdown the machine once you are done using it.

Dont's
1. Eatables are not allowed in the laboratory.
2. Usage of mobile phones is strictly prohibited.
3. Do not open the system unit casing.
4. Do not remove anything from the computer laboratory without permission.
5. Donottouch,connectordisconnectanyplugorcablewithoutyourfaculty/
laboratorytechnician’s permission.
Dept. of CSE,
RGMCET(Autonomous)

Python Programming Lab Manual

COURSE DESCRIPTION

ThismanualisintendedfortheSecondyearstudentsinthesubjectofProgrammingwithPython
.This
manualtypicallycontainspractical/LabSessionsrelatedtoProgrammingwithPythoncover
ingvarious aspects in order to enhance subject understanding.

Pythonisageneralpurpose,high-levelprogramminglanguage;otherhigh-levellanguagesyoumighthave
heard of C++, PHP, and Java. Virtually all modern programming languages make us of an
Integrated Development Environment (IDE), which allows the creation, editing, testing, and
saving of programs and modules.

Manymodernlanguagesusebothprocesses.Theyarefirstcompiledintoalowerlevellanguage,calledbyt
e code, and then interpreted by a program called a virtual machine. Python uses both
processes, but because of the way programmers interact with it, it is usually considered an
interpreted language.

There are two ways to use the Python interpreter: shell mode and script mode. In shell mode,
you type
PythonstatementsintothePythonshellandtheinterpreterimmediatelyprintstheresult.Inscriptmod
e,you type statements into the editor and save it in a file known as script.The interpreter
executes the code of the script.

Students are advised to thoroughly go through this manual rather than only topic mentioned in
the syllabus
aspracticalaspectsarethekeytounderstandingandconceptualvisualizationoftheoreticalaspectsc
overed in the books.

Also,thiscourseisdesignedtoreviewtheconceptsofSearchingandSortingtechniques,studiedinprevious
semester. Good Luck for your Enjoyable Laboratory Sessions.

SCOPE &OBJECTIVES
1. Learn basic programming constructs –data types, decision structures, control structures in
python
2. Know how to use libraries for string manipulation and user-defined functions.
3. Learntouse in-builtdata structuresin python–Lists, Tuples,Dictionary andFile handling.
4. Know how to use functions and modules in Python to solve various problems
5. Learn about Regular Expressions and work on some examples using Regular Expressions.
Dept. of CSE,
RGMCET(Autonomous)

INTRODUCTIONTOPYTHONPROGRAMMING

Pythonisahigh-level,general-purpose,interpreted,interactiveandobject-orientedprogramming
language. It was created by Guido van Rossum during 1985- 1990.
Like Perl, Python source code is also available under the GNU General Public License (GPL).

i. Why the name python?

GuidovanRossumwasinterestedonwatchingacomedyshow,whichistelecastingontheBBCchann
el from 1969 to 1974 The complete Monty Python's FlyingCircus.

GuidoVanRossumthoughtheneededanamethatwasshort,unique,andslightlymysteriousforhis
programming language,so he decided to call the language Python.

ii. Applications of Python Programming

Web Development

GameDevelopment
Scientific and Numeric applications
ArtificialIntelligenceandMachineLearningbasedapplications
Data Science related applications
DesktopGUIapplications
Software
Development
Enterprise-level/Business Applications
Educationprogramsandtrainingcourses
Web Scraping Applications
ImageProcessingandGraphicDesignApplications
Data Analysis
iii. Features of Python programming

Simple and Easy to


Learn
FreewareandOpenSourc
e Dynamically typed

ObjectOrientedProgrammingandProcedureOrientedProgra
mming Extensive Library

Embedded
Extensible

Interpreted

Portability
Platform Independent
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 1 :

a) Demonstrate about Basics of Python Programming.

i. Running Python Interpreter:

Python comes with an interactive interpreter.


When you type pythonin your shell or command prompt, the python interpreter becomes
active with a
>>>(REPL) and waits for your commands.

Now you can type any valid python expression at the


prompt.Pythonreadsthetypedexpression,evaluatesitandprint
stheresu lt.

ii. Running Python Scripts in IDLE (Integrated Development and Learning Environment):

IDLEis the standard Python development environment.

It'snameisanacronymof"IntegratedDeveLopmentEnvironment".
It works well on both Unix and Windows platforms.

IthasaPythonshellwindow,whichgivesyouaccesstothePythoninteractivemod
e. It also has a file editor that lets you create and edit existing Python
source files.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Goto File menu click on New File (CTRL+N) and write the code and save add.py

a=input("Enteravalue

")

b=input("Enterbvalue

") c=a+b

print "The sum is",c

Thenrun the program by pressing F5 orRun ==> Run Module.

iii. Running Python scripts in Command Prompt:

Before going to run python27 folder in the command


prompt.
Openyourtexteditor,typethefollowingtextandsaveitash
print "hello"

Inthe command prompt, and run this program by calling python hello.py.
Make sure you change to the directory where you saved the file before doing it.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/17
02/06/20 Python Programming Lab Manual -
21 Writea Pythonprogram to purposefullyraise Indentation Errorand correct it.
RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Indentation:

Code blocks are identified by indentation rather than using symbols like curly braces.

Indentationclearlyidentifieswhichblockofcodeastatementbelongsto.Ofcourse,codeblocksc
an consist of single statements, too.
When one is new to Python, indentation may come as a surprise. Humans generally prefer to
avoid
change,soperhapsaftermanyyearsofcodingwithbracedelimitation,thefirstimpressionofusingpure
indentation may not be completely positive.
However, recall that two of Python's features are that it is simplistic in nature and easy to
read.
Pythondoesnotsupportbracestoindicateblocksofcodeforclassandfunctiondefinitionsorflow
control.
Blocks of code are denoted by line indentation.
Allthecontinuouslinesindentedwithsamenumberofspaceswouldformablock.Pythonstrictly follow
indentation rules to indicate the blocks.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/17
02/06/20 Python Programming Lab Manual -
21 b) Demonstrate about Fundamental Data types in Python Programming.
RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…5/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Description:

Every value in Python has a datatype.


SinceeverythingisanobjectinPythonprogramming,datatypesareactuallyclassesandvariablesare
instances (objects) of these classes.
There are various data types in Python. Some of the important types are listed below.

1. Python Numbers

Integers,floatingpointnumbersandcomplexnumbersfallunderPythonnumberscate
gory. They are defined as int, float and complex classes in Python.
We can use the type() function to know which class a variable or a value belongs
to. Similarly, the isinstance() function is used to check if an object belongs to a
particular class.

Example Programs:

In [21]:

a=5
print(a,"isoftype",type(a)
)

a=2.0
print(a,"isoftype",type(a))

a=1+2j
print(a,"iscomplexnumber?",isinstance(1+2j,compl
5 is of type <class 'int'>
2.0isoftype<class'float'>
(1+2j) is complex number?
True

In [1]:

a=34
print(type(a))
b=456792357968700
print(b)
print(type(b))

<class 'int'>
456792357968700
<class 'int'>

Observation:intdatatypeisusedtorepresentintegralvalues.Inpython3longintvaluescanalsobe
represented by using int type only.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[2]:
f=3.413
print(f)
print(type(f))
f1=1.2e4
print(f1)

3.413
<class'float'>12000
.0

Observation:floatdatatypeisusedtorepresentfloatingpointvalues.Wecanrepresentfloatvalues
scientifically by 'e'or'E'.

In [3]:
c=3+4j
print(type(c))
print(c.real)
print(c.imag)

<class'complex'>3
.0
4.0

Observation: In complex datatype we have some inbuilt attributes to retrieve real and imaginary
parts.

In [4]:

b=True
print(type(b))
a=5
b=8
c=a<b
print(c
)
<class'bool'>True

Observation:Thisdatatypeisusedtorepresentbooleanvalues.Theonlyallowedvaluesforthisdataty
pe are True and False.

Points to Ponder

Integers can be of any length, it is only limited by the memory available.


Afloating-
pointnumberisaccurateupto15decimalplaces.Integerandfloatingpointsareseparatedby
decimal points.
Complexnumbersarewrittenintheform,x+yj,wherexistherealpartandyistheimaginarypart. Here
are some examples.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [23]:

a=1234567890123456789
print(a)

b=0.12345678901234567
89 # float variable
print(b) 'b'truncated
c=1+2j
print(c
)
1234567890123456789
0.1234567890123456
8 (1+2j)

2. Python Strings

String is sequence of Unicode characters.


Wecanusesinglequotesordoublequotestorepresentstrings.
Multi- line strings can be denoted using triple quotes, '''
or """.

In [24]:

s="Thisisastring"print(s
)
s='''Amultilin
e string'''
print(s)

Thisisastring
A multiline
string

In [5]:

s1='python'print(s1
)
s2="record"print(s2
)

pytho
n
recor
d

In [6]:

s="pythonis
a
freeware"pr
i
File"<ipython-input-6-bccaede3693b>",line1
s="python is
^
SyntaxError:EOL while scanning string literal

Observation:Multilinestringliteralsarerepresentedbytriplequotes.Theycannotberepresentedbyusing
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Autono…8/17
02/06/20 Python Programming Lab Manual -
21 single or double quotes. RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

c) Demonstrate the working of ‘id’ and ‘type’ functions.

1. id() function:

The id() function returns identity (unique integer) of an object.

The syntax of id() is:

id(object)

Aswecanseethefunctionacceptsasingleparameterandisusedtoreturntheidentityofanobject.
This identity has to be unique and constant for this object during the lifetime.
Two objects with non-overlapping lifetimes may have the same id() value.
IfwerelatethistoC,thentheyareactuallythememoryaddress,hereinPythonitistheuniqueid.
The output is the identity of the object passed.
This is random but when running in the same program, it generates unique and same identity.

Examples:

In [1]:

id(1025)

Out[1]:

2497999538928

In [2]:
id(1025) # Here, the Output varies with different runs

Out[2]:

2497999539408

In [3]:

id("RGM")

Out[3]:

2497997578032

In [4]:

s="RGM"
print(id(s))

2497999585904

In [6]:

s2="RGM"
print(id(s2))

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…10/17
02/06/20 Python Programming Lab Manual -
21 2497999585904 RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…11/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
print(id(s)==id(s2))

True

In [8]:

# Use in Lists
list1=["Python","Java","C+
+"] print(id(list1[0]))
print(id(list1[2]))

2497932653936
2497999588144

In [10]:

# This returns false


print(id(list1[0])==id(list1[2]))

False

ReturnValuefromid():

The id() function returns identity of the object.


This is an integer which is unique for the given object and remains constant during its lifetime.

In [11]:

print('idof5=',id(5)) a
= 5
print('idofa=',id(a)) b
= a
print('idofb=',id(b))
c
= 5.0
print('idofc =',id(c))
idof5=140737105207824
idofa=140737105207824
idofb=140737105207824
id of c =
2497999538800

2. The ‘type()’ function:

Pythonhaveabuilt-inmethodcalledastypewhichgenerallycomeinhandywhilefiguringoutthetypeof
variable used in the program in the runtime.
The type function returns the datatype of any arbitrary object.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…12/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[21]:
print(type(5))
print(type(5.0))
print(type('5'))
print(type("5"))
print(type([]))
print(type(()))
print(type({}))
print(type({a,}))

<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>

typetakesanythingandreturnsitsdatatype.Integers,strings,lists,dictionaries,tuples,functions,
classes, modules, even types are acceptable.
type can take a variable and return its datatype.

3. range():

range() function is used to generate sequence of numbers.

In [1]:

r = range(10)
print(type(r))
print(r)

<class'range'>
range(0, 10)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…13/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[2]:
r = range(10)
print(type(r))
print(r)
foriinr:
print(i)

<class'range'>
range(0, 10)
0
1
2
3
4
5
6
7
8
9

In [3]:

r = range(10)
print(type(r))
print(r)
foriinr:
print(i,end='')

<class'range'>
range(0, 10)
0 1 2 3 4 5 6 7 8 9

In [4]:

r = range(10)
print(type(r))
print(r)
foriinr:
print(i,end='\t')

<class'range'>
range(0, 10)
0 1 2 3 4 5 6 7 8 9

In [6]:

r=range(10,-
25)
print(type(r))
print(r)
foriinr:
print(i,end='')
<class'range'>
range(10, -25)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
r=range(-
25,10)
print(type(r))
print(r)
foriinr:
print(i,end='')
<class'range'
> range(-25,
10)
-25 -24 -23 -22 -21 -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -
6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9

In [8]:
r=range(1,21,1)
foriinr:
print(i,end='')

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

In [9]:

r=range(1,21,2)
foriinr:
print(i,end='')

1 3 5 7 9 11 13 15 17 19

In [10]:

r=range(1,21,3)
foriinr:
print(i,end='')

1 4 7 10 13 16 19

In [11]:

r=range(1,21,4)
foriinr:
print(i,end='')

1 5 9 13 17

In [12]:

r=range(1,21,-5)
foriinr:
print(i,end='')

In [13]:

r=range(21,1,-5)
foriinr:
print(i,end='')

21 16 11 6

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[14]:
r=range(21,0,-5)
foriinr:
print(i,end='')

21 16 11 6 1

In [15]:

r=range(10,20)
print(r[0])
print(r[-
1]) r1 =
r[1:5]
print(r1)
foriinr1:
print(i)
r[1] = 3445
10
19
range(11, 15)
11
12
13
14

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-15-0c82f2e5b728>in<module>
6 foriin r1:
7 print(i)
---->8r[1]=3445

TypeError:'range' object does not support item assignment

d) Python Programs to demonstrate various Base Conversion functions.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…16/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[16]:
print(bin(12))
print(bin(0XA11))
print(bin(0o2345))
print(bin(54.67))

0b1100
0b101000010001
0b10011100101

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-16-6aaa1bd5a457>in<module>
2 print(bin(0XA11))
3 print(bin(0o2345))
----> 4print(bin(54.67))

TypeError:'float' object cannot be interpreted as an integer

Observation:bin() is used to convert from any base to binary except float values.

In [17]:

print(oct(456))
print(oct(0b1101))
print(oct(0xAB123))
print(oct(56.5))

0o710
0o15
0o2530443

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-17-3d6cec98201e>in<module>
2 print(oct(0b1101))
3 print(oct(0xAB123))
----> 4print(oct(56.5))

TypeError:'float' object cannot be interpreted as an integer

Observation:oct() is used to convert from any base to octal except float values.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…17/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[18]:
print(hex(675))
print(hex(0b1101))
print(hex(0o456))
print(hex(45.65))

0x2a
3
0xd
0x12
e

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-18-d5dc2a4af973>in<module>
2 print(hex(0b1101))
3 print(hex(0o456))
----> 4print(hex(45.65))

TypeError:'float' object cannot be interpreted as an integer

Observation:hex() is used to convert from any base to octal except float values.

e) PythonProgramstodemonstrateofvariousTypeConversion Functions.

Converting the value from one type to another type is called as Type casting or Type Coersion.

In [19]:

print(int(45.56
))
print(int(True)
)
print(int(False
45
1
0

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-19-
857e366a281f>in<module>
2print(int(True))
3print(int(False))
----> 4print(int(3+5j))

TypeError:can't convert complex to

int

Observation:Wecanuseint()toconvertfromothertypestointexceptcomplex.WegettypeErrorwhe
nwe try to convert complex to int.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…18/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[20]:
print(int('10'))
print(int('10.5'))
print(int('ten'))

10

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-20-b088da98807d>in<module>
1print(int('10'))
----> 2print(int('10.5'))
3print(int('ten'))

ValueError:invalid literal for int() with base 10: '10.5'

Observation:Toconvertstringtointtype,compulsarystringshouldcontainintegervaluesandspecifie
dwith base- 10.

In [21]:

print(float('10'))
print(float('10.5'))
print(float('ten'))

10.0
10.5

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-21-3b0ac2ae8b09>in<module>
1 print(float('10'))
2 print(float('10.5'))
----> 3print(float('ten'))

ValueError:could not convert string to float: 'ten'

Observation:Toconvertstringtofloatisnotpossiblewhenthestringcontainscharecters.

In [22]:

print(float(3+4j))

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-22-dd9e89f1504b>in<module>
----> 1print(float(3+4j))

TypeError:can't convert complex to

float

Observation:It is not possible to convert complex to float.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…19/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[23]:
print(complex(2))
print(complex(5.0))
print(complex(True))
print(complex('10'))
print(complex('ram'))

(2+0j)
(5+0j)
(1+0j)
(10+0j)

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-23-f42d0e340fec>in<module>
3 print(complex(True))
4 print(complex('10'))
----> 5print(complex('ram'))

ValueError:complex() arg is a malformed

string

Observation:It is possible to convert any type to complex except string contain characters.

In [24]:

print(bool(0))
print(bool(1))
print(bool(4))
print(bool(2.0))
print(bool(2+3j)
)
print(bool(True)
)
print(bool(False
Fals
e
True
True
True
True
True
Fals
e
True

Observation:Toconvertanytypetoboolispossiple.italwaysgiveeitherTrueor False.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…20/17
02/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[25]:
print(str(12))
print(str(2.0)
)
print(str(2+8j
))
print(str(True
12
2.0
(2+8j
)
True
-122

Observation:It is possible to convert from any type to string type.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…21/17
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment2:DemonstrationofvariousoperatorsusedinPythonwith suitable
example programs.

Operatoris a symbol which can perform specified operation on operands.

TypesofOperatorsusedinPython:

1. Arithmetic operators.
2. Relational or Comparision operators.
3. Equality operators.
4. Logical operators.
5. Bitwise operators.
6. Shift operators.
7. Assignment operators.
8. Ternaryoperator.(or)Conditionaloperator.
9. Special operators:

a. Identity operator.

b. Membership operator.

10. Operator precedence.

1. Arithmetic Operators:

Thearithmeticoperationsarethebasicmathematicaloperatorswhichareusedinourdailylife.Mainlyi
t consists of seven operators.

i. Addition operator -->'+'

ii. Subtraction operator -->'-'

iii.Multiplication operator -->'*'

iv.Normal Division operator -->'/'

v.Modulo Division operator -->'%'

vi.Floor Division operator -->'//'

vii.Exponential operator (or) power operator -->'**'

i. Addition Operator :

Generally addition operator is used to perform the addition operation on two operands.
Butinpythonwecanuseadditionoperatortoperformtheconcatenationofstrings,listsandsoon,but
operands must of same datatype.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…1/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[1]:
x=2
y=3
print("ADDITIONRESULT :",x+y)

ADDITION RESULT :5

In [2]:
x=2
y=3.
3
print("ADDITIONRESULT : ",x+y)#both float andint type are accept
ADDITION RESULT :5.3

In [3]:

x=2.
7
y=3.
3
ADDITION RESULT :6.0

In [4]:

x="2"
y=3
print("ADDITIONRESULT : ",x+y)#str type andint can't be added.

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-4-
d873d6fd7998>in<module> 1x="2"
2y=3
---->3print("ADDITIONRESULT:",x+y)#strtypeandintcan'tbeadde d.

TypeError:can only concatenate str (not "int") to str

In [5]:

x="2"
y="3"
print("ADDITIONRESULT :",x+y)# concatenationwill take place

ADDITION RESULT :23

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…2/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[6]:
x="2
"
y=4.
8
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-6-
32bf23d43c09>in<module> 1x="2"
2y=4.8
---->3print("ADDITIONRESULT:",x+y)#floattypeandstrtyprcan't be added.

TypeError:can only concatenate str (not "float") to str

In [7]:

x=2
y=bool(4.8
)
print("ADDITIONRESULT : ",x+y)#here bool(4.8) returnsTrue i.e, 1
ADDITION RESULT :3

In [8]:

x="2"
y=bool(4.8)
print("ADDITIONRESULT :",x+y)#bool typecant be concatenated.

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-8-
aa2b47f2b5f5>in<module> 1x="2"
2y=bool(4.8)
---->3print("ADDITIONRESULT:",x+y)#booltypecantbeconcatenate d.

TypeError:can only concatenate str (not "bool") to str

In [9]:

x="2"
y=str(bool(4.8))
print("ADDITIONRESULT :",x
+y)
#bool returns 1 generally but we converted into str then it gives True
ADDITION RESULT

:2True In [10]:

x="2"
y=str(complex(4.8 #Here both strings so concatenation will take
print("ADDITIONRESULT :",xplace
))
+y)
ADDITION RESULT :2(4.8+0j)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…3/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[11]:
x=2
y=complex(4.8
)
print("ADDITIONRESULT :",x+y)
# here both are int type so addtion will take place
ADDITION RESULT :(6.8+0j)

ii. Subtraction Operator :

Generally subtraction operator is used to perform the subtraction operation on two operands.

In [12]:

a=3
0
b=1
0
Subtraction result :20

In [13]:

a=30
b="10
"
print("Subtractionresult:",a-b)
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-13-
f0fd62944ccb>in<module> 1a=30
2b="10"
---->3print("Subtractionresult:",a-b)

TypeError:unsupported operand type(s) for -: 'int' and 'str'

In [14]:

a="30"
b="10"
print("Subtractionresult:",a-b)
# can not perform subtraction on str type operands.

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-14-0bebbed27be9>in<module>
1a="30"
2b="10"
---->3print("Subtractionresult:",a-b)
4# can not perform subtraction on str type operands.

TypeError:unsupported operand type(s) for -: 'str' and 'str'

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…4/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
a=20
b=10.0
0
print("Subtractionresult:",a-b)
Subtraction result :10.0

In [16]:

a=20
b=bool(10)
print("Subtractionresult:",a
-b)
Subtraction result :19

iii. Multiplication operator :

Generally multiplication operator is used to perform the multiplication operation on two


operends

Butinpythonwecanusemultiplicationoperatortoperformtherepetitionofstrings,listsandsoon,
but operands must belongs to same datatype.

In [17]:

num1=2
3
num2=3 RESULT ",num1 *num2)
5 :
print("MULTIPLICATI
ON
MULTIPLICATION :805
RESULT
In [18]:

num1=23
num2=35.
0 RESULT ",num1 *num2)
print("MULTIPLICATI :
ON
MULTIPLICATION :805.0
RESULT
In [19]:

num1="23
" num2=5
print("MULTIPLICATI RESULT ",num1 *num2)# 23 string will prints 5 times
ON :
MULTIPLICATION RESULT :2323232323

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…5/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[20]:
num1="23
"
num2="5"
print("MULTIPLICATIONRESULT:",num1*num2)
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-20-e4135d9e3a29>in<module>
1num1="23"
2num2="5"
---->3print("MULTIPLICATION RESULT: ",num1*num2)

TypeError:can't multiply sequence by non-int of type 'str'

In [21]:

l="(1,2,3,4)"
print(float(l*5))

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-21-18109e54b2f8>in<module>
1l="(1,2,3,4)"
---->2print(float(l*5)) ValueError:couldnotconvertstringtofloat:'(1,2,3,4)

(1,2,3,4)(1,2,3, 4)(1,2,3,4)(1,2,3,4)'

In [22]:

l="123"
print(float(l*4))
#initially it will prints string 5 times and converts it into float

123123123123.0

In [23]:

l="123
"
b=2.3
print("MULTIPLICATIONRESULT :",l*b)
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-23-e235870edcad>in<module>
1l="123"
2b=2.3
---->3print("MULTIPLICATIONRESULT : ",l*b)

TypeError:can't multiply sequence by non-int of type 'float'

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…6/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[24]:
l="123"
b=bool(2.3)
print("MULTIPLICATIONRESULT :",l
*b)
MULTIPLICATION RESULT :123

In [25]:

l=[1,2,3]
m=[2,4,5]
print(l*m)# multiplicationof two list datatypes is not possible

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-25-309b92e03dcb>in<module>
1l=[1,2,3]
2m=[2,4,5]
---->3print(l*m)#multiplicationoftwolistdatatypesisnotpossib le

TypeError:can't multiply sequence by non-int of type 'list'

In [26]:

l=(5,6,7)
m=(1,2,3)
print(l*m)#multiplication of twotuple data typesis not possible

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-26-91a31577591d>in<module>
1l=(5,6,7)
2m=(1,2,3)
----

>3print(l*m)#multiplicationoftwotupledatatypesisnotpossib

le TypeError:can't multiply sequence by non-int of type

'tuple'

In [27]:

l=bool(1)
m=bool(4657
)
print(l*m)# asbool returns 1 itprints only one time
1

In [28]:

l=bool()
m=bool(12345678
9)
print(l*m)# Asbool doesn'tcontain anyvalue itconsider as zero.
0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…7/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[29]:
l=str(bool([1,2,3]
)) m=99
print(l*m)

TrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTru
eTrueTr
ueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueT
rueTrue
TrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTru
eTrueTr
ueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueT
rueTrue
TrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTrueTru
eTrueTr ueTrueTrueTrueTrueTrueTrue

In [30]:
l=bool([1,2,3]
) m=99
print(l*m)

99

iv. Division Operator :

Generallydivisionoperatorisusedtoperformthedivisionoperationontwoopera
nds. It returns the result in float type.

In [31]:

a=3
b=4
5
print("Divisionresult: ",a/b)# returnsfloat value
Division result :0.06666666666666667

In [32]:

a=3
b="45
"
print("Divisionresult :",b/a)
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-32-
1b2bbedeebd4>in<module> 1a=3
2b="45"
---->3print("Divisionresult : ",b/a)

TypeError:unsupported operand type(s) for /: 'str' and 'int'

In [33]:

a=3
b=45.000
0
print("Divisionresult :",b/a)
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?downl…8/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[29]:
Division result :15.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…9/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[34]:
a=3
b=bool(0.0000
)
print("Divisionresult :",a/b)
--------------------------------------------------------------------------
-
ZeroDivisionError Traceback(mostrecentcalllas t)
<ipython-input-34-
854e10cbf4f9>in<module> 1a=3
2b=bool(0.0000)
---->3print("Divisionresult:",a/b)

ZeroDivisionError: division by zero

In [35]:

a=3
b=complex((90)
)
print("Divisionresult :",a/b)
Division result :

(0.03333333333333333+0j) In [36]:

a=[1,2,3]
b=[7,8,9]
print("Divisionresult :",a/b)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-36-8289b4627a90>in<module>
1a=[1,2,3]
2b=[7,8,9]
---->3print("Divisionresult : ",a/b)

TypeError:unsupported operand type(s) for /: 'list' and 'list'

In [37]:

a=(1,2,3)
b=(1,2,3)
print("Divisionresult :",a/b)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-37-f02db8ba9671>in<module>
1a=(1,2,3)
2b=(1,2,3)
---->3print("Divisionresult : ",a/b)

TypeError:unsupported operand type(s) for /: 'tuple' and 'tuple'

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…10/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[38]:
a={1,2,3}
b={1,2,3}
print("Divisionresult :",a/b)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-38-cd4ea53f676a>in<module>
1a={1,2,3}
2b={1,2,3}
---->3print("Divisionresult : ",a/b)

TypeError:unsupported operand type(s) for /: 'set' and

'set' In [39]:

l=bool()
m = bool(9)
print(l/m)

0.0

v. Modulo Division:

It returns reminder.

In [40]:
a=3
b=4
print(a%b)
print(b%a)

3
1

vi. Floor Division:

Suppose 10.3 is there, what is the floor value of 10.3?

Answer is 10

What is the ceil value of 10.3?

Answer is 11

In [41]:
print(10/2)

5.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…11/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[42]:
print(10/3)

3.3333333333333335

Ifyouwanttogetintegervalueasresultofdivisionoperation,youneedtomakeuseoffloordivision(//)
operator.
floordivision(//)operatormeantforintegralarithmeticoperationsaswellasfloatingpointarithmetic
operations.
Theresultoffloordivision(//)operatorcanbealwaysfloorvalueofeitherintegervalueorfloatvalue
based on your arguments.
If both arguments are 'int' type, then the result is 'int' type.
If atleast one of the argument is float type, then the result is also float type.

In [43]:

print(10//2)

In [44]:

print(10/3)

3.3333333333333335

In [45]:

print(10.0/3)

3.3333333333333335

In [46]:

print(10.0//3)

3.0

In [47]:

print(10//3)

In [48]:

print(10.0//3.0)

3.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…12/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [49]:

print(20/2)
print(20.5/2)
print(20//2)
print(20.5//2)
print(30//2)
print(30.0//2)

10.0
10.25
10
10.0
15
15.0

vii. Power Operator or Exponential Operaor :

In [50]:

print(10**2)# meaningof thisis 10to thepower 2


print(3**3)

100
27

2. Relational Operators (or) Comparison Operators:

Following are the relational operators usedin Python:

1. Less than (<)


2. Greater than (>)
3. Leass than or Equal to (<=)
4. Greater than or Equal to (>=)

i) Wecanapply relationaloperators fornumber types:

In [51]:

a=1
0
b=2
0
print('a < b is',
a<b)
print('a<=bis',a<=b)
a < b is
True
a<=bisTrue a
> b is False
a >= b is False

ii) Wecanapplyrelationaloperatorsfor'str'typealso,herecomparisonisperformedbasedonASCII or
Unicode values.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…13/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

How to know the Unicode or ASCII value of any character?

By using ord() function, we can get the ASCII value of any character.

In [52]:

print(ord('a'))
print(ord('A'))

97
65

If you know the ASCII value and to find the corresponding character, you need to use the chr()
function.

In [53]:

print(chr(97))
print(chr(65))

a
A

In [54]:

s1 = 'karthi'# ASCII value of 'a' is


97 s2='sahasra'#ASCIIvalueof'b'is98
print(s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)

True
True
Fals
e
Fals
e

s1='karthi's2=
In [55]:
'karthi'print(
s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)

Fals
e
True
Fals
e
True

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…14/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[56]:
s1='karthi's2=
'Karthi'print(
s1<s2)
print(s1<=s2)
print(s1>s2)
print(s1>=s2)

Fals
e
Fals
e
True
True

iii) Wecan applyrelational operatorseven forboolean types also.

In [57]:

print(True>False)
print(True>=False)#True==>
1
print(True<False)#False==>
0 print(True <= False)
True
True
Fals
e
Fals
e

In [58]:

print(10>'karthi')

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-58-e2ae37134b58>in<module>
---->1print(10>'karthi')

TypeError:'>' not supported between instances of 'int' and 'str'

In [60]:

a=1
0
b=2
0
ifa>b:
print('ais greaterthan b')
else:
a is not greater than b

iv) Chaining of relational operatrs:

Chaining of relational operators is possible.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…15/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[56]:
Inthechaining,ifallcomparisonsreturnsTruethenonlyresultis
True. If atleast one comparison returns False then the
result is False.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…16/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[61]:
print(10<20) #
print(10<20<30) ==>True
print(10<20<30<4 #==>True
0) #
print(10<20<30<40>50)#==>Fa
lse
True
True
True
Fals
e

3. Equality Operators:

Equalityoperatorsareusedtocheckwhetherthegiventwovaluesareequalornot.Thefollowingarethe
equality operators used in Python.

1. Equal to (==)
2. Not Equal to (!=)

In [62]:
print(10==20)
print(10!=20)

Fals
e
True

In [63]:
print(1==True)
print(10==10.0)
print('karthi'=='karthi')

Tru
e
Tru
e
Tru
e

Wecan apply theseoperators for anytype, even forincompatible types also.

In [64]:

print(10=='karthi')

False

In

[65]:

print(10=='10')

False
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…17/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[61]:
Note:

Chaining concept is applicable for equality operators.


If atleast one comparison returns False then the result is False. otherwise the result is True.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…18/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[66]:
print(10==20==30==40)
print(10==10==10==10)

Fals
e
True

4. Logical operators:

Following are the various logical operators used in Python.

1. and
2. or
3. not

Youcanapplytheseoperatorsforbooleantypesandnon-booleantypes,butthebehaviorisdifferent.

For boolean types:

and==>IfbothargumentsareTruethenonlyresultisTrue or

==> If atleast one arugemnt is True then result is True not

==> complement

i) 'and' Operator for boolean type:

If both arguments are True then only result is True

In [67]:

print(True and True)


print(TrueandFalse)
print(FalseandTrue)
print(FalseandFalse)

True
Fals
e
Fals
e
Fals
e

ii) 'or' Operator for boolean type:

IfbothargumentsareTruethenonlyresultis True.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…19/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [68]:

print(True or True)
print(TrueorFalse)
print(FalseorTrue)
print(FalseorFalse)

True
True
True
Fals
e

iii) 'not' Operator for boolean type:

Complement (or) Reverse

In [69]:

print(not True)
print(notFalse)

Fals
e
True

Eg:

Now we will try to develop a small authentication application with this

knowledge. we will read user name and password from the keyboard.
if the user name is karthi and password is sahasra, then that user is valid user otherwise
invalid user.

In [70]:

userName=input('EnterUserName:') password
= input('Enter Password : ')
ifuserName=='karthi'andpassword=='sahasra':
print('valid User')
else:
print('invalid user')

EnterUserName:karthi
EnterPassword:sahasra
valid User

In [71]:

userName=input('EnterUserName:') password
= input('Enter Password : ')
ifuserName=='karthi'andpassword=='sahasra':
print('valid User')
else:
print('invalid user')

EnterUserName:ECE
Enter Password : CSE
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…20/31
04/06/20 Python Programming Lab Manual -
21 invalid user RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…21/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Fornon-booleantypesbehaviour:

Note:

0 means False
non-zero means True
empty strings, list,tuple, set,dict is always treated as False

i) X and Y:

Here,XandYarenonbooleantypesandtheresultmaybeeitherXorYbutnotbooleantype(i.e.,The
result is always non boolean type only).

if'X'isevaluatestofalsethentheresultis'X'. If 'X' is
evaluates to true then the result is 'Y'.

In [72]:
print(10and20)
print(0and20)
print('karthi'and'sahasra
')
print(''and'karthi')# firstargument is empty string
print(''and'karthi')
# first argument contains space character, so it is not empty
print('karthi'and'')# second argumentis empty string
print('karthi'and'')
# second argument contains space character, so it is not empty
20
0
sahasra

karthi

ii) X or Y

Here,XandYarenonbooleantypesandtheresultmaybeeitherXorYbutnotbooleantype(i.e.,The
result is always non boolean type only).

if 'X' is evaluates to true then the result


is 'X'. If 'X' is evaluates to false then
the result is 'Y'.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…22/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[1]:
print(10or20
)
print(0or20)
print('karthi'or'sahasra')
print(''or'karthi')# firstargument is empty string
print(''or'karthi')
# first argument contains space character, so it is not empty
print('karthi'or'')# second argumentis empty string
print('karthi'or'')
10
20
karth
i
karth
i

karth
i
karth
i

iii) not X:

Evenyou apply not operator for non boolean type, the result is always boolean type only.

If X is evalutates to False then result is True otherwise False.

In [2]:

print(not'karthi')
print(not '')
print(not0)
print(not10)

Fals
e
True
True
Fals
e

5. Bitwise Operators:

We can apply these operators bit by bit.


Theseoperatorsareapplicableonlyforintandbooleantypes.Bymistakeifwearetryingtoapplyfor
any other type then we will get Error.

Following are the various bitwise operators used in Python:

1. Bitwise and (&)


2. Bitwise or (|)
3. Bitwise ex-or (^)
4. Bitwise complement (~)
5. Bitwise leftshift Operator (<<)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…23/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[1]:
6. Bitwise rightshift Operator(>>)

1. Bitwise and (&):

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…24/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[3]:
print(10.5& 20.6)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-3-d0942894908d>in<module>
---->1print(10.5&20.6)

TypeError:unsupported operand type(s) for &: 'float' and 'float'

In [4]:

print('karthi'|'karthi')

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-4-482742ac27fc>in<module>
---->1print('karthi'|'karthi')

TypeError:unsupported operand type(s) for |: 'str' and 'str'

In [5]:

print(bin(10))
print(bin(20))
print(10&20)# Valid
print(10.0&20.0)#In
valid
0b1010
0b10100
0

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-5-2449e0efc92e>in<module>
2 print(bin(20))
3 print(10&20)# Valid
---->4print(10.0&20.0)# In valid

TypeError:unsupported operand type(s) for &: 'float' and 'float'

In [6]:

print(True&False)

False

2. Bitwise or (|):

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…25/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [7]:

print(True|False)

True

3. Bitwise ex-or (^):

In [9]:

print(2^4)

Behavior of Bitwise Operators:

& ==> If both bits are 1 then only result is 1 otherwise


result is 0 | ==> If atleast one bit is 1 then result is 1
otherwise result is 0
^==>If bits aredifferent then onlyresult is 1otherwise
result is 0
~==>bitwisecomplementoperator,i.e1means0and0mea
ns1
<< ==> Bitwise Left shift
Operataor Bitwise Right Shift
Operator ==>>>

In
[8]:
print( & 5) # 100 & 101
4
print( | 5) # 100 | 101
4
print( ^ 5) # 100 ^ 101
4
4
5
1

Bitwise Complement Operator (~):

We have to apply complement for total bits.

In [10]:

print(~4)#4==>100

-5

Here,wehavetoapplycomplementfortotalbits,notforthreebits(incaseof4).InPythonminimum28
bits required to represent an integer.

Note:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…26/31
04/06/20 Python Programming Lab Manual -
21 Themostsignificantbitactsassignbit.0valuerepresents+venumberwhereas1represents-
RGMCET(Autonomous)

vevalue. Positive numbers will be repesented directly in the memory where as Negative
numbers will be represented
indirectly in 2's complement form.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…27/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

How you can find two's complement of a number?

TofindTwo'scomplementofanumber,firstyouneedtofindOne'scomplementofthatnumberand
add 1 to it. One's complement ==> Interchange of 0's and 1's

In [11]:

print(~5)

-6

In [12]:

print(~-4)# negative valuesare stored inthe memory in2's complement form.

6. Shift Operators:

Following are the various shift operators used in Python:

1. Left Shift Operator (<<)


2. Right Shift Operator (<<)

1. Left Shift Operator (<<):

After shifting the bits from left side, empty cells to be filled with zero.

In [13]:

print(10<<2)

40

2. Right Shift Operator (<<):

After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve).

In [14]:

print(10>>2)

Wecan applybitwise operatorsfor booleantypes also.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…28/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [15]:

print(True&False)
print(True|False)
print(True^False)
print(~True)
print(~False)
print(True<<2)
print(True>>2)

Fals
e
True
True
-2
-1
4
0

7. Assignment Operators:

We can use assignment operator to assign value to the


variable.

In [
]:

x=2

Wecancombineasignmentoperatorwithsomeotheroperatortoformcompoundassignmentoperat
or. Eg :

x+=10 ====> x = x+10

In
[16]:
x=10
x+=20# x = x + 20
print(x)

3
0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…29/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

The following is the list of all possible compound assignment operators in Python:

+=

-=

*=

/=

%=

//=

**

&

|=

^=

<<= and >>=

In [17]:
x=10# 1010
x&=5# 0101
print(x)

In [18]:

x=10
x**=2# x = x**2
print(x)

100

InPythonincrement/

decrementoperatorsconceptisnotthere. Let us see the

following code

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…30/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[19]:
x=10
print(++x)
print(+++
+x)
# Here, + and - are sign bits, not increment and decrement operators
print(-x)
print(--x) print(++
++++++++++-x)
print( +x)
10
10
-10
10
-10
-10

8. TernaryOperator(or)ConditionalOperator

1. Iftheoperator operatesononly oneoperand,we willcallsuch operatorasunary operator.Foreg:,


~a.
2. IftheoperatoroperatesonTwooperands,wewillcallsuchoperatorasbinaryoperator.Foreg:,a+b.
3. IftheoperatoroperatesonThreeoperands,wewillcallsuchoperatorasTernaryoperator.

Syntax:

x = firstValue if condition else secondValue

If condition is True then firstValue will be considered else secondValue will be considered.

In [1]:

a,b=23,43#a=23b=43
c=50ifa>belse100
print(c)

100

Readtwo integer numbers from the keyboard and print minimum value using ternary operator.

In [2]:

x =int(input("Enter First
Number:"))
y=int(input("EnterSecondNumber:"))
min=x if x<y else y
print("Minimum Value:",min)
EnterFirstNumber:2
55
EnterSecondNumber:
22 Minimum Value:
22

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…31/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [3]:

x =int(input("Enter First
Number:"))
y=int(input("EnterSecondNumber:"))
min=x if x<y else y
print("Minimum Value:",min)

Enter First
Number:22
EnterSecondNumber:2
55 Minimum Value:
22

Program for finding minimum of 3 numbers using nesting of ternary operators.

In [4]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
c=int(input("Enter Third Number:"))
min=aifa<banda<celsebifb<celsec print("Minimum
Value:",min)

Enter First
Number:101
EnterSecondNumber:201
Enter Third
Number:301 Minimum
Value: 101

In [5]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
c=int(input("Enter Third Number:"))
min=aifa<banda<celsebifb<celsec print("Minimum
Value:",min)

Enter First Number:-


10
EnterSecondNumber:-
20 Enter Third
Number:-30 Minimum
Value: -30

Python Program for finding maximum of 3 numbers.

In [6]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
c=int(input("Enter Third Number:"))
max=aifa>banda>celsebifb>celsec
print("Maximum Value:",max)

Enter First Number:33


EnterSecondNumber:22
Enter Third Number:44
Maximum Value: 44
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…32/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Assumethattherearetwonumbers,xandy,whosevaluestobereadfromthekeyboard,andprint the
following outputs based on the values of x and y.

case 1: If both are equal, then the output is : Both numbers are equal
case2:Iffirstnumberissmallerthansecondone,thentheoutputis:FirstNumberisLessthanSecond
Number
case3:Ifthefirtsnumberisgreaterthansecondnumber,thentheoutputis:FirstNumberGreaterthan
Second
Number

In [7]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
print("Bothnumbers areequal"ifa==b
else"First Number is Less than Second Number"
ifa<belse"First NumberGreater than Second Number")

Enter First Number:10


EnterSecondNumber:10
Both numbers are
equal

In [8]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
print("Bothnumbers areequal"ifa==b
else"First Number is Less than Second Number"
ifa<belse"First NumberGreater than Second Number")

Enter First Number:10


Enter Second
Number:20
First Number is Less than Second Number

In [9]:

a=int(input("Enter First Number:"))


b=int(input("EnterSecondNumber:"))
print("Bothnumbers areequal"ifa==b
else"First Number is Less than Second Number"
ifa<belse"First NumberGreater than Second Number")

Enter First Number:20


Enter Second
Number:10
First Number Greater than Second Number

9. Special Operators:

There are two types of special operators are there in Python:

1. Identity Operators
2. Membership Operators

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…33/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

1. Identity Operators:

Wecan use identityoperators for address comparison.There are two identityoperators used in
Python:

i) is

ii) is not

r1 is r2 returns True if both r1 and r2 are pointing to the same object.


r1 is not r2 returns True if both r1 and r2 are not pointing to the same object.

In [1]:

a=10
b=10
print(aisb
) x=True
y=True
print(xisy
)
True
Tru
e

In [2]:
a="karthi"b="karthi
"print(id(a))
print(id(b)
)
print(aisb)

1509178647664
1509178647664
True

In [3]:
list1=["one","two","three"]
list2=["one","two","three"]
print(id(list1))
print(id(list2))
print(list1islist2)
print(list1isnotlist2)# reference comaprison(is & is not)
print(list1==list2)# contentcomparison (==)

1509178190144
1509178196736
False
True
True

Note:

Wecan use isoperator for address comparisonwhere as ==operator for content comparison.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…34/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

2. Membership Operators

WecanuseMembershipoperatorstocheckwhetherthegivenobjectpresentinthegivencollection.(Itmay
be String,List,Set,Tuple or Dict)

There are two types of membership operators used in Python:

i) in

ii) not in

in returns True if the given object present in the specified Collection.


not in retruns True if the given object not present in the specified Collection.

In [4]:

x="hellolearningPythonisveryeasy!!!"pr
int ('h'in x)
print('d'inx)
print('d'notinx)
print('python'inx)#case sensitivity
print('Python'inx)

True
Fals
e
True
Fals
e
True

list1=["sunny","bunny","chinny","pinny
In [5]:
"] print("sunny"in list1)
print("tunny"inlist1)
print("tunny"notinlist1)

True
Fals
e
True

10. Operator Precedence:

Ifmultipleoperatorspresentthenwhichoperatorwillbeevaluatedfirstisdecidedbyoperator
precedence.

In [6]:

print(3+10*2)
print((3+10)*2
)
23
26

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…35/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

The following list describes operator precedence in Python:

() ==>Parenthesis

** ==> exponential operator

~,-==>Bitwisecomplementoperator,unaryminus operator

*,/,%,// ==> multiplication,division,modulo,floor division

+,- ==>addition,subtraction

<<,>>==>LeftandRightShift &

==> bitwise And

^ ==> Bitwise X-OR

| ==> Bitwise OR

<,<=,>,>=,==, != ==> Relational or Comparison operators

=,+=,-=,*=...==>Assignmentoperators is

, is not ==> Identity Operators

in,notin==>Membershipoperato

rs not

==> Logical not

and==>Logicalan

d or

==> Logical or

In [7]:

a=3
0
b=2
0
c=1
0
d=5
print((a+b)*c/d
)
100.0
100.0
70.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…36/31
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [8]:

print(3/2*4+3+(10/5)**3-
2)
print(3/2*4+3+2.0**3-2)
print(3/2*4+3+8.0-2)
print(1.5*4+3+8.0-2)
print(6.0+3+8.0-2)
15.0
15.0
15.0
15.0
15.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…37/31
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 3:

a) WritePythonprograms todemonstratethe following:

i) input( ) ii) print( ) iii) ‘sep’ attribute


iv) ‘end’ attribute v) replacement Operator ({ })

i. input():

ThisfunctionalwaysreadsthedatafromthekeyboardintheformofStringFormat.Wehavetoconv
ert that string type to our required type by using the corresponding type casting
methods.

In [1]:

type(input("Entervalue:"))

Entervalue:10

Out[1]:

str

In [2]:

type(input("Entervalue:"))

Entervalue:22.7

Out[2]:

str

In [3]:

type(input("Entervalue:"))

Entervalue:True

Out[3]:

str

In [4]:

type(input("Entervalue:"))

Entervalue:'RGMCET'Out[4]

str

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Note:

Why input() in Python 3 gave the priority for string type as return type?

Reason:Themostcommonlyusedtypeinanyprogramminglanguageisstrtype,that'swhytheygavethe
priority for str type as default return type of input() function.

Demo Program 1: Read input data from the Keyboard

In [5]:

x=input("Enter First
Number:")
y=input("EnterSecondNumber:"
) i=int(x)
j=int(y)
print("The Sum:",i+j)
Enter First
Number:1000
EnterSecondNumber:200
0 The Sum: 3000

Above code in simplified form:

In [6]:

x=int(input("Enter First Number:"))


y=int(input("EnterSecondNumber:"))
print("The Sum:",x+y)

Enter First
Number:1000
EnterSecondNumber:200
0 The Sum: 3000

Wecan writethe abovecode insingle line also.

In [7]:

print("TheSum:",int(input("EnterFirst Number:"))
+int(input("EnterSecond Number:")))

Enter First
Number:1000
EnterSecondNumber:200
0 The Sum: 3000

DemoProgram 2: Write aprogram to read Employeedata from the keyboardand print that data.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[8]:
eno=int(input("EnterEmployeeNo:"))
ename=input("Enter Employee Name:")
esal=float(input("EnterEmployeeSalary:"))
eaddr=input("Enter Employee Address:")
married=bool(input("EmployeeMarried?[True|
False]:")) print("Please Confirm your provided
Information") print("EmployeeNo:",eno)
print("Employee Name :",ename)
print("EmployeeSalary:",esal)
print("EmployeeAddress:",eaddr)
print("EmployeeMarried? :",marri
ed)

Enter Employee No:11111


EnterEmployeeName:Karthikeya
Enter Employee Salary:100000
Enter Employee
Address:Nandyal Employee
Married ?[True|False]:T
PleaseConfirmyourprovidedInformation
Employee No : 11111
EmployeeName:Karthikeya
EmployeeSalary:100000.0
EmployeeAddress:Nandyal
Employee Married ? : True

In [9]:

eno=int(input("EnterEmployeeNo:"))
ename=input("Enter Employee Name:")
esal=float(input("EnterEmployeeSalary:"))
eaddr=input("Enter Employee Address:")
married=bool(input("EmployeeMarried?[True|
False]:")) print("Please Confirm your provided
Information") print("EmployeeNo:",eno)
print("Employee Name :",ename)
print("EmployeeSalary:",esal)
print("EmployeeAddress:",eaddr)
print("EmployeeMarried? :",marri
ed)
Enter Employee No:11111
EnterEmployeeName:Karthikeya
Enter Employee Salary:100000
Enter Employee
Address:Nandyal
Employee Married ?[True|
False]:False
PleaseConfirmyourprovidedInformation
Employee No : 11111
EmployeeName:Karthikeya
EmployeeSalary:100000.0
EmployeeAddress:Nandyal
Employee Married ? : True

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [10]:

eno=int(input("EnterEmployeeNo:"))
ename=input("Enter Employee Name:")
esal=float(input("EnterEmployeeSalary:"))
eaddr=input("Enter Employee Address:")
married=bool(input("EmployeeMarried?[True|
False]:")) print("Please Confirm your provided
Information") print("EmployeeNo:",eno)
print("Employee Name :",ename)
print("EmployeeSalary:",esal)
print("EmployeeAddress:",eaddr)
print("EmployeeMarried? :",marri
ed)

Enter Employee No:11111


EnterEmployeeName:Karthikeya
Enter Employee Salary:100000
Enter Employee
Address:Nandyal
EmployeeMarried ?[True|
False]:
PleaseConfirmyourprovidedInformation
Employee No : 11111
EmployeeName:Karthikeya
EmployeeSalary:100000.0
EmployeeAddress:Nandyal
Employee Married ? : False

Whenyouarenotprovidinganyvaluetothemarried(JustpressEnter),thenonlyitconsidersemptystr
ing and gives the False value. In the above example, to read the boolean data, we need to
follow the above process.

Butitisnotourlogicrequirement.IfyouwanttoconvertstringtoBooleantype,insteadofusingbool()
function we need to use eval() function.

In [11]:

eno=int(input("EnterEmployeeNo:"))
ename=input("Enter Employee Name:")
esal=float(input("EnterEmployeeSalary:"))
eaddr=input("Enter Employee Address:")
married=eval(input("EmployeeMarried?[True|
False]:")) print("Please Confirm your provided
Information") print("EmployeeNo:",eno)
print("Employee Name :",ename)
print("EmployeeSalary:",esal)
print("EmployeeAddress:",eaddr)
print("EmployeeMarried? :",marri
ed)
Enter Employee No:11111
EnterEmployeeName:Karthikeya
Enter Employee Salary:100000
Enter Employee
Address:Nandyal
Employee Married ?[True|
False]:False
PleaseConfirmyourprovidedInformation
Employee No : 11111
EmployeeName:Karthikeya
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Autono…4/83
06/06/20 Python Programming Lab Manual -
21 EmployeeSalary:100000.0 RGMCET(Autonomous)
EmployeeAddress:Nandyal
Employee Married ? : False

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…5/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

eval() Function:

eval() Function is a single function which is the replacement of all the typecasting functions in
Python.

In [12]:
x=(input('EnterSomething:'
)) print(type(x))

Enter Something : 10
<class 'str'>

In [13]:

x=(input('EnterSomething:'
)) print(type(x))

Enter Something :33.3


<class

'str'> In

x=eval((input('EnterSomething:')
[15]:
)) print(type(x))

Enter Something : 'Nandyal'


<class 'str'>

In [16]:

x=eval((input('Ente Something : ')))


r print(type(x))

Enter Something :
10
<class 'int'>

In [17]:

x=eval((input('Ente Something : ')))


r print(type(x))

Enter Something : 33.3


<class 'float'>

In [18]:

x=eval((input('Ente Something : ')))


r print(type(x))

Enter Something : 'Nandyal'


<class 'str'>

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[19]:
x=eval((input('EnterSomething:')
)) print(type(x))

Enter Something : [1,2,3]


<class 'list'>

In [20]:

x=eval((input('EnterSomething:')
)) print(type(x))

Enter Something : (1,2,3)


<class 'tuple'>

In [21]:

x=eval((input('EnterSomething:')
)) print(type(x))

Enter Something : (10)


<class 'int'>

In [22]:

x=eval((input('EnterSomething:')
)) print(type(x))

Enter Something : (1,)


<class 'tuple'>

ii.print():

Wecanuseprint()functiontodisplayoutputtotheconsoleforendusersake.
Multiple forms are there related to print() function.

Form-1: print() without any

argument Just it prints new line

character (i.e.,\n)

In [1]:

print('karthi')
print()# prints new line character
print('sahasra')

karthi

sahasra

seethedifferenceinbelow code:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[2]:
print('karthi')
#print() # prints new line character
print('sahasra')

karthi
sahasra

Form-2: print() function to print of string argument

In [3]:

print("Hello World")

Hello World

Wecanuseescapecharacters also.

In [4]:
print("Hello\nWorld")
print("Hello\tWorld")

Hello
Worl
d
Hello World

We can use repetetion operator (*) in the string.

In [6]:

print(10*"RGM"
)
print("RGM"*10
RGMRGMRGMRGMRGMRGMRGMRGMRGMRGM
RGMRGMRGMRGMRGMRGMRGMRGMRGMRGM

We can use + operator also.

In [7]:
print("RGM"+"CET")

RGMCET

Note:

If both arguments are string type then + operator acts as concatenation operator.
IfoneargumentisstringtypeandsecondisanyothertypelikeintthenwewillgetError
Ifbothargumentsarenumbertypethen+operatoractsasarithmeticadditionoperator.

Form-3: print() with variable number of arguments:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[8]:
a,b,c=10,20,30
print("TheValuesare :",a,b,c)
# here, we are passing 4 arguments to the print function.

The Values are : 10 20 30

iii. 'sep'attribute:

Form-4: print() with 'sep'attribute:

Bydefaultoutputvaluesareseperatedbyspace.Ifwewantwecanspecifyseperatorbyusing"sep"
attribute. 'sep' means seperator.

In [9]:

a,b,c=10,20,30
print(a,b,c)#102030
print(a,b,c,sep=',')#10,20
,30
print(a,b,c,sep=':')#10:20:30
print(a,b,c,sep='-')#10-20-30
10 20 30
10,20,30
10:20:30
10-20-30

iv. 'end'attribute:

Form-5: print() with 'end'attribute:

In [10]:

print("Hello")
print("Karthi")
print("Sahasra")

Hello
Karthi
Sahasra

If we want output in the same line with space, we need to use end attribute.
defaultvalueof'end'attributeisnewlinecharacter.(Thatmeans,ifthereisnoendattribute,
automatically newline
character will be printed).

In [11]:

print("Hello",end='')
print("Karthi",end='')#ifendisspace character
print("Sahasra")

Hello Karthi Sahasra

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [12]:

print("Hello",end='')
print("Karthi",end='')#ifendisnothing
print("Sahasra")

HelloKarthiSahasr

a In [13]:

print('hello',end='::')
print('karthi',end='****')
print('sahasra')

hello::karthi****sahasra

Eg: Program to demonstrate both 'sep' and 'end'attributes.

In [14]:

print(10,20,30,sep=':',end='***')
print(40,50,60,sep=':')#defaultvalueof'end'attributei
s '\n' print(70,80,sep='**',end='$$')
print(90,100)

10:20:30***40:50:60
70**80$$90 100

Eg :Consider the following case,

In [15]:

print('karthi'+'sahasra')# Concatanation
print('karthi','sahasra')#',' meansspace isthe seperator
print(10,20,30)

karthisahasra
karthi
sahasra
10 20 30

Form-6: print(object) statement:

We can pass any object (like list,tuple,set etc)as argument to the print() statement.

In [16]:

l=[10,20,30,40]
t=(10,20,30,40)
print(l)
print(t)

[10, 20, 30, 40]


(10, 20, 30, 40)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…10/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Form-7: print(String,variable list):

We can use print() statement with String and any number of arguments.

In [17]:

s="Karthi"a
= 6
s1="java"
s2="Python"
print("Hello",s,"YourAgeis",a)
print("Youarelearning",s1,"and",s2)

Hello Karthi Your Age is 6


You are learning java and Python

Form-8: print(formatted string):

%i ====>int

%d ====>int

%f =====>float

%s ======>String type

Syntax:

print("formatted string" %(variable list))

In [18]:

a=1
0
b=2
0
c=3
0
a value is 10
b value is 20 and c value is 30

In [19]:

s="Karthi"
list=[10,20,30,40]
print("Hello%s ...TheList of Itemsare%s"%(s,list))

Hello Karthi ...The List of Items are [10, 20, 30, 40]

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…11/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [20]:

price=70.56789
print('Pricevalue={}'.format(price))
print('Price value = %f'%price)
print('Pricevalue=%.2f'%price)

Price value =
70.56789
Pricevalue=70.567890
Price value = 70.57

v. Replacement Operator ({}):

Form-9: print() with replacement operator { }

In [21]:

name="Karthi"sa
lary=100000
sister="Sahasra"
print("Hello{} your salary is {}and Your Sister{} is waiting"
.format(name,salary,sister))
print("Hello{0}your salary is {1}and Your Sister{2}is waiting"
.format(name,salary,sister))
print("Hello{1}your salary is {2}and Your Sister{0}is waiting"
.format(name,salary,sister))
print("Hello{2}your salary is {0}and Your Sister{1}is waiting"
.format(salary,sister,name))
print("Hello{x}your salary is {y}and Your Sister{z}is waiting"
.format(x=name,y=salary,z=sister))

HelloKarthiyoursalaryis100000andYourSisterSahasraiswaiting
HelloKarthiyoursalaryis100000andYourSisterSahasraiswaiting
Hello100000yoursalaryisSahasraandYourSisterKarthiiswaiting
HelloKarthiyoursalaryis100000andYourSisterSahasraiswaiting
HelloKarthi your salary is 100000 and Your Sister Sahasra is
waiting

In [22]:

a,b,c,d=10,20,30,40#print a=10,b=20,c=30,d=40
print('a={},b ={},c= {},d= {}'.format(a,b,c,d))

a = 10,b = 20,c = 30,d = 40

b) Demonstrate the following Conditional statements in Python with suitable examples.

i) if statement ii) ifelse statement


iii) if – elif – else statement

i) if statement:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…12/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Syntax:

ifconditio
n:
statement 1

statement 2

statement 3

statement

In [23]:

if10<20:
print('10islessthan20')
print('End of Program')

10islessthan20
End of Program

In [24]:

if10<20:
print('10islessthan20')
print('End of Program')

File"<ipython-input-24-f2d3b9a6180e>",line2
print('10 is less than 20')
^
IndentationError:expected an indented block

In [25]:

name=input("EnterName:")
ifname=="Karthi":
print("HelloKarthiGoodMornin
g")
print("How are you!!!")
Enter Name:Karthi
HelloKarthiGoodMornin
g How are you!!!

In [26]:

name=input("EnterName:")
ifname=="Karthi":
print("HelloKarthiGoodMornin
g")
print("How are you!!!")
EnterName:Soura
v How are
you!!!

ii) ifelse statement:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…13/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Syntax:

ifconditio
n:
Action 1

else:

Action 2

if condition is true then Action-1 will be executed otherwise Action-2 will be executed.

In [27]:

name=input('EnterName : ')
ifname=='Karthi':
print('HelloKarthi!Good
Morning')
else:
print('HelloGuest!
GoodMorning') print('How are
Enter Name : Karthi
HelloKarthi!GoodMorning
How are you?

In [29]:

name=input('EnterName : ')
ifname=='Karthi':
print('HelloKarthi!Good
Morning')
else:
print('HelloGuest!
GoodMorning') print('How are
Enter Name : sourav
HelloGuest!
GoodMorning How are
you?

iii) if – elif – else statement :

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Syntax:

Based condition the corresponding action will be executed.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [30]:

brand=input("EnterYourFavouriteBrand:")
ifbrand=="RC":
print("Itischildrens
brand")
elifbrand=="KF":
print("Itis notthat much kick")
elifbrand=="FO":
print("Buyone getFree One")
else:
print("OtherBrands arenot recommended")

EnterYourFavouriteBrand:RC
It is childrens brand

In [31]:

brand=input("EnterYourFavouriteBrand:")
ifbrand=="RC":
print("Itischildrens
brand")
elifbrand=="KF":
print("Itis notthat much kick")
elifbrand=="FO":
print("Buyone getFree One")
else:
print("OtherBrands arenot recommended")
EnterYourFavouriteBrand:FO
Buy one get Free One

In [32]:

brand=input("EnterYourFavouriteBrand:")
ifbrand=="RC":
print("Itischildrens
brand")
elifbrand=="KF":
print("Itis notthat much kick")
elifbrand=="FO":
print("Buyone getFree One")
else:
print("OtherBrands arenot recommended")
Enter Your Favourite
Brand:ABC Other Brands are
not recommended

Points to Ponder:

1. else part is always optional.


2. There is no switch statement in Python.

c) Demonstrate the following Iterative statements in Python with suitable examples.

i) while loop ii)for loop

i) while loop:
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…16/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Ifwewanttoexecuteagroupofstatementsiterativelyuntilsomeconditionfalse,thenweshouldgofor
while loop.

Syntax:

while condition:

body

Eg1: Write a Pythonprogram to print numbersfrom 1 to 10by using while loop.

In [13]:

x=1
whilex<=10:
print(x,end='')
x=x+1

1 2 3 4 5 6 7 8 9 10

Eg2: Write aPython program todisplay the sumof first 'n'numbers.

In [14]:

n=int(input("Enternumber:"
)) sum=0
i=1
whilei<=n:
sum=sum+i
i=i+1
print("Thesumoffirst",n,"numbersis:",sum)

Enter number:10
The sum of first 10 numbers is : 55

Eg 3: write a program to prompt user to enter some name until entering RGM.

In [15]:

name=""
whilename!="RGM":
name=input("EnterName:"
)
print("Thanksforconfirmation")
EnterName:SRE
C Enter
Name:GPR
EnterName:KSR
M
EnterName:AIT
S Enter
Name:RGM
Thanks for confirmation

ii) for loop:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…17/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Ifwewanttoexecutesomeactionforeveryelementpresentinsomesequence(itmaybestringor
collection) then we should go for for loop.

Syntax:

for x in sequence:

body

Where, 'sequence' can be string or any collection.


Body will be executed for every element present in the sequence.

Eg1: Write aPython Program toprint characters presentin the given string.

In [1]:

s="Sahasra"
forxins:
print(x)

S
a

r
s="Sahasra"
a
forxins:
print(x,end='\t')
In [3]:
a s r a

S a h

Eg2:Toprintcharacterspresentinstringindexwise.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…18/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[4]:
s=input("EntersomeString:") i=0
forxins:
print("Thecharacterpresentat",i,"indexis:",x) i=i+1

Enter some String: Karthikeya


The character present at 0 index is : K
The character present at 1 index is : a
The character present at 2 index is : r
The character present at 3 index is : t
The character present at 4 index is : h
The character present at 5 index is : i
The character present at 6 index is : k
The character present at 7 index is : e
The character present at 8 index is : y
The character present at 9 index is : a

Eg3: Writea Python programto printHello 10 times.

In [5]:

s='Hello'
foriinrange(1,11):
print(s)

Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o

In [7]:

s='Hello'
foriinrange(10):
print(s)

Hell
o
Hell
o
Hell
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…19/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[4]:
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o

Eg4: Write aPython program todisplay numbers from0 to 10.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…20/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[8]:
foriinrange(0,11):
print(i,end='')

0 1 2 3 4 5 6 7 8 9 10

Eg5: Write aPython program todisplay odd numbersfrom 0 to 20.

In [9]:

foriinrange(21):
if(i%2!=0):
print(i,end='')

1 3 5 7 9 11 13 15 17 19

Eg6: Write aPython Program to displaynumbers from 10 to1 in descending order.

In [10]:

foriinrange(10,0,-1):
print(i,end='')

10 9 8 7 6 5 4 3 2 1

Eg7: Write aPython program toprint sum ofnumbers presenst inside list.

In [11]:

list=eval(input("EnterList:"
)) sum=0;
forxinlist:
sum=sum+x;
print("The
Sum=",sum)
EnterList:10,20,30,40
The Sum= 100

In [12]:

list=eval(input("EnterList:"
)) sum=0;
for x in list:
sum=sum+x;
print("The Sum=",sum)

EnterList:
[10,20,30,40] The
Sum= 100

Nested Loops:

Sometimes we can take a loop inside another loop,which are also known as nested loops.

Eg 1:
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…21/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [16]:

foriinrange(3):
forjinrange(2):
print('Hello')

Hell
o
Hell
o
Hell
o
Hell
o
Hell
o
Hell
o

Eg 2:

In [17]:

foriinrange(4):
forjinrange(4
):
print('i= {}j = {}'.format(i,j))
i = 0 j = 0
i = 0 j = 1
i = 0 j = 2
i = 0 j = 3
i = 1 j = 0
i = 1 j = 1
i = 1 j = 2
i = 1 j = 3
i = 2 j = 0
i = 2 j = 1
i = 2 j = 2
i = 2 j = 3
i = 3 j = 0
i = 3 j = 1
i = 3 j = 2
i = 3 j = 3

WritePythonPrograms todisplay thebelow patterns.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…22/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…23/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[21]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print("* "*n)

Enter the number of rows: 10


* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…24/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [23]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(i,end="")
print()

Enter the number of rows: 7


1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5
6 6 6 6 6 6 6
7 7 7 7 7 7 7

Pattern-3:

12345

12345

12345

12345

12345

In [24]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(j,end="")
print()

Enter the number ofrows:


5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…25/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…26/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [25]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(chr(64+i),end="")
print()

Enter the number of rows: 10


A A A A A A A A A A
B B B B B B B B B B
C C C C C C C C C C
D D D D D D D D D D
E E E E E E E E E E
F F F F F F F F F F
G G G G G G G G G G
H HHHHHHHH
H
IIIIIIIIII
JJJJJJJJJJ

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…27/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [26]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(chr(64+j),end="")
print()

Enterthenumberofrows:7 A
B C D E F G
ABCDEFG
ABCDEFG
ABCDEFG
ABCDEFG
ABCDEFG A B
C D E F G

n=int(input("Enterthenumberofrows:"))foriinrange(1,n+1):forjinrange(1,n+1):print(n+1-i,end="")
print()

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…28/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [28]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(n+1-j,end="")
print()

Enter the number of rows: 10


10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2 1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…29/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [29]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(chr(65+n-
i),end="") print()

Enterthenumberofrows:10 J
J J J J J J J J J
IIIIIIIIII
HHHHHHHHHH
GGGGGGGGGG
FFFFFFFFFF
EEEEEEEEEE
DDDDDDDDDD
CCCCCCCCCC
BBBBBBBBBB A A A
A A A A A A A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…30/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [30]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+1):
print(chr(65+n-j),end="")
print()

Enterthenumberofrows:10 J
I H G F E D C B A
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA
JIHGFEDCBA J I H
G F E D C B A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…31/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [31]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,i+1):
print("*",end="")
print()

Enter the number ofrows:


* 5
* *
* * *
* * * *
* * * * *

AlternativeWay:

In [32]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print("* "*i)

Enter the number of rows:5


*
* *
* * *
* * * *
* * * * *

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…32/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [34]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,i+1):
print(i,end="")
print()

Enterthenumberofrows:9 1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…33/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[36]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,i+1): print(i,end="\
t") print()

Enter the number of


rows: 10
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…34/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[37]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,i+1
):
print(j,end="
") print()

Enterthenumberofrows:10 1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9
10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…35/83
06/06/2021 PythonProgramming Lab Manual - RGMCET(Autonomous)

In [38]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,i+1
):
print(chr(64+i),end="
") print()

Enterthenumberofrows:10 A
B B
C C C
D D D D
E E E E E
F F F F F F
G G G G G G G
H H H H H H H H
I I I I I I I I
I J J J J J J J J
J J

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…36/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[39]:
n=int(input("Enterthenumberofrows:
"))
foriinrange(1,n+1):
forjinrange(1,i+1):
print(chr(64+j),end="")
print()

Enterthenumberofrows:1
0 A A B
A B C
A B C
D
A B C D
E A B C D
E F
A B C D E F
G A B C D E F
G H
A B C D E F G H
I A B C D E F G H
I J

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…37/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[40]:
n=int(input("Enterthenumberofrows:
"))
foriinrange(1,n+1):
forjinrange(1,n+2-i):
print("*",end="")
print()

Enter the number of rows: 10


* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…38/83
06/06/20 PythonProgramming Lab Manual -
21 RGMCET(Autonomous)

In
[41]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(i,end="
") print()

Enter the number of rows: 10


1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6
7 7 7 7
8 8 8
9 9
10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…39/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[42]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(j,end="
") print()

Enter the number of rows: 10


1 2 3 4 5 6 7 8 9
10
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…40/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [43]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(chr(64+i),end="
") print()

Enter the number of rows: 10


A A A A A A A A A A
B B B B B B B B B
C C C C C C C C
D D D D D D D
E E E E E E
F F F F F
G G G G
H H
H II
J

In [44]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(chr(64+j),end="
") print()

Enterthenumberofrows:7
A B C D E F G
ABCDEF A
B C D E
ABCD A
B
C
AB
A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…41/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [45]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(n+1-i,end="")
print()

Enter the number of rows: 9


9 9 9 9 9 9 9 9 9
8 8 8 8 8 8 8 8
7 7 7 7 7 7 7
6 6 6 6 6 6
5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…42/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [46]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(n+1-j,end="")
print()

Enter the number of rows: 10


10 9 8 7 6 5 4 3 2 1
10 9 8 7 6 5 4 3 2
10 9 8 7 6 5 4 3
10 9 8 7 6 5 4
10 9 8 7 6 5
10 9 8 7 6
10 9 8 7
10 9 8
10 9
10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…43/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [1]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(chr(65+n-i),end="")
print()

Enterthenumberofrows:10
J J J J J J J J J J
IIIIIIIII H H H
H H H H H
GGGGGGG F F
F F F F
EEEEE D
D D D
C C C
BB
A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…44/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [2]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
forjinrange(1,n+2-
i):
print(chr(65+n-j),end="")
print()

Enterthenumberofrows:10
J I H G F E D C B A
JIHGFEDCB J I H
G F E D C
JIHGFED J I
H G F E
JIHGF J
I H G
J I H
JI
J

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…45/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [5]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),"*"*i,end="") print()

Enter the number of rows: 5


*
**
***
****
*****

In [6]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),"*"*i,end="") print()

Enter the number of rows: 5


*
* *
* * *
* * * *
* * * * *

AlternativeWay:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…46/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
n=int(input("Enterthenumberofrows:
foriinrange(1,n+1):
"))
print(""*(n-i),end="")
forjinrange(1,i+1):
print("*",end="")
print()

Enter the number of rows: 5


*
* *
* * *
* * * *
* * * * *

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…47/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [8]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),(str(i)+"")*i)
print()

Enterthenumberofrows:8 1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

6 6 6 6 6 6

7 7 7 7 7 7 7

8 8 8 8 8 8 8 8

Another Pattern:

In [9]:

n=int(input("Enter thenumber ofrows: "))


foriinrange(1,n+1):
print(''*(n-i),((str(i))*i))
print()

Enterthenumberofrows:5 1

22

333

4444

55555

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…48/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…49/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[10]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="") for j in
range(1,i+1):
print(j,end="
") print()

Enter the number of rows: 10


1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…50/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[11]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),(chr(64+i)+"")*i)
print()

Enterthenumberofrows:8 A

B B

C C C

D D D D

E E E E E

F F F F F F

G G G G G G G

H H H H H H H H

In [14]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),str(i)*(n+1-i))

Enterthenumberofrows:5 11111
2222
333
44
5

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…51/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),str(n+1-i)*(n+1-i))

Enterthenumberofrows:5 55555
4444
333
22
1

In [12]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),(str(n+1-i)+"")*(n+1-i))

Enter the number ofrows:


5 5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

In [16]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-
1),end="")
forjinrange(1,n+2-
i):
print(j,end="")
print()

Enter the number of rows: 5


1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…52/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [17]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-
1),end='')
forjinrange(1,n+2-
i):
print(j,end="")
print()

Enterthenumberofrows:5 12345
1234
123
12
1

In [18]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),(str(chr(65+n-i))+"")*(n+1-i))

Enterthenumberofrows:5
E E E E E
DDDD
C C C
BB
A

In [19]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),(str(chr(65+n-i)))*(n+1-i))

Enterthenumberofrows:5
EEEEE DDDD
CC
C
B
B
A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…53/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [20]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-
1),end="")
forjinrange(65,66+n-
i):
print(chr(j),end="")
print()

Enterthenumberofrows:5
A B C D E
ABCD
A B C
AB
A

In [21]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-
1),end="")
forjinrange(65,66+n-
i):
print(chr(j),end="
") print()

Enterthenumberofrows:5
ABCDE ABCD
AB
C
A
B
A

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…54/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [23]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),str(i)*(2*i-1))

Enterthenumberofrows:5 1
222
33333
4444444
555555555

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…55/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [24]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),(str(chr(64+i)))*(2*i-1))

Enterthenumberofrows:5
A BBB
CCCCC
DDDDDDD
EEEEEEEE
E

In [25]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),(str(chr(64+2*i-1)))*(2*i-1))

Enterthenumberofrows:5
A CCC
EEEEE
GGGGGGG
IIIIIIII
I

In [26]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),(str(chr(64+3*i-1)))*(2*i-1))

Enterthenumberofrows:5
B EEE
HHHHH
KKKKKKK
NNNNNNNN
N

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…56/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [28]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="") for j in
range(1,2*i):
print(j,end="
") print()

Enterthenumberofrows:5 1
123
12345
1234567
123456789

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…57/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [29]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),end="")
forjinrange(2*i-1,0,-
1):
print(j,end=""
) print()

Enterthenumberofrows:5 1
321
54321
7654321
987654321

Few more similar patterns:

In [31]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(2*i,1,-
1):
print(j,end=""
) print()

Enterthenumberofrows:5 2
432
65432
8765432
1098765432

In [32]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(2*i,0,-
1):
print(j,end=""
) print()

Enterthenumberofrows:5 21
4321
654321
87654321
10987654321

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…58/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [33]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-i),end="")
forjinrange(65,65+2*i-
1):
print(chr(j),end="
") print()

Enterthenumberofrows:5
A ABC
ABCDE
ABCDEFG
ABCDEFGH
I

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…59/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [34]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(65+2*i-2,64,-1):
print(chr(j),end="")
print()

Enterthenumberofrows:5
A CBA
EDCBA
GFEDCBA
IHGFEDCB
A

In [37]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="") for j in
range(1,i):
print(i-j,end="")
forkinrange(0,i):
print(k,end=""
)
print()

Enterthenumberofrows:5 0
101
21012
3210123
432101234

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…60/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [38]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(1,i):
print(chr(i-j+65),end="")
forkinrange(0,i):
print(chr(k+65),end="
")
print()

Enterthenumberofrows:5
A BAB
CBABC
DCBABCD
EDCBABCD
E

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…61/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [39]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="") for j in
range(1,i+1):
print(j,end="")
forkinrange(i-1,0,-1):
print(k,end=""
) print()

Enterthenumberofrows:5 1
121
12321
1234321
123454321

In [41]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(1,i+1):
print(chr(64+j),end="")
forkinrange(1,i):
print(chr(64+k),end="
")
print()

Enterthenumberofrows:5
A ABA
ABCAB
ABCDABC
ABCDEABC
D

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…62/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Pattern 46:

In [42]:

n=int(input("Enteranumber:"))
foriinrange(1,n+1):
print(""*(n-
i),end="") for j in
range(1,i+1):
print(n+1-j,end="")
print()

Enteranumber:5 5
54
543
5432
54321

In [44]:

n=int(input("Enteranumber:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(1,i+1):
print(n-j+1,end="")
print()

Enteranumber:5 5
5 4
5 4 3
5 4 3 2
5 4 3 2 1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…63/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Pattern 47:

In [45]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(1,num+2-
i):
print("*",end="")
forkinrange(1,num+1-i):
print("*",end="")
print()

Enter a number:5
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*

In [47]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(1,num+2-
i):
print("*",end="")
forkinrange(1,num+1-i):
print("*",end="")
print()

Enter a number:5
*********
*******
*****
***
*

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…64/83
06/06/20 Python Programming Lab Manual -
21 AlternativeWay: RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…65/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[48]:
num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(1,num+2-
i):
print("*",end="")
print()

Enter a number:5
* * * * *
* * * *
* * *
* *
*

Pattern 48:

In [49]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(0,num+1-
i):
print(num+1-i,end="")
forkinrange(1,num+1-
i): print(num+1-
i,end="")
print()

Enteranumber:5
555555555
4444444
33333
222
1

Simi;ar type Patterns:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…66/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [50]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(0,num+2-
i):
print(num+1-i,end="")
forkinrange(1,num-
i+1): print(num+1-
i,end="")
print()

Enteranumber:5
5555555555
44444444
333333
2222
11

Pattern 49:

In [51]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(0,num+1-
i):
print(2*num+1-2*i,end="")
forkinrange(1,num+1-i):
print(2*num+1-
2*i,end="")
print()

Enteranumber:5
999999999
7777777
55555
333
1

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…67/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Pattern 50:

In [52]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(1,num+2-
i):
print(j,end="")
forkinrange(2,num+2-
i): print(num+k-
i,end="")
print()

Enteranumber:5
123456789
1234567
12345
123
1

d) Demonstrate the following control transfer statements in Python with suitable examples.

i) break ii) continue iii)pass

i) break:

Wecan use breakstatement inside loops tobreak loop executionbased on some condition.

In [3]:

foriinrange(10):
ifi==7:
print("processingisenough..plz break")
break
print(i)

0
1
2
3
4
5
6
processing is enough..plz break

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…68/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[4]:
cart=[10,20,600,60,70]
foritemincart
:
ifitem>500
:
print("Toplace this orderinsurence must be required")
break
print(item)

10
20
To place this order insurence must be required

ii) continue:

Wecan use continuestatement to skipcurrent iteration andcontinue next iteration.

Eg1: Write aPython program to printodd numbers in therange 0 to 9.

In [5]:

foriinrange(10):
ifi%2==0:
continue
print(i)

1
3
5
7
9

Eg 2:

In [6]:

cart=[10,20,500,700,50,60]
foritemincart:
ifitem>=500
:
print("Wecannot processthis item :",item)
continue
print(item)

10
20
Wecannotprocessthisitem:500
Wecannotprocessthisitem:700
50
60

Eg 3:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…69/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [7]:

numbers=[10,20,0,5,0,30]
forninnumber
s:
ifn==0:
print("Heyhow we candivide with zero..just skipping")
continue
print("100/{}={}".format(n,100/n))

100/10 = 10.0
100/20 = 5.0
Heyhowwecandividewithzero..justskipping 100/5
= 20.0
Heyhowwecandividewithzero..justskipping 100/30
= 3.3333333333333335

Loops with else block:

Insideloopexecution,ifbreakstatementnotexecuted,thenonlyelsepartwillbeexecut
ed. else means loop without break.

In [9]:

cart=[10,20,30,40,50]
foritemincart:
ifitem>=500
:
print("Wecannot processthis order")
break
print(item)
else:
print("Congrats...all itemsprocessed successfully")

10
20
30
40
50
Congrats ...all items processed successfully

In [11]:

cart=[10,20,600,30,40,

50]
foritemincart:
ifitem>=500
:
print("Wecannot processthis order")
break
print(item)
else:
print("Congrats...all itemsprocessed successfully")

10
20
We cannot process this order

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…70/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)
iii) pass:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…71/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

pass is a keyword in Python.


Inourprogrammingsyntacticallyifblockisrequiredwhichwon'tdoanythingthenwecandefineth
at empty block with pass keyword.
pass statement ==>

1. It is an empty statement

2. It is null statement

3. It won't do anything

In [12]:

ifTrue:# It is invalid

File"<ipython-input-12-2d7926e5e65a>",line1
if True: # It is invalid
^
SyntaxError:unexpected EOF while parsing

In [13]:

ifTrue:
pass# It is valid

In [14]:

defm1():# It is invalid

File"<ipython-input-14-55805493e471>",line1
def m1(): # It is invalid
^
SyntaxError:unexpected EOF while parsing

In [15]:

defm1():
pass# It is valid

Use of pass:

Sometimes in the parent class we have to declare a function with empty body and child
class
responsibletoprovideproperimplementation.Suchtypeofemptybodywecandefinebyusingpas
s keyword. (It is something like abstract method in java).

Example:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…72/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [16]:

foriinrange(100
): ifi
%9==0:
print(i)
else:
pass

0
9
18
27
36
45
54
63
72
81
90
99

More example programs on all the above concepts:

Q1.Write aprogram to findbiggest ofgiven 2 numbers.

In [33]:

n1=int(input("Enter First
Number:"))
n2=int(input("EnterSecondNumber:"
)) if n1>n2:
print("BiggestNumberis:",n1)
else:
print("BiggestNumberis:",n2)

Enter First Number:10


EnterSecondNumber:20
Biggest Number is: 20

Q2.Write aprogram to findbiggest ofgiven 3 numbers.

In [34]:

n1=int(input("Enter First
Number:"))
n2=int(input("EnterSecondNumber:"
)) n3=int(input("Enter Third
Number:")) if n1>n2 and n1>n3:
print("BiggestNumberis:",n1)
elifn2>n3:
print("BiggestNumberis:",n2)
else:
print("BiggestNumberis:",n3)

Enter First Number:10


EnterSecondNumber:20
Enter Third Number:35
Biggest Number is: 35
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…73/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Q3.Write aprogram to findsmallest ofgiven 2 numbers?

In [35]:

n1=int(input("Enter First
Number:"))
n2=int(input("EnterSecondNumber:"
)) if n1>n2:
print("SmallestNumberis:",n2)
else:
print("SmallestNumberis:",n1)

Enter First Number:35


EnterSecondNumber:44
Smallest Number is:
35

Q4.Write aprogram to findsmallest ofgiven 3 numbers?

In [36]:

n1=int(input("Enter First
Number:"))
n2=int(input("EnterSecondNumber:"
)) n3=int(input("Enter Third
Number:")) if n1<n2 and n1<n3:
print("SmallestNumberis:",n1)
elifn2<n3:
print("SmallestNumberis:",n2)
else:
print("SmallestNumberis:",n3)

Enter First
Number:100
EnterSecondNumber:350
Enter Third
Number:125 Smallest
Number is: 100

Q5.Write a programto check whetherthe given numberis even or odd?

In [37]:

n1=int(input("EnterFirstNumber:")
) rem = n1 % 2
ifrem==0:
print('EnteredNumber isan Even Number')
else:
print('EnteredNumber isan Odd Number')

Enter First Number:34


Entered Number is an Even Number

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…74/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[39]:
n1=int(input("EnterFirstNumber:")
) rem = n1 % 2
ifrem==0:
print('EnteredNumber isan Even Number')
else:
print('EnteredNumber isan Odd Number')

Enter First Number:33


Entered Number is an Odd Number

Q6.Write a programto check whether thegiven number is inbetween 1 and 100?

In [40]:

n=int(input("EnterNumber:"))
ifn>=1andn<=100:
print("Thenumber",n,"isinbetween1to100")
else:
print("Thenumber",n,"isnotinbetween1to 100")

Enter Number:45
The number 45 is in between 1 to 100

In [41]:

n=int(input("EnterNumber:"))
ifn>=1andn<=100:
print("Thenumber",n,"isinbetween1to100")
else:
print("Thenumber",n,"isnotinbetween1to 100")

Enter Number:123
The number 123 is not in between 1 to 100

Q7.Writeaprogramtotakeasingledigitnumberfromthekeyboardandprintit'svalueinEnglish word?

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…75/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[42]:
n=int(input("Enteradigitfromoto9:"))
ifn==0:
print("ZERO")
elifn==1:
print("ONE")
elifn==2:
print("TWO")
elifn==3:
print("THREE")
elifn==4:
print("FOUR")
elifn==5:
print("FIVE")
elifn==6:
print("SIX")
elifn==7:
print("SEVEN")
elifn==8:
print("EIGHT")
elifn==9:
print("NINE")
else:
print("PLEASEENTER A DIGITFROM 0 TO 9")

Enteradigitfromoto9:8 EIGHT

In [43]:

n=int(input("Enteradigitfromoto9:"))
ifn==0:
print("ZERO")
elifn==1:
print("ONE")
elifn==2:
print("TWO")
elifn==3:
print("THREE")
elifn==4:
print("FOUR")
elifn==5:
print("FIVE")
elifn==6:
print("SIX")
elifn==7:
print("SEVEN")
elifn==8:
print("EIGHT")
elifn==9:
print("NINE")
else:
print("PLEASEENTER A DIGITFROM 0 TO 9")

Enter a digit from o to 9:10


PLEASE ENTER A DIGIT FROM 0
TO 9

AnotherWayofwritingprogramforthesamerequirement:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…76/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[44]:
list1=['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT','NINE']
n=int(input('Enteradigitfrom0to9:'))

print(list1[n]) Enteradigitfrom0to9:7 SEVEN

In [45]:

list1=['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT',

'NINE']
n=int(input('Enteradigitfrom0to9:')) print(list1[n])

Enter a digit from 0 to 9 :15

--------------------------------------------------------------------------
-
IndexError Traceback(mostrecentcalllas t)
<ipython-input-45-bbd0655ae62d>in<module>
1 list1=['ZERO','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVE
N','E IGHT','NINE']
2 n=int(input('Entera digitfrom0 to9 :'))
----> 3print(list1[n])

IndexError:list index out of

range

How can you extend the above program from 0 to 99?

In [47]:

words_upto_19=['','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIG

HT',
'NINE','TEN','ELEVEN','TWELVE','THIRTEEN','FOURTEEN','FIF
TEEN', 'SIXTEEN','SEVENTEEN','EIGHTEEN','NINETEEN']
words_for_tens=['','','TWENTY','THIRTY','FORTY','FIFTY','SIXTY','SEVENTY',
'EIGHTY','NINETY']
n=int(input('Enteranumberfrom0to99:')) output = ''
ifn==0:
output='ZERO'
elifn<=19:
output=words_upto_19[n]
elifn<=99:
output=words_for_tens[n//10]+''+words_upto_19[n%10]
else:
output='PleaeEnteravaluefron0to99only'print(output)

Enteranumberfrom0to99:0 ZERO

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…77/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[48]:
words_upto_19=['','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT',
'NINE','TEN','ELEVEN','TWELVE','THIRTEEN','FOURTEEN','FIF
TEEN', 'SIXTEEN','SEVENTEEN','EIGHTEEN','NINETEEN']
words_for_tens=['','','TWENTY','THIRTY','FORTY','FIFTY','SIXTY','SEVENTY',
'EIGHTY','NINETY']
n=int(input('Enteranumberfrom0to99:')) output = ''
ifn==0:
output='ZERO'
elifn<=19:
output=words_upto_19[n]
elifn<=99:
output=words_for_tens[n//10]+''+words_upto_19[n%10]
else:
output='PleaeEnteravaluefron0to99only'print(output)

Enteranumberfrom0to99:9 NINE

In [49]:

words_upto_19=['','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT',
'NINE','TEN','ELEVEN','TWELVE','THIRTEEN','FOURTEEN','FIF
TEEN', 'SIXTEEN','SEVENTEEN','EIGHTEEN','NINETEEN']
words_for_tens=['','','TWENTY','THIRTY','FORTY','FIFTY','SIXTY','SEVENTY',
'EIGHTY','NINETY']
n=int(input('Enteranumberfrom0to99:')) output = ''
ifn==0:
output='ZERO'
elifn<=19:
output=words_upto_19[n]
elifn<=99:
output=words_for_tens[n//10]+''+words_upto_19[n%10]
else:
output='PleaeEnteravaluefron0to99only'print(output)

Enteranumberfrom0to99:1
9 NINETEEN

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…78/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[50]:
words_upto_19=['','ONE','TWO','THREE','FOUR','FIVE','SIX','SEVEN','EIGHT',
'NINE','TEN','ELEVEN','TWELVE','THIRTEEN','FOURTEEN','FIF
TEEN', 'SIXTEEN','SEVENTEEN','EIGHTEEN','NINETEEN']
words_for_tens=['','','TWENTY','THIRTY','FORTY','FIFTY','SIXTY','SEVENTY',
'EIGHTY','NINETY']
n=int(input('Enteranumberfrom0to99:')) output = ''
ifn==0:
output='ZERO'
elifn<=19:
output=words_upto_19[n]
elifn<=99:
output=words_for_tens[n//10]+''+words_upto_19[n%10]
else:
output='PleaeEnteravaluefron0to99only'print(output)

Enteranumberfrom0to99:56
FIFTY SIX

Q8.Pythonprogramtofindallprimenumberswithinagivenrange. Theory:

Prime numbers:

A prime number is a natural number greater than 1 and having no positive divisor other than
1 and itself.

Forexample:3,7,11etcareprime numbers.

Compositenumber:Othernaturalnumbersthatarenotprimenumbersarecalledcompositenu

mbers. For example: 4, 6, 9 etc. are composite numbers.

Hereis source code of the Python Program to check if a number is a prime number.

In [24]:

r=int(input("EnterRange:"))
forainrange(2,r+1): k=0
foriinrange(2,a//
2+1): if(a
%i==0):
k=k+1
if(k<=0):
print(a)

Enter Range: 20
2
3
5
7
11
13
17
19

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…79/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[25]:
r=int(input("EnterRange:"))
forainrange(2,r+1): k=0
foriinrange(2,a//
2+1): if(a
%i==0):
k=k+1
if(k<=0):
print(a,end='')

Enter Range: 20
2 3 5 7 11 13 17 19

Q9.Pythonprogramtoprint‘n'termsofFibonacciseriesofnumbers.

Theory:

A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....


Thefirsttwotermsare0and1.Allothertermsareobtainedbyaddingtheprecedingtwoterms.This
means to say the nth term is the sum of (n-1)th and (n-2)th term.

In [27]:

n=int(input("Howmanyterms? "))
# first two terms
n1=
0
n2=
1
count=0
# check if the number of terms is valid
ifn<=0:
print("Pleaseenter apositive integer")
elifn==1:
print("Fibonaccisequenceupto",n,":")
print(n1)
else:
print("Fibonaccisequenceupto",n,":")
whilecount<n:
print(n1,end=''
) next = n1 +
n2
# update values
n1=n2
n2 = next
count+=1

How many terms? 20


Fibonacci sequence upto 20 :
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…80/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[28]:
n=int(input("Howmanyterms? "))
# first two terms
n1=
0
n2=
1
count=0
# check if the number of terms is valid
ifn<=0:
print("Pleaseenter apositive integer")
elifn==1:
print("Fibonaccisequenceupto",n,":")
print(n1)
else:
print("Fibonaccisequenceupto",n,":")
whilecount<n:
print(n1,end=''
) next = n1 +
n2
# update values
n1=n2
n2 = next
count+=1

How many terms? 10


Fibonacci sequence upto 10 :
0 1 1 2 3 5 8 13 21 34

Q10.WriteaPythonprogramtocomputedistancebetweentwopointstakinginputfromtheuser (Pythagorean
Theorem).

In [30]:

importmath;
x1=int(input("Enterx1---
>"))
y1=int(input("Entery1--->"))
x2=int(input("Enterx2--->"))
y2=int(input("Entery2--->"))
d1=(x2-x1)*(x2-x1);
d2=(y2-y1)*(y2-y1); res =
math.sqrt(d1+d2)
print("Distance between two points:",res);

Enter x1---
>5
Entery1---
>10
Enterx2---
>15 Enter
y2--->20
Distance between two points: 14.142135623730951

Q11.WriteaPythonprogramtocomputetheGCDoftwonumbers.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…81/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[32]:
defgcd(a,b):
if(b==0):
return
a else:
returngcd(b,a%b)
a=int(input("Enter first
number:"))
b=int(input("Entersecondnumber:"))
print (gcd(a,b))

Enter first number:5


Entersecondnumber:15
5

Q12.Write aPython program tofind the exponentiationof a number.

In [34]:

num=int(input("Enteranumber:
"))
exp=int(input("Enteranumber:
")) res=num
foriinrange(1,exp
): res=num*res
print("Exponent",res)

Enteranumber:
3
Enteranumber:
4 Exponent
81

Q13.Acashierhascurrencynotesofdenominations10,50and100.Iftheamounttobewithdrawnis input
through the keyboard in hundreds, write a Python program find the total number of currency notes of
each denomination the cashier will have to give to the withdrawer.

In [4]:

Amount=int(input("Please EnterAmount forWithdraw :"))

print("\n\nRequirednotes of100 is :",Amount//100) # Floor Division


print("Required notes of 50is : ",(Amount%100)//50)
print ("Required notes of 10 is : ", (((Amount % 100) % 50) // 10))
print("Amountstillremainingis:",(((Amount%100)%50)%10))

Please Enter Amount for Withdraw :1575

Requirednotesof100is:15
Required notes of 50 is :1
Required notes of 10 is :2
Amount still remaining is :5

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…82/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[5]:
Amount=int(input("Please EnterAmount forWithdraw :"))

print("\n\nRequirednotes of100 is :",Amount//100) # Floor Division


print("Required notes of 50is : ",(Amount%100)//50)
print ("Required notes of 10 is : ", (((Amount % 100) % 50) // 10))
print("Amountstillremainingis:",(((Amount%100)%50)%10))

Please Enter Amount for Withdraw :0

Requirednotesof100is:0
Required notes of 50 is
:0
Required notes of 10 is :0
Amount still remaining is :0

In [6]:

Amount=int(input("Please EnterAmount forWithdraw :"))

print("\n\nRequirednotes of100 is :",Amount//100) # Floor Division


print("Required notes of 50is : ",(Amount%100)//50)
print ("Required notes of 10 is : ", (((Amount % 100) % 50) // 10))
print("Amountstillremainingis:",(((Amount%100)%50)%10))

Please Enter Amount for Withdraw :100456

Requirednotesof100is:1004
Required notes of 50 is :1
Required notes of 10 is :0
Amount still remaining is :6

Q14. Python Program to calculate overtime pay of 10 employees. Overtime is paid at the rate of Rs.
12.00perhourforeveryhourworkedabove40hours.Assumethatemployeesdonotworkfor fractional part
of an hour.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…83/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
overtime_pay=0
foriinrange(10): print("\
nEnterthetimeemployeeworkedinhr")
time_worked = int(input())
if(time_worked>40):
over_time=time_worked-40
overtime_pay=overtime_pay+(12*over_time)
print("\ Overtime Pay Of 10 EmployeesIs
nTotal ",overtime_pay)
Enterthetime employe worked in hr
45 e

Enterthetime employe worked in hr


42 e

Enterthetime employe worked in hr


43 e

Enterthetime employe worked in hr


44 e

Enterthetime employe worked in hr


50 e

Enterthetime employe worked in hr


53 e

Enterthetime employe worked in hr


42 e

Enterthetime employe worked in hr


66 e

Enterthetime employe worked in hr


44 e

Enterthetime employe worked in hr


33 e

Total Overtime Pay Of 10 Employees Is828

Q15.Alibrarychargesafineforeverybookreturnedlate.Forfirstfivedaysthefineis50paise,for6 to 10 days
fine is one rupee, and above 10 days fine is five rupees. If you return the book after 30 days your
membership will be cancelled. Write a Python program to accept the number of days the member is
late to return the book and display the fine or the appropriate message.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…84/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[16]:
days=int(input("Enter Numberof Days: "))

if((days>0)and(days<=5)): fine
= 0.5 * days
elif((days>5)and(days<=10))
: fine = 1 * days
elif((days>10)):
fine=5*days
if(days>30):
print('YourMembershipCancelled!!
!') print('You have to pay
Rs.',fine)

Enter Number of Days : 45


YourMembershipCancelled!!!
You have to pay Rs. 225

In [17]:

days=int(input("Enter Numberof Days: "))

if((days>0)and(days<=5)): fine
= 0.5 * days
elif((days>5)and(days<=10))
: fine = 1 * days
elif((days>10)):
fine=5*days
if(days>30):
print('YourMembershipCancelled!!
!') print('You have to pay
Rs.',fine)

EnterNumberofDays:6
You have to pay Rs. 6

In [18]:

days=int(input("Enter Numberof Days: "))

if((days>0)and(days<=5)): fine
= 0.5 * days
elif((days>5)and(days<=10))
: fine = 1 * days
elif((days>10)):
fine=5*days
if(days>30):
print('YourMembershipCancelled!!
!') print('You have to pay
Rs.',fine)

EnterNumberofDays:1
You have to pay Rs.
0.5

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…85/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [19]:

days=int(input("Enter Numberof Days: "))

if((days>0)and(days<=5)): fine
= 0.5 * days
elif((days>5)and(days<=10))
: fine = 1 * days
elif((days>10)):
fine=5*days
if(days>30):
print('YourMembershipCancelled!!
!') print('You have to pay
Rs.',fine)

EnterNumberofDays:12
You have to pay Rs. 60

Q16.Twonumbersareenteredthroughkeyboard,WriteaPythonprogramtofindthevalueofone number
raised to the power another.

In [20]:

importmath
n1=int(input("Please entera number: "))
exp=int(input("Pleaseenterexponentvalue:")) power

= math.pow(n1,exp)

print('Theresult of{}power{}

={}'.format(n1,exp,power)) Please enter a number :

3
Pleaseenterexponentvalue:4
The result of 3 power 4 =
81.0

VivaQuestions:

Q 1. What is the difference between for loop and while loop in Python?

Wecanuse loopsto repeatcode execution.


Repeat code for every item in sequence ==>for loop
Repeatcodeaslongasconditionistrue==>whileloop

Q 2. How to exit from the loop?

by using break statement.

Q 3. How to skip some iterations inside loop?

by using continue statement.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…86/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)
Q4. When else part will be executed with respect to loops?

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…87/83
06/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

If loop executed without break.

GOOD LUCK

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…88/83
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 4:

WritePythonprograms toprint thefollowing Patterns.

i)

In [1]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(n-
i),end="")
forjinrange(1,i+1):
print(chr(64+j),end="")
print()
Enterthenumberofrows:5
A A B
A B C
A B C
D
A B C D E

ii)

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 1/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [3]:

n=int(input("Enterthenumberofrows:"))
foriinrange(1,n+1):
print(""*(i-1),"*"*(n+1-i))

Enter the number of rows: 5


*****
****
***
**
*

iii)

In [6]:

num=int(input("Enterthenumberofrows:"))
foriinrange(1,num+1):
print(""*(i-
1),end="")
forjinrange(1,num+2-
i):
print(chr(65+num-i),end="")
forkinrange(2,num+2-i):
print(chr(65+num-
Enterthenumberofrows:5
E E E E E E E E E
DDDDDDD C C
C C C
BBB A

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 2/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

iv
)

In [7]:

num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(num-
i),end="")
forjinrange(1,i+1):
print(num-j,end="")
print()
for k in range(1,num):
print(""*k,end="")
forlinrange(1,num+1-
k):
print(num-l,end="")
Enteranumber:5 4
4 3
4 3 2
4 3 2 1
4 3 2 1 0
4 3 2 1
4 3 2
4 3
4

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 3/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

v)

In [8]:
num=int(input("Enteranumber:"))
foriinrange(1,num+1):
forjinrange(1,i+1):
print(num-i+j-1,end="")
print()
forainrange(1,num+1):
forkinrange(0,num-
a):
print(k+a,end="")
print()
Enteranumber:5 4
3 4
2 3 4
1 2 3 4
0 1 2 3 4
1 2 3 4
2 3 4
3 4
4

vi)

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 4/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[16]:
num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(num-
i),end="")
forjinrange(1,i+1):
print("*",end="")
print(""*(num-
i),end="")
forkinrange(1,i+1):
print("*",end="")
Enter a number:5
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * * *

vii)

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 5/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[17]:
n=int(input("Enteranumber"))
foriinrange(1,2*n+1): ifi
%2==0:
print("*"*i,end="")
else:
print("*"*(i+1),end="")
print()

Enter a number5
**
**
****
****
******
******
********
********
**********
**********

viii)

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 6/


RGMCET(Autono… 7
04/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[18]:
num=int(input("Enteranumber:"))
foriinrange(1,num+1):
print(""*(num-
i),end="")
forjinrange(0,i):
print(chr(65+num+j-i),end="")
print()
for k in range(1,num):
print(""*k,end="")
forlinrange(0,num-
k):
print(chr(65+k+l),end=""
Enteranumber:5
E D E
C D E
B C D
E
A B C D E
B C D E
C D
E
DE
E

localhost:8892/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 7/


RGMCET(Autono… 7
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Experiment 5:

a) Writea Pythonprogram to demonstratevarious ways ofaccessing the string.

i) By using Indexing (Both Positive and Negative)

ii) By using Slice Operator

What is String?

Any sequence of characters within either single quotes or double quotes is considered as a
String.

Syntax:

s='karthi'

s="karthi"

Note:

InmostofotherlangugeslikeC,C++,Java,asinglecharacterwithinsinglequotesistreatedaschar
data type value. But in Python we are not having char data type.Hence it is treated as
String only.

In [1]:
ch='a'
print(type(ch)
)
<class 'str'>

How to access characters of a String?

Wecan accesscharacters of astring by usingthe following ways.

1. By using index

2. By using slice operator

1. 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).

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…1/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In [2]:

s='Karthi'print(s[0
])
print(s[5])
print(s[-1])
print(s[19])

K
i
i

--------------------------------------------------------------------------
-
IndexError Traceback(mostrecentcalllas t)
<ipython-input-2-d39a6b459de8>in<module>
3 print(s[5])
4 print(s[-1])
----> 5print(s[19])

IndexError:string index out of

range

Eg:Q1.Writeaprogramtoacceptsomestringfromthekeyboardanddisplayitscharactersbyindex wise(both
positive and negative index).

In [6]:

s=input("EnterSomeString:"
) i=0
forxins:
print("Thecharacterpresentatpositiveindex{}andatnegativeindex{}is
{}".f ormat(i,len(s)-i,s[i]))
i=i+1

Enter Some String:RGMCET


The character present at positive index 0 and at negative index 6 is R
The character present at positive index 1 and at negative index 5 is G
The character present at positive index 2 and at negative index 4 is M
The character present at positive index 3 and at negative index 3 is C
The character present at positive index 4 and at negative index 2 is E
The character present at positive index 5 and at negative index 1 is T

2. Accessing characters by using slice operator:

string slice means a part of the string (i.e, Sub string).

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…2/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Syntax:

string_Name [beginindex:endindex:step]

Here,

i. beginindex: From where we have to consider slice(substring)

ii. endindex:We haveto terminatethe slice(substring)at endindex-1

iii.step: incremented / decremented value

Note:

Slicing operator returns the sub string form beginindex to endindex - 1


Ifwearenotspecifyingbeginindexthenitwillconsiderfrombeginningofthestring
. If we are not specifying end index then it will consider up to end of the
string.
step is
The default value for
1

In [7]:
s='abcdefghijk'prin
t(s[2:7])

cdefg

In
s='abcdefghijk'prin
[8]:
t(s[:7])

abcdef

s='abcdefghijk'prin
g In
t(s[2:])

[9]:

cdefghij

k In

s='abcdefghijk'prin
[10]:
t(s[:])

abcdefghij

k In [11]:

s='abcdefghijk'prin
t(s[2:7:1])
localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -
RGMCET(Autonomous).ipynb?do…3/24
07/06/20 Python Programming Lab Manual E5 -
21 cdefg RGMCET(Autonomous)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…4/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[12]:
s='abcdefghijk'prin
t(s[2:7:2])

ceg

In [13]:

s='abcdefghijk'prin
t(s[2:7:3])

cf

In [14]:

s='abcdefghijk'prin
t(s[::1])

abcdefghij

k In [15]:
s='abcdefghijk'prin
t(s[::2])

acegik

In
s='abcdefghijk'prin
t(s[::3])
[16]:

adgj
s="LearningPythonisveryveryeasy!!!"s[1
:7: 1]
In [17]:

Out[17]:

'earnin'

In [18]:

s="LearningPythonisveryveryeasy!!!"s[1:7]

Out[18]:

'earnin'

In [19]:

s="LearningPythonisveryveryeasy!!!"s[1
:7: 2]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…5/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[12]:
Out[19]:

'eri'

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…6/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[20]:
s="LearningPythonisveryveryeasy!!!"s[:7]

Out[20]:

'Learnin'

In [21]:

s="LearningPythonisveryveryeasy!!!"s[7:]

Out[21]:

'g Python is very very

easy!!!' In [22]:

s="LearningPythonisveryveryeasy!!!"s[::]

Out[22]:

'Learning Python isvery very


easy!!!'
In [23]:

s="LearningPythonisveryveryeasy!!!"s[:]

Out[23]:

'Learning Python isvery very


easy!!!'
In [24]:

s="LearningPythonisveryveryeasy!!!"s[:
:- 1]

Out[24]:

'!!!ysae yrev yrev si nohtyP gninraeL'

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…7/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In [27]:

s='LearningPython'p
ri nt(s[::-1])
print(s[::-2])
print(s[::-3])
print(s[::-5])
print(s[::-10])
print(s[::-100])
print(s[3:5:-1])
print(s[3:5:1])
print(s[5:3:-1])
print(s[5:0:-1])
print(s[-2:-1:-1])
print(s[2:-1:-1])
print(s[2:0:1])
print(s[0:0:1])

nohtyPgninrae
L nhy nnaL
nti
a
nPn
nn
n

r
n
i
n
inrae

Important Conclusions:

1. In the backward direction if the end value is -1, then the result is always empty string.
2. In the farward diretions if the end value is 0, then the result is always empty string.

In forward direction:

default value for begin: 0


defaultvalueforend:lengthofstrin
g default value for step: +1

In backward direction:

default value for begin: -1


default value for end: -(length of string + 1)

Note:

Either forward or backward direction, we can take both +ve and -ve values for begin and end

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…8/24
07/06/20 Python Programming Lab Manual E5 -
21 index. RGMCET(Autonomous)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…9/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

b) Demonstratethefollowingfunctions/methodswhichoperatesonstringsinPythonwithsuitable
examples:

i) len( ) ii) strip( ) iii) rstrip( ) iv) lstrip( )

v) find( ) vi) rfind( ) vii) index( ) viii) rindex()

ix) count( ) x)replace( ) xi) split( ) xii) join( )

xiii) upper( )xiv) lower( ) xv) swapcase( ) xvi) title( )

xvii) capitalize( ) xviii) startswith() xix) endswith()

i. len():

We can use len() function to find the number of characters present in the string.

In [28]:

s='karthi'
print(len(s))
#6
6

Q1.WriteaPythonprogramtoaccesseachcharacterofstringinforwardandbackwarddirectionby using while


loop.

In [29]:

s="LearningPythonisveryeasy!!!"n=len(s
) i=0
print("Forwarddirection")
print()
whilei<n:
print(s[i],end='
') i +=1
print('')
print('')
print("Backwarddirection")
print()
i=-1
whilei>=-n:
print(s[i],end='
') i=i-1

Forward direction

L e a r n i n g P y t h o n i s v e r y e a s y

!!! Backward direction

! ! ! y s a e yr e v s i n o h t y P g n i n r a e L

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…10/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Alternative way [Using slice operator]:

In [30]:

s="LearningPythonisveryeasy!!!"print("
For ward direction")
print('')
foriins:
print(i,end='')
print('')
print('')
print("Forwarddirection")
print('')
foriins[::]:
print(i,end='')
print('')
print('')
print('BackwardDirection')
print('')
foriins[::-1]:
print(i,end='')

Forward direction

L e a r n i n g P y t h o n i s v e r y e a s y

!!! Forward direction

L e a r n i n g P y t h o n i s v e r y e a s y

!!! Backward Direction

! ! ! y s a e yr e v s i n o h t y P g n i n r a e L

Another Alternative:

In [31]:
s=input('Enter thestring :
')
print('DatainFarwardDirectio
n') print(s[::1])
print()
print('DatainBackwardDirectio
n') print(s[::-1])
Enterthestring:PythonLearningiseasy Data
in Farward Direction
Python Learning is easy

DatainBackwardDirecti
on ysae si gninraeL
nohtyP

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…11/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Removing spaces from the string:

Toremovetheblankspacespresentateitherbeginningandendofthestring,wecanusethefollowing3
methods:

1. rstrip()===>Toremoveblankspacespresentatendofthestring(i.e.,righthandside)
2. lstrip()===>Toremoveblankspacespresentatthebeginningofthestring(i.e.,lefthandside)
3. strip()==>Toremovespacesbothsides

ii. strip():

Used to remove spaces both sides of the string.

In [1]:

city=input("EnteryourcityName:")
scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

EnteryourcityName:Hyderabad
Hello Hyderbadi..Adab

In [3]:

scity=input("EnteryourcityName:"
) #scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Hyderabad your entered city is


invalid

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?do…12/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[2]:
city=input("EnteryourcityName:")
scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Hyderabad Hello Hyderbadi..Adab

iii. rstrip():

Used to remove blank spaces present at end of the string (i.e.,right hand side)

In [4]:

scity=input("EnteryourcityName:"
) #scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

EnteryourcityName:Hyderabad
your entered city is
invalid

In [5]:

city=input("EnteryourcityName:")
scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

EnteryourcityName:Hyderabad
Hello Hyderbadi..Adab

iv. lstrip():

Used to remove blank spaces present at the beginning of the string (i.e.,left hand side)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…13/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[6]:
scity=input("EnteryourcityName:"
) #scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Hyderabad your entered city is


invalid

In [7]:

city=input("EnteryourcityName:")
scity=city.lstrip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Hyderabad Hello Hyderbadi..Adab

MoreTestcases:

In [9]:

city=input("EnteryourcityName:")
scity=city.strip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Bangalore Hello
Kannadiga...Shubhodaya

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…14/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In [10]:

city=input("EnteryourcityName:")
scity=city.lstrip()
ifscity=='Hyderabad':
print("HelloHyderbadi..Adab")
elifscity=='Chennai':
print("Hello Madrasi...Vanakkam")
elifscity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("yourentered cityis invalid")

Enter your city Name:

Chennai Hello
Madrasi...Vanakkam

Finding Substrings:

IfyouwanttofindwhetherthesubstringisavailableinthegivenstringornotinPython,wehave4
methods.

For forward direction:

1. find()
2. index()

For backward direction:

1. rfind()
2. rindex()

v. find():

Syntax:

s.find(substring) (Without Boundary)

Returns index of first occurrence of the given substring. If it is not available then we will get -1

In [11]:

s="LearningPythonisveryeasy"print(s.fi
nd( "Python")) # 9
print(s.find("Java"))#-1
print(s.find("r"))#3
print(s.rfind("r"))#21

9
-1
3
21

Bydefault find() methodcan search total string.We can also specifythe boundaries to search.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…15/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Syntax:

s.find(substring,begin,end) (With Boundary)

It will always search from begin index to end-1 index.

In [12]:

s="karthikeyasahasra"p
ri nt(s.find('a'))#1
print(s.find('a',7,15))#9
print(s.find('z',7,15))#-1

1
9
-1

vi. rfind():

In [13]:

s="LearningPythonisveryeasy"print(s.rf
ind ("Python")) # 9
print(s.rfind("Java"))#-1
print(s.find("r"))#3
print(s.rfind("r"))#21

9
-1
3
21

vii. index():

index()methodisexactlysameasfind()methodexceptthatifthespecifiedsubstringisnotavailable
then we will get ValueError.

In [14]:

s='abbaaaaaaaaaaaaaaaaabbababa'print(s.in
dex('bb',2,15))

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-14-136a30f266f9>in<module>
1s='abbaaaaaaaaaaaaaaaaabbababa'
---->2print(s.index('bb',2,15))

ValueError: substring not found

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…16/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[15]:
s='abbaaaaaaaaaaaaaaaaabbababa'print(s
.in dex('bb'))

In [17]:

s=input("Enter main
string:")
subs=input("Entersubstring:
") try:
n=s.index(subs)
exceptValueError:
print("substringnotfound"
)
else:
Entermainstring:RGMCE
T Enter sub
string:CET substring
found

In [18]:

s=input("Enter main
string:")
subs=input("Entersubstring:
") try:
n=s.index(subs)
exceptValueError:
print("substringnotfound"
)
else:
Entermainstring:RGMCE
T Enter sub
string:CTE substring
not found

viii. rindex():

In [16]:

s='abbaaaaaaaaaaaaaaaaabbababa'print(s
.ri ndex('bb'))

20

ix. count():

We can find the number of occurrences of substring present in the given string by using
count() method.

Different forms of count() function/method:

1. s.count(substring) ==> It will search through out the string


2. s.count(substring, begin, end) ===> It will search from begin index to end-1 index

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…17/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[19]:
s="abcabcabcabcadda"pr
in t(s.count('a'))#6
print(s.count('ab'))#4
print(s.count('a',3,7))#2

6
4
2

In [20]:

s='abcdcdckk'
print(s.count('cdc'))

Q.Write a PythonProgram to display allpositions of substring ina given main string.

In [21]:

s=input("Enter main
string:")
subs=input("Entersubstring:
") flag=False
pos=-1
n=len(s)
c = 0
whileTrue:
pos=s.find(subs,pos+1,n)
ifpos==-1:
break
c=c+1
print("Foundatposition",pos)
flag=True
ifflag==False:
print("Not
Found")
Entermainstring:abcabcabcaaa
Enter sub string:abc
Foundatposition0
Foundatposition3
Found at position 6
The number of occurrences :3

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…18/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[22]:
s=input("Enter main
string:")
subs=input("Entersubstring:
") flag=False
pos=-1
n=len(s)
c = 0
whileTrue:
pos=s.find(subs,pos+1,n)
ifpos==-1:
break
c=c+1
print("Foundatposition",pos)
flag=True
ifflag==False:
print("Not
Found")
Entermainstring:
bb Enter sub
string:a Not
Found
The number of occurrences :0

In [23]:

s=input("Enter main
string:")
subs=input("Entersubstring:
") flag=False
pos=-1
n=len(s)
c = 0
whileTrue:
pos=s.find(subs,pos+1,n)
ifpos==-1:
break
c=c+1
print("Foundatposition",pos)
flag=True
ifflag==False:
print("Not
Found")
Entermainstring:abcabcabcaaa
Enter sub string:bb
Not Found
The number of occurrences :0

AlternateWay:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…19/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[24]:
s=input("Enter main string:")
subs=input("Entersubstring:") i
= s.find(subs)
ifi==-1:
print('SpecifiedSubstringisnotfound')
c = 0
whilei!=-1: c
= c + 1
print('{}ispresentatindex:{}'.format(subs,i)) i =
s.find(subs,i+len(subs),len(s))
print('Thenumber ofoccurrences : ',c)

Entermainstring:PythonProgramming
Enter sub string:ram
ram is present at index:
11 The number of
occurrences :1

In [25]:

s=input("Enter main string:")


subs=input("Entersubstring:") i
= s.find(subs)
ifi==-1:
print('SpecifiedSubstringisnotfound')
c = 0
whilei!=-1: c
= c + 1
print('{}ispresentatindex:{}'.format(subs,i)) i =
s.find(subs,i+len(subs),len(s))
print('Thenumber ofoccurrences : ',c)

Entermainstring:PythonProgramming
Enter sub string:raj
SpecifiedSubstringisnotfound The
number of occurrences :0

x. replace():

We can repalce a string with another string in python using a library function replace().

Syntax:

s.replace(oldstring,newstring)

Here, inside 's', every occurrence of oldstring will be replaced with new string.

In [26]:

s="LearningPythonisverydifficult"s1=s.rep
lace("difficult","easy")
print(s1)

Learning Python is very easy

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…20/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[28]:
s="ababababababab"p
rint(id(s))
s1=s.replace("a","b")#Alloccurrenceswillbereplac
ed print(id(s1))
print(s1)

2374771477808
2374771516016
bbbbbbbbbbbbbb

In [29]:

s="ababababababab"p
rint(id(s))
s=s.replace("a","b")#twoobjcetsarecreated
print(id(s))
print(s)

2374771477808
2374771517552
bbbbbbbbbbbbbb

Q. String objects are immutable then how we can change the content by using replace() method.

Ans: Once we creates string object, we cannot change the content.This non changeable
behaviour
isnothingbutimmutability.Ifwearetryingtochangethecontentbyusinganymethod,thenwiththosecha
nges a new object will be created and changes won't be happend in existing object.

Hence with replace() method also a new object got created but existing object won't be changed.

In [30]:

s="abab"
s1=s.replace("a","b")
print(s,"isavailableat:",id(s))
print(s1,"isavailableat:",id(s1))

ababisavailableat:2374771519408
bbbb is available at :
2374771517552

Intheaboveexample,originalobjectisavailableandwecanseenewobjectwhichwascreatedbecauseof
replace() method.

Eg : Consider the string : Python is easy but Java is difficult.

How can you replace the string 'difficult' with 'easy' and 'easy' with 'difficult'?

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…21/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[31]:
s='PythoniseasybutJavaisdifficult's
= s.replace('difficult','easy')
s=s.replace('easy','difficult')
print(s)# itis notgiving correct
output
Python is difficult but Java is

difficult In [32]:

s='PythoniseasybutJavaisdifficult's =
s.replace('difficult','d1')
s=s.replace('easy','e1')
print(s)

Python is e1 but Java is

d1 In [33]:

s='PythoniseasybutJavaisdifficult's =
s.replace('difficult','d1')
s=s.replace('easy','e1')
s=s.replace('d1','easy')
s=s.replace('e1','difficul
t') print(s)

Python is difficult but Java is easy

xi. split():

We can split the given string according to specified seperator by using split() method.
We can split the given string according to specified seperator in reverse direction by using
rsplit()
method.

Syntax :

l=s.split(seperator, Maximum splits)

Here,

Both parameters are optional.


Thedefaultseperatorisspace.
Maximumsplitdefinesmaximumnumberofsplits
The return type of split() method is List.

Note:

rsplit() breaks the string at the seperator staring from the right and returns a list of strings.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…22/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[34]:
s="cseeceeee"l=s.sp
lit()
forxinl:
print(x)

cs
e
ec
e
ee
e

In [35]:

s="22-02-2018"
l=s.split('-')
forxinl:
print(x)

22
02
2018

In [36]:

s="22-02-2018"
l=s.split()# no spacein the string, so outputis same asthe given string
forxinl:
print(x)

22-02-2018

In [37]:

s='rgmnandyalcseeceeee'l=s.sp
lit ()
forxinl:
print(x)

rgm
nandyal
cse
ec
e
ee
e

In [38]:

s='rgmnandyalcseeceeee'l=s.rspli
t('',3)
forxinl:
print(x)

rgmnandyal
cse
ec
e
ee
e
localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -
RGMCET(Autonomous).ipynb?d…23/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In
[39]:
s='rgmnandyalcseeceeeemece'l=s.rsplit(
'', 3)
forxinl:
print(x)

rgmnandyalcseec
e eee
m
e
c
e

In [40]:

s='rgmnandyalcseeceeeemece'l=s.lsplit(
'', 3)
forxinl:
print(x)

--------------------------------------------------------------------------
-
AttributeError Traceback(mostrecentcalllas t)
<ipython-input-40-24e277deda26>in<module>
1 s='rgm nandyal cse ece eee me ce'
---->2l=s.lsplit('',3)
3 forxin l:
4 print(x)

AttributeError:'str' object has no attribute 'lsplit'

In [41]:

s='10,20,30,40,50,60,70,80'
l=s.split(',',3)
forxinl:
print(x)

10
20
30
40,50,60,70,80

In [42]:

s='10,20,30,40,50,60,70,80'
l=s.rsplit(',',3)
forxinl:
print(x)

10,20,30,40,50
60
70
80

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…24/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In [43]:

s='10,20,30,40,50,60,70,80'
l=s.split(',',-1)
forxinl:
print(x)

10
20
30
40
50
60
70
80

xii. join():

We can join a group of strings(list or tuple) with respect to the given seperator.

Syntax:

s=seperator.join(group of strings)

In [44]:

t=('sunny','bunny','chinn
y') s='-'.join(t)
print(s)

sunny-bunny-

chinny In [45]:

l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)

hyderabad:singapore:london:du

bai In [46]:

l=['hyderabad','singapore','london','dubai']
s=''.join(l)
print(s)

hyderabadsingaporelondondub

ai In [47]:

l=['hyderabad','singapore','london','dubai']
s=''.join(l)
print(s)

hyderabad singapore london dubai

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…25/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

Changing case of a String:

We can change case of a string by using the following methods.

xiii. upper():

Used to convert all characters to upper case in the given string.

xiv. lower():

Used to convert all characters to lower case in the given string.

xv. swapcase():

Usedtoconvertalllowercasecharacterstouppercaseandalluppercasecharacterstolowercas
ein the given string.

xvi. title():

Usedtoconvertallcharacterstotitlecase.(i.efirstcharacterineverywordshouldbeuppercaseandall
remaining characters should be in lower case in the given string).

xvii. capitalize():

Onlyfirstcharacterwillbeconvertedtouppercaseandallremainingcharacterscanbeconvertedto
lower case.

In [48]:

s='learningPythonisveryEasy'print(s.up
per ())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

LEARNING PYTHON IS VERY EASY


learningpythonisveryeasy
LEARNING pYTHON IS VERY
eASY
LearningPythonIsVeryEasy
Learning python is very
easy

Q.Write a Pythonprogram to Convert theuppercase characters intolowercase and remove spaces.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…26/24
07/06/20 Python Programming Lab Manual E5 -
21 RGMCET(Autonomous)

In [49]:

s='LearningPythonIsVeryEasy'
s = s.lower().replace('','')
print(s)

learningpythonisveryeas

y In [50]:

# Above example with join() & split() functions


s='LearningPythonIsVeryEasy's =
s.lower()
s1 = s.split()
s=''.join(s1)
print(s)

learningpythonisveryeasy

Checking starting and ending part of the string:

Python contains the following methods for this purpose.

1. s.startswith(substring)
2. s.endswith(substring)

xviii. startswith():

Used to check the starting of the string.

xix. endswith():

Used to check the ending of the string.

In [51]:
s='learningPythonisveryeasy'print(s.st
art swith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))

True
Fals
e
True

Good Luck

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual E5 -


RGMCET(Autonomous).ipynb?d…27/24
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 6: File I/O

Asthepartofprogrammingrequirement,wehavetostoreourdatapermanentlyforfuturepur
pose.For this requirement we should go for files.
Files are very common permanent storage areas to store our data.
Afileisdefinedasplacedonthedisk.wherethegroupofrelateddatacanbestored.
file handling is an important part of any web application.

VariouspropertiesofFileObject:

Onceweopendafileandwegotfileobject,wecangetvariousdetailsrelatedtothatfilebyusing

itsproperties. name: Name of opened file

mode:Mode in which the file is opened

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.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 1/


RGMCET(Autono… 6
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

a) Writea Python programto perform readand write operationson a file.

In [1]:

str=input("Enterthedataintoafile
:") f1=open('abc.txt','w')
f1.write(str)
f1.close()
f2=open('abc.txt','r
') data=f2.read()
print(data)
f2.close()

Enterthedataintoafile:PythonProgrammingLabManual
Python Programming Lab Manual

In [3]:

filename=input("Enterthefilename:")
f1=open(filename,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f2=open(filename,'r
') data=f2.read()
print(data)
f2.close()
Enter the file name : RGM
Computer science Engineering
ElecronicsandCommunicationEngineerin
g Civil Engineering

In [4]:

filename=input("Enterthefilename:")
f1=open(filename,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f2=open(filename,'r
')
data=f2.readline()
print(data)
Enter the file name : rgm
Computer science Engineering

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 2/


RGMCET(Autono… 6
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[5]:
filename=input("Enterthefilename:")
f1=open(filename,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f2=open(filename,'r
')
data=f2.readlines()
print(data)
Enter the file name : Python ['ComputerscienceEngineering\
n','ElecronicsandCommunicationEngineeri ng\n', 'Civil Engineering\n']

b) Writea Python programto copy thecontents of onefile to another file.

In [6]:

filename1=input("Enterthefilename1:") f1
= open(filename1,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f2=open(filename,'r
') data1 =
f2.read()
print(data)
f2.close()
filename2=input("Enterthefilename2:") f3 =
open(filename2,'w')
f3.write(data1)
f3.close()
f3=open(filename2,'r
') data2 = f3.read()
print(data2)
Enter the file name 1: Pyhton ['ComputerscienceEngineering\
n','ElecronicsandCommunicationEngineeri ng\n', 'Civil Engineering\n']
Enter the file name 2: c++
Computer science Engineering
ElecronicsandCommunicationEngineerin
g Civil Engineering

c) Writea Python programto count frequencyof characters ina givenfile.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 3/


RGMCET(Autono… 6
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
filename=input("Enterafilename:") f1
= open(filename,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f1=open(filename,'r')
data = f1.read()
a=list(set(data))
sorted(a)
print(a)
f1.close()
foriina:
print("{}asoccured{} times".format(i,data.count(i)))
Enter a file name : rgmcet
['','r','E','C','t','p','g','u','o','c','m','a','i','\n', 's', 'v',
'e', 'l', 'n', 'd']
as occured 6 times
r as occured 5 times
E as occured 4 times
C as occured 3 times
t as occured 2 times
p as occured 1 times
g as occured 6 times
u as occured 2 times
o as occured 4 times
c as occured 5 times
m as occured 3 times
a as occured 2 times
i as occured 12
times

as occured 3
times
sasoccured2times
v as occured 1
times
easoccured10times
l as occured 2
times
nasoccured14times
d as occured 1
times

d) Writea Python programto print eachline of afile in reverse order.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 4/


RGMCET(Autono… 6
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[8]:
filename=input("Enterafilename:") f1
= open(filename,'w')
f1.write('Computerscience Engineering\
n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f1=open(filename,'r
') data =
f1.readlines()
print(data)
foriindata:
print(i[::-
Enter a file name : rgmcet ['ComputerscienceEngineering\
n','ElecronicsandCommunicationEngineeri ng\n', 'Civil Engineering\n']

gnireenignE ecneics retupmoC

gnireenignEnoitacinummoCdnascinorcel

E gnireenignE liviC

e) Writea Python programto compute the numberof characters, words andlines in a file.

In [10]:
filename=input("Enterafilename:") c =
0 w=0
l=0
f1=open(filename,'w
')
f1.write('Computerscience Engineering\n')
f1.write('ElecronicsandCommunicationEngineering\
n') f1.write('Civil Engineering\n')
f1.close()
f2=open(filename,'r
') data =
f2.readlines()
print(data)
foriindata:
c=c+len(i)
w=w+len(i.split()) l
= l + 1
f2.close()
print('ThenumberofCharactersare:',c)
print('The number of Words are :', w)
print('Thenumber ofLines are:',l)
Enter a file name : rgmcet ['ComputerscienceEngineering\
n','ElecronicsandCommunicationEngineeri ng\n', 'Civil Engineering\n']
ThenumberofCharactersare:88
The number of Words are : 9
The number of Lines are : 3

f).Write a Pythonprogram to reversefirst n charactersin a file.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 5/


RGMCET(Autono… 6
07/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
f=open("rgmcet",'r+')
n=int(input("Enterthefirstnnumbertoreverseinafile:")) s
=f.read(n) print(s)
f.seek(0,0)
f.write(s[n::-1])
f.close()
f=open("rgmcet",'r
') f.seek(0,0)
print(f.read()
) f.close()

Enterthefirstnnumbertoreverseinafile:5
upmoC Computer science Engineering
ElecronicsandCommunicationEngineering
Civil Engineering

Good Luck

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 6/


RGMCET(Autono… 6
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 7: List Data type

a) Demonstrate the different ways of creating list objects with suitable example programs.

Ifwewanttorepresentagroupofindividualobjectsasasingleentitywhereinsertionorderispreservedand
duplicates are allowed, then we should go for List.

Insertion order preserved.


Duplicate objects are allowed
Heterogeneous objects are allowed.
Listisdynamicbecausebasedonourrequirementwecanincreasethesizeanddecreasethesize. In List
the elements will be placed within square brackets and with comma seperator.
Wecandifferentiateduplicateelementsbyusingindexandwecanpreserveinsertionorderbyusing
index.Hence index will play very important role.
Pythonsupportsbothpositiveandnegativeindexes.+veindexmeansfromlefttorightwhereas
negative index means right to left.

Eg:[10,"A","B",20, 30, 10]

List objects are mutable.(i.e., we can change the content.)

Creation of List Objects:

1. Wecancreateemptylist object:

In [1]:
list=[]
print(list)
print(type(list
))
[]
<class 'list'>

2. If we know elements already then we can create list object:

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [2]:
list=[10,20,30,40]
print(list)
print(type(list))

[10, 20, 30, 40]


<class 'list'>

3. Creationof listobject Withdynamic input:

In [3]:

list=(input("EnterList:"))#Entire inputisconsideredas string


print(list)
print(type(list))

EnterList:10,20,30,40
10,20,30,40
<class 'str'>

In [4]:

list=eval(input("EnterList:"
)) print(list)
print(type(list))

EnterList:
[10,20,30,40] [10,
20, 30, 40]
<class 'list'>

In [5]:

list=eval(input("EnterList:"
)) print(list)
print(type(list))

Enter List:[ram,raj]

--------------------------------------------------------------------------
-
NameError Traceback(mostrecentcalllas t)
<ipython-input-5-5a3b608c2f72>in<module>
---->1list=eval(input("Enter List:"))
2 print(list)
3 print(type(list))

<string>in<module>

NameError:name 'ram' is not defined

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[6]:
list=eval(input("EnterList:"
)) print(list)
print(type(list))

Enter List:['ram','raj']
['ram', 'raj']
<class 'list'>

4. Wecan createa listobject usinglist() function:

In [8]:

l=list(range(0,10,2))
print(l)
# Not working in jupyter notebook but works in any standard editor

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-8-70c9fdd81115>in<module>
----> 1l=list(range(0,10,2))
2 print(l)
3 #Notworkinginjupyternotebookbutworksinanystandardeditor

TypeError: 'list' object is not callable

In [9]:

[0,2,4,6,8]

Out[9]:

[0, 2, 4, 6, 8]

In [ ]:

s="rgmcet"l=l
i st(s)
print(l)

In [10]:

['r','g','m','c','e','t']

Out[10]:

['r', 'g', 'm', 'c', 'e', 't']

5. Wecancreate listobject withsplit() function:

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[11]:
s="LearningPythonisveryveryeasy!!!"l=s
.sp lit()
print(l)
print(type(l))

['Learning', 'Python', 'is', 'very', 'very', 'easy', '!!!']


<class 'list'>

b) Demonstratethefollowingfunctions/methodswhichoperatesonlistsinPythonwithsuitable
examples.

i) list( ) ii) len( ) iii) count( ) iv) index ( )

v) append( ) vi) insert( ) vii) extend() viii) remove(


)
ix) pop( ) x) reverse( ) xi) sort( ) xii) copy( )

xiii) clear( )

Important functions of List:

i. list():

In [ ]:

l=list(range(0,10,2))
print(l)
# Not working in jupyter notebook but works in any standard editor

ii) len():

It returns the number of elements present in the list.

In [1]:

n=[10,20,30,40]
print(len(n))

In [2]:

n=[10,20,30,40,'rgm']
print(len(n))

iii) count():

It returns the number of occurrences of specified item in the list.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[3]:
n=[1,2,2,2,2,3,3]
print(n.count(1
))
print(n.count(2
))
print(n.count(3
1
4
2
0

iv) index():

It returns the index of first occurrence of the specified item.

In [4]:

n=[1,2,2,2,2,3,
3]
print(n.index(1) # 0
)
print(n.index(2) # 1
)
print(n.index(3) # 5
)
print(n.index(4)
)
0
1
5

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-4-b7a2785b40f1>in<module>
3 print(n.index(2))#1
4 print(n.index(3))#5
----> 5print(n.index(4))

ValueError:4 is not in list

Note:

IfthespecifiedelementnotpresentinthelistthenwewillgetValueError.Hencebeforeindex()methodwe
have to check whether item present in the list or not by using in operator.

Example Program:

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…5/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[5]:
l=[10,20,30,40,10,20,10,10]
target=int(input('Enter valueto search: '))
iftargetinl:
print(target,'availableandits firstoccurrence isat ',l.index(target))
else:
print(target,'isnotavailable')

Enter value to search : 500


500is not available

In [6]:

l=[10,20,30,40,10,20,10,10]
target=int(input('Enter valueto search: '))
iftargetinl:
print(target,'availableandits firstoccurrence isat ',l.index(target))
else:
print(target,'isnotavailable')

Enter value to search : 20


20 available and its first occurrence is at1

In [7]:

l=[10,20,30,40,10,20,10,10]
target=int(input('Enter valueto search: '))
iftargetinl:
print(target,'availableandits firstoccurrence isat ',l.index(target))
else:
print(target,'isnotavailable')

Enter value to search : 10


10 available and its first occurrence is at0

v) append():

We can use append() function to add item at the end of the list.
By using this append function, we always add an element at last position.

In [8]:

list=[]
list.append("A"
)
list.append("B")
list.append("C")
print(list)
['A', 'B', 'C']

Q.Write a Python Programto add all elementsto list upto 100which are divisible by 10.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [9]:

list=[]
foriinrange(101
): ifi
%10==0:
list.append(i)
print(list)
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

AnotherWay:

In [10]:

list=[]
foriinrange(0,101,10):
list.append(i)
print(list)

[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

vi) insert():

It is used to insert item at specified index position.

In [11]:

n=[1,2,3,4,5]
n.insert(1,888
) print(n)

[1, 888, 2, 3, 4, 5]

In [12]:

n=[1,2,3,4,5]
n.insert(10,777)
n.insert(-10,999)
print(n)
print(n.index(777
))
print(n.index(999
[999, 1, 2, 3, 4, 5, 777]
6
0

Note:

Ifthespecifiedindexisgreaterthanmaxindexthenelementwillbeinsertedatlastposi
tion. If the specified index is smaller than min index then element will be
inserted at first position.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

vii) extend():

If we waant to add all items of one list to another list,we use extend()method.

Eg:

l1.extend(l2)

All items present in l2 will be added to l1.

In [13]:

order1=["Chicken","Mutton","Fis
h"] order2=["RC","KF","FO"]
order1.extend(order2)
print(order1)
print(order2)

['Chicken','Mutton','Fish','RC','KF','FO']
['RC', 'KF', 'FO']

In [14]:

order1=["Chicken","Mutton","Fis
h"] order2=["RC","KF","FO"]
order3=order1+order2
print(order1)
print(order2)
print(order3)

['Chicken', 'Mutton', 'Fish']


['RC', 'KF', 'FO']
['Chicken', 'Mutton', 'Fish', 'RC', 'KF', 'FO']

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
l1=[10,20,30]
l2=[40,50,60]
l1.extend(l2)
print(l1)

[10, 20, 30, 40, 50, 60]

In [16]:

order=["Chicken","Mutton","Fish"]
order.extend("Mushroom")
print(order)# It adds everycharacter as a singleelement to the list

['Chicken', 'Mutton', 'Fish', 'M', 'u', 's', 'h', 'r', 'o', 'o', 'm']

Explanation:

Here,'Mushroom'isastringtype,inthisstring8elementsarethere.Theseelementsareadded
seperately.

In [17]:

order=["Chicken","Mutton","Fish"]
order.append("Mushroom")# Itadds thisstring as asingle elementto the list
print(order)

['Chicken', 'Mutton', 'Fish', 'Mushroom']

viii) remove():

We can use this function to remove specified item from the list.
If the item present multiple times then only first occurrence will be removed.

In [18]:

n=[10,20,10,30]
n.remove(10
) print(n)

[20, 10, 30]

If the specified item not present in list then we will getValueError.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[19]:
n=[10,20,10,30]
n.remove(40
) print(n)

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-19-c4e183b90359>in<module>
1n=[10,20,10,30]
----> 2n.remove(40)
3 print(n)

ValueError:list.remove(x): x not in

list

Note:

Hencebeforeusingremove()methodfirstwehavetocheckspecifiedelementpresentinthelistornotby
using in
operator.

In [20]:
l1=[10,20,30,40,50,60,70]
x=int(input('Enterthe elementto beremoved : '))
ifxinl1:
l1.remove(x)
print('ElementremovedSuccessfully'
) print(l1)
else:
print('Specifiedelement isnot available ')

Entertheelementtoberemoved:10
Element removed Successfully
[20, 30, 40, 50, 60, 70]

In [21]:

l1=[10,20,30,40,50,60,70]
x=int(input('Enterthe elementto beremoved : '))
ifxinl1:
l1.remove(x)
print('ElementremovedSuccessfully'
) print(l1)
else:
print('Specifiedelement isnot available ')

Entertheelementtoberemoved:90
Specified element is not available

ix) pop():

It removes and returns the last element of the list.


This is only function which manipulates list and returns some element.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…10/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[22]:
n=[10,20,30,40]
print(n.pop())
print(n.pop())
print(n)

40
30
[10, 20]

If the list is empty then pop() function raises IndexError.

In [23]:

n=[]
print(n.pop())

--------------------------------------------------------------------------
-
IndexError Traceback(mostrecentcalllas t)
<ipython-input-23-
bfeb9843d2be>in<module> 1n=[]
----> 2print(n.pop())

IndexError:pop from empty

list

Note:

1. pop()is the only function which manipulates the list and returns some value.
2. Ingeneralwecanuseappend()andpop()functionstoimplementstackdatastructurebyusinglist,
which follows LIFO(Last In First Out) order.
3. Ingeneralwecanusepop()functiontoremovelastelementofthelist.Butwecanalsousepop
() function to remove elements based on specified index.

Wecan usepop() functionin followingtwo ways:

n.pop(index)==>Toremoveandreturnelementpresentatspecifie

d index. n.pop()==>Toremoveandreturnlastelementofthe

list.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…11/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [24]:

n=[10,20,30,40,50,60]
print(n.pop())#60
print(n.pop(1))#20
print(n.pop(10))#IndexError:popindexoutofrange

60
20

--------------------------------------------------------------------------
-
IndexError Traceback(mostrecentcalllas t)
<ipython-input-24-47504bb9f619>in<module>
2 print(n.pop())#60
3 print(n.pop(1))#20
---->4print(n.pop(10))#IndexError:popindexoutofrange

IndexError: pop index out of range

Note:Intheabovetable,whereverspecialisthere,consideritasspecific. Note:

List objects are dynamic (i.e., based on our requirement we can increase and decrease the size).

append(),insert(),extend() ===>for increasing the size/growable nature


remove(),pop() ======>for decreasing the size /shrinking nature

x) reverse():

It is used to reverse the order of elements in the list.

In [25]:
n=[10,20,30,40]
n.reverse()
print(n)

[40, 30, 20, 10]

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…12/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

xi) sort():

In list by default insertion order is preserved.


If you want to sort the elements of list according to default natural sorting order then we
should go for
sort() method.

For numbers ==> default natural sorting order is Ascending Order

ForStrings==>defaultnaturalsortingorderisAlphabeticalOrder

In [26]:

n=[20,5,15,10,0]
n.sort()
print(n)

[0, 5, 10, 15, 20]

In [27]:

s=["Dog","Banana","Cat","Apple"]
s.sort()
print(s)

['Apple', 'Banana', 'Cat',

'Dog'] In [28]:

s=["Dog","Banana","Cat","apple"]
s.sort()# Unicode valuesare used duringcomparison of alphbets
print(s)

['Banana', 'Cat', 'Dog', 'apple']

Note:

To use sort() function, compulsory list should contain only homogeneous elements, otherwise
we will get
TypeError.

In [29]:

n=[20,10,"A","B"]
n.sort()
print(n)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-29-76d0c10ed9e7>in<module>
1n=[20,10,"A","B"]
----> 2n.sort()
3 print(n)

TypeError:'<' not supported between instances of 'str' and 'int'

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…13/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Howtosorttheelementsoflistinreverseofdefaultnaturalsortingorder? One

Simple Way:

In [30]:

n=[40,10,30,20]
n.sort()
n.reverse()
print(n)

[40, 30, 20, 10]

AlternateWay:

We can sort according to reverse of default natural sorting order by using reverse = True
argument.

In [31]:

n=[40,10,30,20]
n.sort()
print(n)#[10,20,30,40]
n.sort(reverse=True)
print(n)#[40,30,20,10]
n.sort(reverse=False)
print(n)#[10,20,30,40]

[10, 20, 30, 40]


[40, 30, 20, 10]
[10, 20, 30, 40]

In [32]:

s=["Dog","Banana","Cat","Apple"]
s.sort(reverse=True)#reverseofAlphabeticalorder
print(s)

['Dog', 'Cat', 'Banana', 'Apple']

Aliasing and Cloning of List objects:

The process of giving another reference variable to the existing list is called aliasing.

In [33]:
x=[10,20,30,40]
y=x
print(id(x)
)
print(id(y))
1979461271296
1979461271296

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Theprobleminthisapproachisbyusingonereferencevariableifwearechangingcontent,thenthose
changes will be reflected to the other reference variable.

In
[34]:
x=[10,20,30,40]
y=x
y[1]=777
print(x)

[10, 777, 30,


40]

Toovercomethisproblemweshouldgoforcloning.

Cloning:Theprocessofcreatingexactlyduplicateindependentobjectiscalledcloning.

We can implement cloning by using the following ways:

1. slice operator
2. copy() function

1. By using slice operator:

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [35]:

x=[10,20,30,40]
y=x[:]
y[1]=777
print(x)#[10,20,30,40]
print(y)#[10,777,30,40]

[10, 20, 30, 40]


[10, 777 30,
, 40]

2. By using copy() function:

xii) copy():

In
[36]:
x=[10,20,30,40]
y=x.copy()
y[1]=777
print(x)#[10,20,30,40]
print(y)#[10,777,30,40]

[10, 20, 30, 40]


[10, 777, 30, 40]

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…16/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Q. What is the difference between = operator and copy() function?

Ans: = operator meant for aliasing copy() function meant for

xiii) clear():

We can use clear() function to remove all elements of List.

In [37]:

n=[10,20,30,40]
print(n)
n.clear()
print(n)

[10,20,30,40] []

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…17/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

c) Demonstrate the following with suitable example programs:

i) List slicing

ii) List Comprehensions

i) List slicing:

Syntax:

list2= list1[start:stop:step]

start ==>it indicates the index where slice has to start default value is 0
stop===>Itindicatestheindexwhereslicehastoenddefaultvalueismaxallowedindexoflistiele
ngth of the list step ==>increment value (step default value is 1)

In [1]:

l=[10,20,30,40,50,60]
print(l[::])

[10, 20, 30, 40, 50, 60]

In [2]:

l=[10,20,30,40,50,60]
l1=l[::]
print(l1)

[10, 20, 30, 40, 50, 60]

In [3]:

l=[10,20,30,40,50,60]
print(l[::2])

[10, 30, 50]

In [4]:

l=[10,20,30,40,50,60]
print(l[::-1])

[60, 50, 40, 30, 20, 10]

In [5]:

l=[10,20,[30,40],50,60]
print(l[0:3:])

[10, 20, [30, 40]]

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…18/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[6]:
n=[1,2,3,4,5,6,7,8,9,10]
print(n[2:7:2]) #3,5,7
print(n[4::2]) # 5,7,9
print(n[3:7]) #4,5,6,7
print(n[8:2:-2]) # 9,7,5
print(n[4:100]) #5,6,7,8,9,10

[3, 5, 7]
[5, 7, 9]
[4, 5, 6, 7]
[9, 7, 5]
[5, 6, 7, 8, 9,
10]

ii) List Comprehensions:

Itisveryeasyandcompactwayofcreatinglistobjectsfromanyiterableobjects(like
list,tuple,dictionary,range etc) based on some condition.

Syntax:

list=[expression for item in list if condition]

Consider an example, If you want to store squares of numbers form 1 to 10 in a list,

In [7]:

l1=[]
forxinrange(1,11):
l1.append(x*x)
print(l1)

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

Intheabovecase,theprogramconsisting4linesofcode.Nowforthesamepurposewewillwritethe
following code in more concised way.

In [8]:

l1=[x*xforxinrange(1,21)]
l2=[xforxinl1ifx%2==0] print(l1)
print(l2)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289,
324, 361, 400]
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

Few more examples on List comprehensions:

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…19/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[9]:
l1=[x*xforxinrange(1,11)]
print(l1)

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

In [10]:

l=[2**xforxinrange(1,11)]
print(l)

[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]

In [11]:
l=[xforxinrange(1,11)ifx%2==0] print(l)

[2, 4, 6, 8, 10]

In [12]:
l=[xforxinrange(1,11)ifx%2==1] print(l)

[1, 3, 5, 7, 9]

In [13]:

l=[x**2forxinrange(1,11)if(x**2)%2==1] print(l)

[1, 9, 25, 49, 81]

In [14]:

words=["Balaiah","Nag","Venkatesh","Chiranjeevi"
] l=[w[0] for w in words]
print(l)

['B', 'N', 'V',

'C'] In [15]:

words=["Balaiah","Nag","Venkatesh","Chiranjeevi
"] l=[w for w in words if len(w)>6]
print(l)

['Balaiah', 'Venkatesh',

'Chiranjeevi'] In [16]:

num1=[10,20,30,40]
num2=[30,40,50,60]
num3=[iforiinnum1ifinotinnum
2] print(num3)

[10, 20]

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…20/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[17]:
words="thequickbrownfoxjumpsoverthelazydog".split()
print(words) l=[[w.upper(),len(w)]forwinwords]
print(l)

['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']


[['THE', 3], ['QUICK', 5], ['BROWN', 5], ['FOX', 3], ['JUMPS', 5], ['OVE
R', 4], ['THE', 3], ['LAZY', 4], ['DOG', 3]]

More Example Programs:

Q1.Write a Pythonprogram to find themaximum number ofa list of numbers.

In [36]:

n=int(input("Enterthelistsize:")) a=[]
foriinrange(n):
num=int(input("Enterthenumber"))
a.append(num)
print(a)
max=a[0]
foriinrange(n)
:
if(max<a[i]):
max=a[i]
print("Maximum number in the list is : ",max)

Enterthelistsize:5
Enter the number33
Enter the
number77
Enterthenumber221
Enter the number5
Enter the number7
[33, 77, 221, 5,
7]
maximum number in the list is :221

Q2.Write a Pythonprogram to find theminimum number ofa list of numbers.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…21/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [39]:

n=int(input("Enterthelistsize:")) a=[]
foriinrange(n):
num=int(input("Enterthenumber"))
a.append(num)
print(a)
min=a[0]
foriinrange(n)
:
if(min>a[i]):
min = a[i]
print("Minimum number in the list is : ",min)

Enterthelistsize:5
Enter the number33
Enter the number6
Enterthenumber27
Enter the number7
Enterthenumber44
[33, 6, 27, 7,
44]
Minimum number in the list is :6

Good Luck

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…22/22
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment8:TupleDatatype

a) Demonstrate the different ways of creating tuple objects with suitable example programs.

Introduction:

1. TupleisexactlysameasListexceptthatitisimmutable.i.e.,oncewecreatesTupleobject,wecan
not perform any changes in that object. Hence Tuple is Read Only Version of List.
2. If our data is fixed and never changes then we should go for Tuple.
3. Insertion Order is preserved.
4. Duplicates are allowed.
5. Heterogeneous objects are allowed.
6. Wecanpreserveinsertionorderandwecandifferentiateduplicateobjectsbyusingindex.Hencei
ndex will play very important role in Tuple also.
7. Tuplesupportboth+veand-veindex.+veindexmeansforwarddirection(fromlefttoright)and-
veindex means backward direction(from right to left).
8. WecanrepresentTupleelementswithinParenthesisandwithcommaseperator.

Note:

Parenethesis are optional but recommended to use.

In [1]:
t=10,20,30,40
print(t)
print(type(t))

(10, 20, 30, 40)


<class 'tuple'>

In [2]:

t=(10,20,30,40)
print(t)
print(type(t))

(10, 20, 30, 40)


<class 'tuple'>

In [3]:

t=()
print(type(t))

<class 'tuple'>

Note:

Wehavetotakespecialcareaboutsinglevaluedtuple.compulsarythevalueshouldendswith
comma,otherwise it is not treated as tuple.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 1/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [4]:

t=(10)
print(t)
print(type(t))

10
<class 'int'>

In [5]:

t=(10,)
print(t)
print(type(t))

(10,)
<class 'tuple'>

Q. Which of the following are valid/Invalid tuples?

In [6]:

t=() # valid
t=10,20,30,40 # valid
t=10 # not valid
t=10, # valid
t=(10) # notvalid
t=(10,) # valid
t=(10,20,30,40) # valid
t=(10,20,30,) # valid

In [7]:
t=(10,20,30,)
print(t)
print(type(t))

(10, 20, 30)


<class 'tuple'>

CreationofTupleObjects:

1. Wecancreateemptytuple object:

In [8]:

t=()
print(t)
print(type(t))

()
<class 'tuple'>

2. Creation of single valued tuple object:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 2/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[9]:
t=(10,)
print(t)
print(type(t))

(10,)
<class 'tuple'>

3. creation of multi values tuples & parenthesis are optional:

In [10]:

t=10,20,30
print(t)
print(type(t))

(10, 20, 30)


<class 'tuple'>

In [11]:

t=eval(input("EnterTuple:"
)) print(t)
print(type(t))

EnterTuple:(10,20,30)
(10, 20, 30)
<class 'tuple'>

In [12]:

t=eval(input("EnterTuple:"
)) print(t)
print(type(t))

EnterTuple:10,20,
30 (10, 20, 30)
<class 'tuple'>

4. Wecan createa tupleobject usingtuple() function:

If you have any sequence (i.e., string, list, range etc.,) which can be easily converted into a tuple
by using
tuple() function.

In [13]:

list=[10,20,30]
t=tuple(list)
print(t)
print(type(t))

(10, 20, 30)


<class 'tuple'>

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 3/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[14]:
t=tuple(range(10,20,2
)) print(t)
print(type(t))

(10, 12, 14, 16, 18)


<class 'tuple'>

In [15]:

t=tuple('karthi'
) print(t)
print(type(t))

('k', 'a', 'r', 't', 'h', 'i')


<class 'tuple'>

b) Demonstratethefollowingfunctions/methodswhichoperatesontuplesinPythonwithsuitable
examples.

i) len() ii) count() iii) index () iv) sorted()

v) min() vi) max() vii) cmp() viii)


reversed()

Important functions of Tuple:

i. len():

Itisanin-builtfunctionofPython,ifyouprovideanysequnce(i.e.,strings,list,tupleetc.,),inthathow
many elements are there that will be returned this function.
It is used to return number of elements present in the tuple.

In
[16]:
t=(10,20,30,4
0) #
print(len(t)) 4

ii) count():

It returns the number of occurrences of specified item in the list.

In [17]:

t=(10,20,10,10,20)
print(t.count(10))#3

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 4/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[18]:
n=(1,2,2,2,2,3,3)
print(n.count(1
))
print(n.count(2
))
print(n.count(3
))
1
4
2
0

In [19]:

t=(10,20,10,10,20)
print(t.count(100))

iii) index():

It returns the index of first occurrence of the specified item.


If the specified element is not available then we will get ValueError.

In [20]:

t=(10,20,10,10,20)
print(t.index(10))#0
print(t.index(30))#ValueError:tuple.index(x):xnotintuple

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-20-c98072186526>in<module>
1t=(10,20,10,10,20)
2print(t.index(10))#0
---->3print(t.index(30))#ValueError:tuple.index(x):xnotintuple

ValueError: tuple.index(x): x not in tuple

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 5/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[21]:
n=(1,2,2,2,2,3,
3) # 0
print(n.index(1
))
print(n.index(2 # 1
))
print(n.index(3 # 5
))
print(n.index(4
))
0
1
5

--------------------------------------------------------------------------
-
ValueError Traceback(mostrecentcalllas t)
<ipython-input-21-e2f70118d739>in<module>
3 print(n.index(2)) 1
#
4 print(n.index(3)) 5
#
---- print(n.index(4))
>5

ValueError:tuple.index(x): x not in tuple

iv) sorted():

It is used to sort elements based on default natural sorting order (Ascending order).

In [22]:

t=(10,30,40,20)
print(sorted(t))#sorted()is goingtoreturn list

[10, 20, 30, 40]

In [23]:

t=(10,30,40,20)
t.sort()
print(t)

--------------------------------------------------------------------------
-
AttributeError Traceback(mostrecentcalllas t)
<ipython-input-23-6dd56d99cf24>in<module>
1t=(10,30,40,20)
----> 2t.sort()
3print(t)

AttributeError:'tuple' object has no attribute 'sort'

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 6/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[24]:
t=(40,10,30,20)
t1=tuple(sorted(t)
) print(type(t1))
print(t1)
print(type(t1))
print(t)

<class
'tuple'> (10,
20, 30, 40)
<class
'tuple'> (40,
10, 30, 20)

We can sort according to reverse of default natural sorting order is as follows:

In [25]:

t=(40,10,30,20)
t1=tuple(sorted(t))
t1=sorted(t,reverse=True)
print(t1) #[40, 30, 20, 10]

[40, 30, 20, 10]

v) min():

min()functionreturntheminimumvalueaccordingtodefaultnaturalsortingorder
. This function will works on tuple with respect to homogeneous elements
only.

In [26]:
t=(40,10,30,20)
print(min(t))#10

10

In [27]:

t=('karthi')# based on unicode values these functions will work.


print(min(t))

In [28]:

t=('kArthi')
print(min(t))

vi) max():

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 7/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[24]:
max()functionreturnthemaximumvalueaccordingtodefaultnaturalsortingo
rder. This function will works on tuple with respect to homogeneous
elements only.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 8/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[29]:
t=(40,10,30,20)
print(max(t))#40

40

In [30]:

t=('karthi')# based on unicode values these functions will work.


print(max(t))

In [31]:

t=('kArthi')
print(max(t))

vii) cmp():

Itcomparestheelementsofbothtuple
s. If both tuples are equal then
returns 0.
If the first tuple is less than second tuple then it returns -1.
If the first tuple is greater than second tuple then it returns +1.

In [32]:

t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(cmp(t1,t2) # -1
)
print(cmp(t1,t3) # 0
)
print(cmp(t2,t3) # +1
)
--------------------------------------------------------------------------
-
NameError Traceback(mostrecentcalllas t)
<ipython-input-32-848450ec0e9e>in<module>
2 t2=(40,50,60)
3 t3=(10,20,30)
---- print(cmp(t1,t2) # -1
>4 )
5 print(cmp(t1,t3) # 0
)
6 print(cmp(t2,t3) # +1
)

NameError:name 'cmp' is not defined

Note: cmp() function is available only in Python 2 but not in Python 3.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 9/


RGMCET(Autono… 9
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[33]:
t1=(10,20,30)
t2=(40,50,60)
t3=(10,20,30)
print(t1==t2
)
print(t1==t3
)
print(t2==t3
)
Fals
e
True
Fals
e
True

In [47]:

t1=(10,20,30)
t2=(5,50,60)
print(t1<t2)

False

viii) reversed():

It is used to reverse the elements of the given tuple.

In [49]:

t1=(10,20,30)
t2=reversed(t1)
foriint2:
print(i,end='')

30 20 10

Good Luck

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual - 10


RGMCET(Autono… /9
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 9: Set Data type

a) Demonstrate the different ways of creating set objects with suitable example programs.

Introduction:

If we want to represent a group of unique values as a single entity then we should go for set.

Key features of Set Data Type:

1. Duplicates are not allowed.


2. Insertion order is not preserved.But we can sort the elements.
3. Indexing and slicing not allowed for the set.
4. Heterogeneous elements are allowed.
5. Setobjectsaremutablei.eoncewecreatessetobjectwecanperformanychangesinthatobject
based on our requirement.
6. Wecan representset elements withincurly braces andwith comma seperation.
7. Wecanapplymathematical operationslikeunion,intersection,difference etconset objects.

Creation of Set Objects:

1. Creation of set object with single value:

In [1]:

s={10}
print(type(s))
print(s)

<class 'set'>
{10}

2. Creation of set object with multiple values:

In [2]:

s={30,40,10,5,20}#Intheoutputordernotpreserved
print(type(s))
print(s)

<class 'set'>
{5, 40, 10, 20, 30}

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[3]:
s={30,40,10,5,20}#Intheoutputordernotpreserved
print(type(s))
print(s[0])

<class 'set'>

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-3-87d1e6948aef>in<module>
1 s={30,40,10,5,20}#Intheoutputordernotpreserved
2 print(type(s))
----> 3print(s[0])

TypeError:'set' object is not subscriptable

In [4]:

s={30,40,10,5,20}#Intheoutputordernotpreserved
print(type(s))
print(s[0:6])

<class 'set'>

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-4-bf084a8b7575>in<module>
1 s={30,40,10,5,20}#Intheoutputordernotpreserved
2 print(type(s))
----> 3print(s[0:6])

TypeError:'set' object is not subscriptable

3. Creation of set objects using set() function:

We can create set objects by using set() function.

Syntax:

s=set(any sequence)

In [5]:

l=[10,20,30,40,10,20,10]
s=set(l)
print(s)# {40, 10, 20,30} because duplicates arenot allowed in set

{40, 10, 20, 30}

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [6]:

s=set(range(5))
print(s)#{0,1, 2,3,
4}
{0, 1, 2, 3, 4}

In [7]:

s=set('karthi'
) print(s)

{'i', 'r', 'a', 'h', 'k',

't'} In [8]:

s=set('aaabbbb')
print(s)

{'b',

'a'} In

[9]:

st=eval(input("EnterSet:")
) print(st)
print(type(st))

Enter Set:{10,20,30}
{10, 20, 30}
<class 'set'>

Note:

While creating empty set we have to take special care. Compulsory we should use set()
function.

s={}==>It is treated as dictionary but not empty set.

In [10]:
s={}
print(type(s))

<class

'dict'> In

[11]:

s=set()# set function without any arguments


print(s)
print(type(s))

set()
<class 'set'>

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

b) Demonstratethefollowingfunctions/methodswhichoperatesonsetsinPythonwithsuitable
examples.

i) add() ii) update() iii)copy() iv) pop()

v) remove() vi)discard() vii)clear()

viii)union() ix)intersection()

x)difference()

Important functions of Set:

i. add():

It Adds an item 'x' to the set.

In [12]:

s={10,20,30
} # ';' is optional for python statements
s.add(40);
print(s) # {40, 10, 20, 30}

{40, 10, 30}


20,
In [13]:

s={10,20,30}
s.add('karthi');#';' isoptional forpython
statements
print(s)

{10, 'karthi', 20, 30}

ii) update():

This method is used to add multiple items to the set.


ArgumentsarenotindividualelementsandtheseareIterableobjectslikeList,rangeetc.
All elements present in the given Iterable objects will be added to the set.

In [14]:

s={10,20,30}
s.update('karthi');#';' isoptional forpython statements
print(s)

{'i', 'r', 10, 'a', 'h', 20, 'k', 't', 30}

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [15]:

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5
)) print(s)

{0, 1, 2, 3, 4, 40, 10, 50, 20, 60, 30}

In [16]:

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),100)
print(s)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-16-96e519440e16>in<module>
1s={10,20,30}
2l=[40,50,60,10]
----> 3s.update(l,range(5),100)
4print(s)

TypeError:'int' object is not iterable

In [17]:

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'100')
print(s)

{0, 1, 2, 3, 4, '0', 40, 10, 50, '1', 20, 60, 30}

In [18]:

s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5),'karthi
') print(s)

{0, 1, 2, 3, 4, 'i', 'r', 40, 10, 'a', 'h', 50, 20, 'k', 60, 't', 30}

In [19]:

s=set()
s.update(range(1,10,2),range(0,10,2))
print(s)

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…5/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Q1. What is the difference between add() and update() functions in set?

Wecanuseadd()toaddindividualitemtotheSet,whereaswecanuseupdate()functiontoadd
multiple items to Set.
add()functioncantakeonlyoneargumentwhereasupdate()functioncantakeanynumberof
arguments but all arguments should be iterable objects.

Q2. Which of the following are valid for set s?

1. s.add(10) ==>Valid
2. s.add(10,20,30)==>TypeError:add()takesexactlyoneargument(3given)
3. s.update(10)==>TypeError:'int'objectisnot iterable
4. s.update(range(1,10,2),range(0,10,2)) ==>Valid

iii) copy():

It returns copy of the set. It is cloned object (Backup copy).

In [21]:

s={10,20,30}
s1=s.copy()
print(s1)
print(s)

{10, 20, 30}


{10, 20, 30}

iv) pop():

It removes and returns some random element from the set.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[22]:
s={40,10,30,2
0}
print(s)
print(s.pop()
)
print(s.pop()
)
print(s.pop()
# Empty
) print(s) set
print(s.pop()
{40, 10, 20, 30}
40
10
20
{30}
30
set()

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-22-3f6a1609f80b>in<module>
7print(s.pop())
8print(s) # Empty set
----> 9print(s.pop())

KeyError: 'pop from an empty set'

Consider the following case :

In [23]:

s={40,10,30,20}
print(s)
print(s.pop())
print(s.pop())
print(s)

{40, 10, 20, 30}


40
10
{20, 30}

In [24]:

s={40,10,30,20}
print(s)
print(s.pop())
print(s.pop())
print(s)

{40, 10, 20, 30}


40
10
{20, 30}

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[25]:
s={40,10,30,20}
print(s)
print(s.pop())
print(s.pop())
print(s)

{40, 10, 20, 30}


40
10
{20, 30}

Note:

Howmanytimesyoumayexecutethecode,theelementswhicharepoppedfromthesetinsameorder.The

reason is --- All the elements of set are inserted based on some hashcode.
Ifthatorderisfixedthenitisalwaysgoingtoreturnonebyone.Butinwhichordertheseelementsare
inserted we don't know.

v) remove():

It removes specified element from the set.


If the specified element not present in the Set then we will get KeyError.

In [26]:

s={40,10,30,20}
s.remove(30)
print(s)#{40,10, 20}
s.remove(50)#KeyError:50

{40, 10, 20}

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-26-77437864d839>in<module>
2 s.remove(30)
3 print(s)#{40,10, 20}
---->4s.remove(50)#KeyError:50

KeyError: 50

vi) discard():

It removes the specified element from the set.


If the specified element not present in the set then we won't get any error.

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [1]:

s={10,20,30}
s.discard(10)
print(s)#{20,3
0}
s.discard(50)
print(s)#{20,3
0}
{20, 30}
{20, 30}

vii) clear():

It is used to remove all elements from the Set.

In [2]:

s={10,20,30}
print(s)
s.clear()
print(s)

{10, 20, 30}


set()

viii) union():

x. union(y)==>Wecanusethisfunctiontoreturnallelementspresentinbothxandy

sets Wecan perform union operation in two ways:

1. x.union(y)==> by calling through union() method.

2. x|y==> by using '|'operator.

This operation returns all elements present in both sets x and y (without duplicate elements).

In [3]:

x={10,20,30,40}
y={30,40,50,60}
print(x.union(y))#{10,20,30, 40,50,60} #Orderisnot preserved
print(x| 20, 30, 40, 50, 60}
y)#{10,
{40, 10, 50, 60 30}
20, ,
{40, 10, 50, 60 30}
20, ,

ix) intersection():

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Wecanperformintersection operationintwo ways:

1. x.intersection(y) ==> by calling through intersection() method.

2. x&y==> by using '&'operator.

This operation returns common elements present in both sets x and y.

In [4]:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y))#{40,30}
print(x&y)#{40,30}

{40, 30}
{40, 30}

x) difference():

Wecanperformdifferenceoperationintwoways:

1. x.difference(y)==>by callingthroughdifference() method.

2. x-y ==> by using '-'operator.

This operation returns the elements present in x but not in y.

In [5]:

x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y))#{10,
20} print(x-y)#{10,20}
print(y-x)#{50,60}

{10, 20}
{10, 20}
{50, 60}

Good Luck

localhost:8890/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…10/10
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 10: Dictionary Data type

a) Demonstrate the different ways of creating Dictionary objects with suitable example programs.

Introduction:

WecanuseList,Tuple andSettorepresent agroupofindividual objectsasasingle entity.


If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.

Eg:

rollno---name

phone number--

address ipaddress---

domain name

Key features of Dictionary Data type:

1. Duplicate keys are not allowed but values can be duplicated.


2. Hetrogeneous objects are allowed for both key and values.
3. insertion order is not preserved.
4. Dictionaries are mutable.
5. Dictionaries are dynamic in nature.
6. indexing and slicing concepts are not applicable.

Creation of Set Objects:

1. Creation of dict object with single value:

In [1]:
d={'Karthi':99
}
print(type(d))
print(d)
<class 'dict'>
{'Karthi': 99}

2. Creation of dict object with multiple values:

In [2]:

d={'Karthi':99,'saha':100,'Rahul':98}
print(type(d))
print(d)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/15
18/06/20 Python Programming Lab Manual -
21 <class 'dict'> RGMCET(Autonomous)
{'Karthi': 99, 'saha': 100, 'Rahul': 98}

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

3. Creation of set objects using dict() function:

We can create dict objects by using dict() function.

In [3]:

d=dict()
print(type(d))

<class

'dict'> In

[5]:

d=eval(input("EnterDictionay:"))
print(d)
print(type(d))

Enter Dictionay:{'a':100,'b':200,'c':300}
{'a': 100, 'b': 200, 'c': 300}
<class 'dict'>

4. Wecan createan empty dictionaryby usingfollowing approach also:

In [6]:

d={}
print(type(d))

<class 'dict'>

Wecan addentries intoa dictionaryas follows:

d[key] = value

In [7]:

d[100]="karthi"d[2
0
0]="sahasra"d[300]
= "sri"
d['rgm']='Nandyal'
print(d)#{100: 'karthi', 200:'sahasra', 300: 'sri','rgm' : 'Nandyal'}
{100: 'karthi', 200: 'sahasra', 300: 'sri', 'rgm': 'Nandyal'}

b) Demonstratethefollowingfunctions/methodswhichoperatesondictionaryinPythonwithsuitable
examples.

i) dict() ii) len() iii)clear() iv) get()

v) pop() vi)popitem() vii)keys() viii)values(


)
ix) items() x)copy() xi)update()

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Example Program:

Q.WriteaPythonprogramtoenternameandpercentagemarksinadictionaryanddisplay information on
the screen.

In [8]:

rec={}
n=int(input("Enternumberofstudents:"))
i=1 whilei<=n:
name=input("EnterStudentName:")
marks=input("Enter%ofMarksofStudent:")
rec[name]=marks
i=i+1 print("NameofStudent","\
t","%of Marks") forxinrec:
print("\t",x,"\t",rec[x])#x===>keyrec[x]=====> value

Enter number of students:


3
Enter Student Name: Karthi
Enter % of Marks of 98
Student:
Enter Student Name: Sourav
Enter % of Marks of 97
Student:
Enter Student Name: Afridi
Enter % of Marks of 34
Student:
Name of Student % of
Marks
Karthi 98
Sourav 97
Afridi 34

Important functions of Dictionary:

i. dict():

This function is used to create a dictionary.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [10]:

d=dict()#Itcreatesempty
dictionary print(d)
d=dict({100:"karthi",200:"saha"
}) print(d)
d=dict([(100,"karthi"),(200,"saha"),
(300,"sri")]) print(d) d=dict(((100,"karthi"),
(200,"saha"),(300,"sri"))) print(d)
d=dict({(100,"karthi"),(200,"saha"),
(300,"sri")}) print(d) d=dict({[100,"karthi"],
[200,"saha"],[300,"sri"]}) print(d)

{}
{100: 'karthi', 200: 'saha'}
{100: 'karthi', 200: 'saha', 300: 'sri'}
{100: 'karthi', 200: 'saha', 300: 'sri'}
{300: 'sri', 200: 'saha', 100: 'karthi'}

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-10-b19e5b872e1c>in<module>
9d=dict({(100,"karthi"),(200,"saha"),
(300,"sri")}) 10print(d)
--->11d=dict({[100,"karthi"],[200,"saha"],[300,"sri"]})
12print(d)

TypeError:unhashable type:

'list'

Note:

Compulsoryinternallyweneedtotaketupleonlyisacceptable.Ifyoutakelistitgivestheabove
specified error.

Ifthekey&valuesareavailableintheformoftuple,thenallthosetuplevaluescanbecovertedinto
dictionary by using 'dict()' function.

ii) len():

It returns the number of items in the dictionary.

In [11]:

d=dict({100:"karthi",200:"saha"})#Itcreatesdictionarywithspecifiedel
ements print(d)
print(len(d))

{100: 'karthi', 200: 'saha'}


2

iii) clear():
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Autono…5/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

This function is used to remove all entries from the dictionary.

In [9]:

d={100:"karthi",200:"sahasra",300:"sri
"} print(d)
d.clear()
print(d)

{100: 'karthi', 200: 'sahasra', 300: 'sri'}


{}

iv) get():

It is used tTo get the value associated with the specified key.

There are two forms of get() method is available in Python.

i. d.get(key):

IfthekeyisavailablethenreturnsthecorrespondingvalueotherwisereturnsNone.Itwontraiseany
error.

In [12]:

d=dict({100:"karthi",200:"saha"})#Itcreatesdictionarywithspecifiedelements
print(d.get(100))

karthi

In

[13]:

d=dict({100:"karthi",200:"saha"})#Itcreatesdictionarywithspecifiedelements
print(d.get(500))

None

ii. d.get(key,defaultvalue):

If the key is available then returns the corresponding value otherwise returns default value.

In [14]:

d=dict({100:"karthi",200:"saha"})#Itcreatesdictionarywithspecifiedelements
print(d.get(100,'ravan'))

karthi

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [15]:

d=dict({100:"karthi",200:"saha"})#Itcreatesdictionarywithspecifiedelements
print(d.get(500,'ravan'))
print(d)

ravan
{100: 'karthi', 200: 'saha'}

Another Example:

In [16]:

d={100:"karthi",200:"saha",300:"sri"}
print(d[100]) #karthi
print(d[400])#KeyError:400
print(d.get(100))#karthi
print(d.get(400))#None
print(d.get(100,"Guest"))#karthi
print(d.get(400,"Guest"))#Guest

karthi

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-16-b4151f9f1cde>in<module>
1d={100:"karthi",200:"saha",300:"sri"}
2print(d[100])#karthi
---->3print(d[400])#KeyError:400
4print(d.get(100))#karthi
5print(d.get(400))#None

KeyError: 400

In [17]:

d={100:"karthi",200:"saha",300:"sri"}
print(d[100]) #karthi
#print(d[400]) #KeyError:400
print(d.get(100))#karthi
print(d.get(400))#None
print(d.get(100,"Guest"))#karthi
print(d.get(400,"Guest"))#Guest

karth
i
karth
i
None
karth
i
Guest

v) pop():

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Itremovestheentryassociatedwiththespecifiedkeyandreturnsthecorrespondingval
ue. If the specified key is not available then we will get KeyError.

Syntax:

d.pop(key)

In [18]:

d={100:"karthi",200:"saha",300:"sri"}
print(d)
print(d.pop(100
)) print(d)
print(d.pop(400
))
{100:'karthi',200:'saha',300:'sri'}
karthi
{200: 'saha', 300: 'sri'}

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-18-82136391b748>in<module>
3print(d.pop(100))
4print(d)
----> 5print(d.pop(400))

KeyError: 400

vi) popitem():

It removes an arbitrary item(key-value) from the dictionaty and returns it.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[19]:
d={100:"karthi",200:"saha",300:"sri"}
print(d)
print(d.popitem())
print(d.popitem())
print(d)
print(d.pop(400))#KeyErr
or
{100: 'karthi', 200: 'saha', 300: 'sri'}
(300, 'sri')
(200, 'saha')
{100: 'karthi'}

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-19-ef041cdb3d72>in<module>
4print(d.popitem())
5print(d)
---->6print(d.pop(400))#KeyError

KeyError: 400

If the dictionary is empty then we will get KeyError.

In [20]:

d={}
print(d.popitem())#KeyError:'popitem():dictionaryisempty'

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-20-
052c88c1625e>in<module> 1d={}
---->2print(d.popitem())#KeyError:'popitem():dictionaryisempty'

KeyError: 'popitem(): dictionary is empty'

Another example:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[21]:
d={100:"karthi",200:"saha",300:"sri"}
print(d)
print(d.popitem(
))
print(d.popitem(
))
print(d.popitem(
))
{100: 'karthi', 200: 'saha', 300: 'sri'}
(300, 'sri')
(200, 'saha')
(100, 'karthi')

--------------------------------------------------------------------------
-
KeyError Traceback(mostrecentcalllas t)
<ipython-input-21-
45eab152fd1e>in<module>
4print(d.popitem())
5print(d.popitem())
----> 6print(d.popitem())
7print(d)

KeyError: 'popitem(): dictionary is empty'

vii) keys():

It returns all keys associated with dictionary.

In [22]:

d={100:"karthi",200:"saha",300:"sri"}
print(d.keys())
forkeyind.keys():
print(key)

dict_keys([100, 200, 300])


100
200
300

viii) values():

It returns all values associated with the dictionary.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…10/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [23]:

d={100:"karthi",200:"saha",300:"s
ri"} print(d.values())
forkeyind.values():
print(key)

dict_values(['karthi','saha','sri'])
karthi
sah
a
sri

ix) items():

It returns list of tuples representing key-value pairs like as shown below.

[(k,v),(k,v),(k,v)]

In [24]:

d={100:"karthi",200:"saha",300:"sri
"} list = d.items()
print(list)

dict_items([(100, 'karthi'), (200, 'saha'), (300, 'sri')])

In [26]:

d={100:"karthi",200:"saha",300:"sri"}
fork,vind.items():
print(k,"--
>",v)
100 --> karth
i
200 --> saha
300 --> sri

x) copy():

This method is used to create exactly duplicate dictionary(cloned copy).

In [27]:

d={100:"karthi",200:"saha",300:"sri"}
d1=d.copy()
print(d1)
print(d)

{100: 'karthi', 200: 'saha', 300: 'sri'}


{100: 'karthi', 200: 'saha', 300: 'sri'}

xi) update():

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…11/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Syntax:

d.update(x)

All items present in the dictionary 'x' will be added to dictionary 'd'.

In [28]:

d={100:"karthi",200:"saha",300:"sri"}
d1={'a':'apple','b':'banan
a'} d.update(d1)
print(d)

{100: 'karthi', 200: 'saha', 300: 'sri', 'a': 'apple', 'b':

'banana'} In [29]:

d={100:"karthi",200:"saha",300:"sri"}
d1={'a':'apple','b':'banana'} d2
= {777:'A', 888:'B'}
d.update(d1,d2)#For updatemethod.you needtopass singleargument only.
print(d)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-29-b0832a652cd0>in<module>
2d1={'a':'apple','b':'banana'}
3d2={777:'A',888:'B'}
---->4d.update(d1,d2)#Forupdatemethod.youneedtopasssingleargum ent only.
5print(d)

TypeError:update expected at most 1 argument, got 2

In [30]:
d={100:"karthi",200:"saha",300:"sri"}
d1={'a':'apple','b':'banana'} d2
= {777:'A', 888:'B'}
d.update([(777,'A')])#For uipdatemethod. youcan passlist oftuple asan argument.
print(d)

{100: 'karthi', 200: 'saha', 300: 'sri', 777: 'A'}

In [31]:

d={100:"karthi",200:"saha",300:"sri"}
d1={'a':'apple','b':'banana'} d2
= {777:'A', 888:'B'}
d.update([(777,'A'),(888,'B'),(999,'C')])#youcanaddanyno.oflistoftupleelement s.
print(d)

{100: 'karthi', 200: 'saha', 300: 'sri', 777: 'A', 888: 'B', 999: 'C'}

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…12/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Few More Example Programs on Dictioary data type:


Q1.Write a Python programto take dictionary fromthe keyboard and printthe sum of values.

In [32]:

d=eval(input("Enterdictionary:")
) s=sum(d.values())
print("Sum=",s)

Enterdictionary:{'A':100,'B':200,'c':300}
Sum=600

In [33]:

d=eval(input("Enterdictionary:")
) s=sum(d.values())
print("Sum=",s)

Enterdictionary:'A':100,'B':200,'c':300

Traceback (most recent call last):

File"C:\Users\HP\anaconda3\lib\site-packages\IPython\core\
interactivesh ell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)

File"<ipython-input-33-
51a5d22abba9>",line1,in<module>d=eval(input("Enter
dictionary:"))

File"<string>", line1
'A':100,'B':200,'c':3
00
^

Sum() function:

In
[34]:
l=[10,20,30,40]
s=sum(l) # sum() function works on list
print('Sumis: also
',s)
Sum is :100

In [35]:

l=(10,20,30,40)
s=sum(l) # sum() function works on tuple also
print('Sumis:',s) l

Sumis:100

Out[35]: (10, 20,

30, 40)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…13/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[36]:
l={10,20,30,40}
s=sum(l) # sum() function works on set
print('Sumis: also
',s)
Sum is :100

Note: sum() function can work on any sequence.

Q2.Write a Python programto find number ofoccurrences of each letterpresent in the given string.

In [38]:

word=input("Enteranyword:") d={}
for x in word:
d[x]=d.get(x,0)+1
fork,vind.items():
print(k,"occurred",v,"times"
)

Enter any word: mississippi


m occurred 1 times
i occurred 4 times
s occurred 4 times
p occurred 2 times

In [39]:

word=input("Enteranyword:") d={}
for x in word:
d[x]=d.get(x,0)+1
fork,vinsorted(d.items()):#Tosortalltheitemsofthedictionaryinalphabetical order
print(k,"occurred",v,"times")

Enter any word: mississippi


i occurred 4 times
m occurred 1 times
p occurred 2 times
s occurred 4 times

Q3.Write a Python programto find number ofoccurrences of each vowelpresent in the given string.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[40]:
word=input("Enteranyword:
")
vowels={'a','e','i','o','
u'} d={}
forxinword:
if x in vowels:
d[x]=d.get(x,0)+1
fork,vinsorted(d.items()):
print(k,"occurred",v,"times")
Enter any word: doganimaldoganimal
a occurred 4 times
i occurred 2 times
o occurred 2 times

Q4.Writeaprogramtoacceptstudentnameandmarksfromthekeyboardandcreatesadictionary. Also
display student marks by taking student name as input.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/15
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[41]:
n=int(input("Enterthenumberofstudents:")) d={}
foriinrange(n):
name=input("EnterStudentName:")
marks=input("EnterStudentMarks:")
d[name]=marks # assigninng values to the keys of the dictionary
'd'
whileTrue:
name=input("EnterStudentNametogetMark
s:") marks=d.get(name,-1)
ifmarks==-1:
print("StudentNotFound")
else:
print("TheMarksof",name,"are",marks)
option=input("Doyouwant tofind anotherstudent marks[Yes|
No]") ifoption=="No":
break
print("Thanksfor usingour application")

Enterthenumberofstudents:5 Enter
Student Name: Karthi
Enter Student Marks: 87
EnterStudentName:Sahasra
Enter Student Marks: 88
EnterStudentName:Sourav Enter
Student Marks: 77
EnterStudentName:Rahul
Enter Student Marks:
65
EnterStudentName:Vira
t Enter Student
Marks: 87
EnterStudentNametogetMarks:Karthi
The Marks of Karthi are 87
Doyouwanttofindanotherstudentmarks[Yes|No]y Enter
Student Name to get Marks: karthi
Student Not Found
Doyouwanttofindanotherstudentmarks[Yes|No]y Enter
Student Name to get Marks: Virat
The Marks of Virat are 87
Doyouwanttofindanotherstudentmarks[Yes|No]y Enter
Student Name to get Marks: Robin
Student Not Found
Doyouwanttofindanotherstudentmarks[Yes|No]No Thanks
for using our application

Good Luck

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…16/15
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment11:Functions

Introduction:
Ifagroupofstatementsisrepeatedlyrequiredthenitisnotrecommendedtowritethesestatements
everytime seperately.
Wehavetodefinethesestatementsasasingleunitandwecancallthatunitanynumberoftimesbased
on our requirement without rewriting. This unit is nothing but function.
The main advantage of functions is Code Reusability.

Note:

In other languages functions are known as methods,procedures,subroutines etc.

a) Demonstrate the following kinds of Parameters used while writing functions in Python.

i) Positional Parameters ii) Default Parameters

iii)Keyword Parameters iv) Variable length

Parameters

Parameters:

Parameters are inputs to the function.


Ifafunctioncontainsparameters,thenatthetimeofcalling,compulsoryweshouldprovide
values,otherwise we will get error.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…1/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

TypesofParametersinPython:

1. Positional Parameters:

Inthecaseofpositionalarguments,numberofargumentsmustbesame.
In the case of positional arguments, order of the arguments is
important.

2. Keyword (i.e., Parameter name) Parameters:

Inthecaseofkeywordarguments,orderoftheargumentsisnotimportant
. In the case of keyword arguments, number of arguments must be
same.

3. Default Parameters:

You can define default value for the arguments.


If you are not passing any argument, then default values by default will be considered.
Afterdefaultargumentsyoushouldnottakenormalarguments.
(i.e.,Defaultargumentsyouneedtotake at last)

4. VariablelengthParameters:

Sometimeswecanpassvariablenumberofargumentstoourfunction,suchtypeofargumentsarecall
ed variable length arguments.
Wecan declarea variable lengthargument with '*'symbol as follows

def f1(*n):

Wecancallthisfunctionbypassinganynumberofargumentsincludingzeronumber.Internallyallthese
values represented in the form of tuple.

Example Programs:

Q1.Write a function totake name of thestudent as input andprint wish message by name.

In [1]:
defwish(name):
print("Hello",name,"GoodMorning")
wish("Karthi")
wish("Sahasra"
)
Hello KarthiGood
Morning Hello
SahasraGood Morning

Q2.Write a functionto take numberas input andprint its square value.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…2/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[2]:
defsquareIt(number):
print("TheSquareof",number,"is",number*numbe
r)
squareIt(4
)
squareIt(5
The Square of 4 is 16
The Square of 5 is 25
The Square of 7 is 49

Eg 3:

In [3]:

defwish():
print('hello'
) print(wish())

hell
o
None

Q4.Write a functionto accept 2numbers as inputand return sum.

In [4]:

defadd(x,y):
returnx+y
result=add(10,20)
print("Thesumis",result)
print("Thesumis",add(100,20
0))
The sum is
30 The sum
is 300

Note:

If we are not writing return statement then default return value is None.

In [5]:

deff1():
print("Hello")
f1()
print(f1())

Hell
o
Hell
o
None

Q5.Write a functionto check whetherthe given numberis even or odd.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…3/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[6]:
defeven_odd(num
): ifnum
%2==0:
print(num,"isEven Number")
else:
print(num,"isOddNumber")
even_odd(10)
even_odd(15)
10 is Even Number
15 is Odd Number

Q6.Write afunction tofind factorialof given number.

In [7]:
deffact(num):
result=1
whilenum>=1:
result=result*nu
m num=num-1
returnresult
foriinrange(1,5
):
print("TheFactorialof",i,"is :",fact(i))
The Factorial of 1 is :
1
The Factorial of 2 is :
2 The Factorial of 3 is
: 6 The Factorial of 4

Example programs to demonstrate Positional Arguments.

In [13]:

defcalc(a,b) # Here, 'a'&'b' are called positional


: arguments
sum=a+
b
sub=a-
b
returnsum,sub,mul,div
a,b,c,d=calc(100,50) # Positional
arguments
print(a,b,c,d)
150 50 5000 2.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…4/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[14]:
defcalc(a,b):#PositionalArguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,d
150
50
5000
2.0

In [ ]:

In [
]:

In [
]:

Example programs to demonstrate Keyword Arguments.

In [15]:

defcalc(a,b) # keyword arguments


: Arguments
sum=a+
b
sub=a-
b
returnsum,sub,mul,div
t=calc(a=100,b=50)#keyword arguments
Arguments
forxint:
print(x)
150
50
5000
2.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…5/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[16]:
defcalc(a,b): # keyword arguments Arguments
sum=a+
b
sub=a-
b
mul=a*
b # keyword arguments Arguments
div=a/
b
returnsum,sub,mul,d
iv t = calc(b = 50, a
= 100) for x in t:
print(x)

150
50
5000
2.0

In [17]:

defcalc(a,b) # keyword arguments


: Arguments
sum=a+
b
sub=a-
b
returnsum,sub,mul,div
t=calc(100,b=50) # It is perfectly
valid
forxint:
print(x)

150
50
5000
2.0

In [18]:
defcalc(a,b):#keywordargumentsArguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,d
iv t = calc(b = 50,
100)
File"<ipython-input-18-70a44f0ef84d>",line7 t
= calc(b = 50, 100)
^
SyntaxError:positional argument follows keyword argument

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…6/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[19]:
defcalc(a,b):#keywordargumentsArguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,div
t=calc(50,a=50)# Itis also
--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-19-2669f311ec68>in<module>
5 div=a/b
6 returnsum,sub,mul,div
---- t = calc(50,a=50)#It isalso
>7 invalid
8 for xin t:
9 print(x)

TypeError:calc() got multiple values for argument 'a'

Another Example:

In [20]:

defwish(name,msg):
print('Hello',name,ms
g)
wish(name='Karthi',msg='Good Morning')
#order is not important, but no.of arguments is important.
wish(msg='GoodMorning',name='Karthi')
HelloKarthiGoodMorning
Hello Karthi Good
Morning

Example programs to demonstrate Default Arguments.

In [22]:

defwish(name='Guest',msg):
# After default argument, we should not take non-default argument
print('Hello',name,msg)

File"<ipython-input-22-a83b9dddb70c>",line1 def
wish(name ='Guest',msg):
^
SyntaxError:non-default argument follows default argument

In [23]:

defwish(msg,name='Guest'):
print(msg,name)
wish('Hello','Karthi')

Hello Karthi
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?downl…7/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[24]:
defwish(msg,name='Guest'):
print(msg,name)
wish('Hello')

Hello

Guest In

[25]:

defwish(msg,name='Guest'):
print(msg,name)
wish()

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-25-8435118960b8>in<module>
1 defwish(msg,name='Guest'):
2 print(msg,name)
----> 3wish()

TypeError:wish() missing 1 required positional argument: 'msg'

Note:

You can give any number of default arguments.

In [26]:

defwish(name='Guest',msg='GoodMorning'):
print('Hello',name,msg)
wish()

Hello Guest Good

Morning In [27]:

defwish(marks,age,name='Guest',msg='GoodMorning'):
print('Student Name:',name)
print('Student Age:',age)
print('StudentMarks:',marks)
print('Message:',msg)
wish(99,48,'Karthi') # Valid

StudentName:Karth
i Student Age: 48
Student Marks: 99
Message: Good Morning

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…8/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[28]:
defwish(marks,age,name='Guest',msg='GoodMorning'):
print('Student Name:',name)
print('Student Age:',age)
print('StudentMarks:',marks)
print('Message:',msg)
wish(age=48,marks= 100)

StudentName:Guest
Student Age: 48
Student Marks: 100
Message: Good Morning

In [29]:

defwish(marks,age,name='Guest',msg='GoodMorning'):
print('Student Name:',name)
print('Student Age:',age)
print('StudentMarks:',marks)
print('Message:',msg)
wish(100,age=46,msg='BadMorning',name='Karthi') # valid

StudentName:Karth
i Student Age: 46
Student Marks: 100
Message: Bad Morning

In [30]:

defwish(marks,age,name='Guest',msg='GoodMorning'):
print('Student Name:',name)
print('Student Age:',age)
print('StudentMarks:',marks)
print('Message:',msg)
wish(marks=100,46,msg='BadMorning',name='Karthi')# invalid

File"<ipython-input-30-694cd2b4bf85>", line6
wish(marks=100,46,msg='Bad Morning',name = 'Karthi') #
invalid
^
SyntaxError:positional argument follows keyword argument

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?downl…9/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [31]:

defwish(marks,age,name='Guest',msg='GoodMorning'):
print('Student Name:',name)
print('Student Age:',age)
print('StudentMarks:',marks)
print('Message:',msg)
wish(46,marks=100,msg='BadMorning',name='Karthi') # invalid

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-31-eb2f97227036>in<module>
4 print('Student Marks:',marks)
5 print('Message:',msg)
----> 6 wish(46,marks=100,msg='Bad Morning',name = 'Karthi')

#invalid TypeError: wish() got multiple values for argument

'marks'

ExampleprogramstodemonstrateVariablelength Arguments.

In [32]:

defsum(a,b):
print(a+b)
sum(10,20)

30

Nowitisworkingcorrectly.Aftersometimemyrequiremnetisasfollows:

sum(10,20,30)

In [33]:

defsum(a,b):
print(a+b)# Thissum() functionwe can'tuse forthe new requirement.
sum(10,20,30)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-33-5c96eb93c4b3>in<module>
1 defsum(a,b):
2 print(a+b)#Thissum()functionwecan'tuseforthenewrequ irement.
----> 3sum(10,20,30)

TypeError:sum() takes 2 positional arguments but 3 were given

In [34]:

defsum(a,b,c):
print(a+b+
# we have to go for another sum() function
c)
sum(10,20,30)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…10/28
17/06/20 Python Programming Lab Manual -
21 60 RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…11/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Nowitisworkingcorrectly.Aftersometimemyrequiremnetisasfollows:

sum(10,20,30,40)

In [35]:

def sum(a,b,c):
print(a+b+c)
sum(10,20,30,40)

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-35-b271960d93ea>in<module>
1 defsum(a,b,c):
2 print(a+b+c)
----> 3sum(10,20,30,40)

TypeError:sum() takes 3 positional arguments but 4 were


given

Once again the same problem. we should go for anothersum()


function.

In [36]:

defsum(a,b,c,d):
print(a+b+c+ # we have to go for another sum()
d) function
sum(10,20,30,40)
100

Ifyouchangethenumberofarguments,thenautomaticallyforeverychange,compusorilywenee
dtogo for new function unnecessarily. Because of this length of the code is going to
increase.

In
[37]:
defsum(*n):
# Here, 'n' is a variable length argument.
result=0
forxinn:
result=result+x
print(result)
sum(10,20,30,40)

100

In [38]:

defsum(*n):
result=0
forxinn:
result=result+x
print(result)
sum(10,20,30)

60

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…12/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[39]:
defsum(*n):
result=0
forxinn:
result=result+x
print(result)
sum(10,20)
30

In [40]:

defsum(*n):
result=0
forxinn:
result=result+x
print(result)
sum(10)

10

In [41]:

defsum(*n):
result=0
forxinn:
result=result+x
print(result)
sum()

In [42]:

defsum(*n):
result=0
forxinn:
result=result+x
print('TheSumis:',resul
t)
sum(10,20,30,40)
sum(10,20,30)
sum(10,20)
sum(10)
sum()
TheSumis:100
The Sum is :60
The Sum is :30
The Sum is :10
The Sum is :0

Note: Same function is used for variable number of arguments.

Key Point 1:

Wecan mixvariable lengtharguments withpositional arguments.


Youcantakepositionalargumentsandvariablelengtharguments simultaneously.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…13/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[43]:
defsum(name,*n)
: result =0
forxinn:
result=result+x
print("TheSumby",name,":",result)
sum('Robin',10,20,30,40)
sum('Rahul',10,20,30)
sum('Sachin',10,20)
sum('Sourav',10)
sum('Karthi')

TheSumbyRobin:100 The
Sum by Rahul :60
TheSumbySachin:30
TheSumbySourav:10 The
Sum by Karthi :0

Note:

Rule:Aftervariablelengthargumenst,ifwearetakinganyotherargumentsthenweshouldprovidevaluesas
keyword arguments.

In [44]:

defsum(*n,name)
: result =0
forxinn:
result=result+x
print("TheSumby",name,":",result)
sum('Robin',10,20,30,40)
sum('Rahul',10,20,30)
sum('Sachin',10,20)
sum('Sourav',10)
sum('Karthi')

--------------------------------------------------------------------------
-
TypeError Traceback(mostrecentcalllas t)
<ipython-input-44-9cbb9821a5b4>in<module>
4 result =result +x
5 print("TheSumby", name,":",result
)
---- sum('Robin',10,20,30,4
>6 0)
7 sum('Rahul',10,20,30)
8 sum('Sachin',10,20)

TypeError:sum() missing 1 required keyword-only argument: 'name'

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…14/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[45]:
defsum(*n,name)
: result =0
forxinn:
result=result+x
print("TheSumby",name,":",result)
sum(name =
'Robin',10,20,30,40)
sum(name='Rahul',10,20,30)
sum(name = 'Sachin',10,20)
sum(name = 'Sourav',10)
sum(name='Karthi')

File"<ipython-input-45-96d7fd117357>",line6 sum(name
= 'Robin',10,20,30,40)
^
SyntaxError:positional argument follows keyword argument

In [46]:

defsum(*n,name)
: result =0
forxinn:
result=result+x
print("TheSumby",name,":",result)
sum(10,20,30,40,name = 'Robin')
sum(10,20,30,name='Rahul')
sum(10,20,name = 'Sachin')
sum(10,name = 'Sourav')
sum(name='Karthi')

TheSumbyRobin:100 The
Sum by Rahul :60
TheSumbySachin:30
TheSumbySourav:10 The
Sum by Karthi :0

Another Example:

In [47]:

deff1(n1,*s)
:
print(n1)
fors1ins:
print(s1
) f1(10)
f1(10,20,30,40)
f1(10,"A",30,"B
10
10
20
30
40
10
A
3
0
B

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…15/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Conclusions:

Aftervariablelengtharguments,ifyouaretakinganyotherargument,thenwehavetoprovidevaluesa
s key word arguments only.
Ifyoupassfirstnormalargumentandthenvariablearguments,thenthereisnoruletofollow.Itworks
correctly.

Key Point 2:

Keyword variable length arguments:

Now,Supposeifwewanttopassanynumberofkeywordargumentstoafunction,compulsorilywehave
to identify the difference with the above case (i.e., Passing of any number of positional
arguments).
We can declare key word variable length arguments also. For this we have to use **.
Wecancallthisfunctionbypassinganynumberofkeywordarguments.Internallythesekeyword
arguments will be stored inside a dictionary.

In
[48]:
defdisplay(**kwargs):
fork,vinkwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
display(rno=100,name="Karthi",marks=70,subject="Python")

n1 = 10
n2 = 20
n3 = 30
rno = 100
name=Karthi
marks
= 70
subject =
Case Study:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…16/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Output:

b) Writea Python programto return multiple valuesat a timeusing a return statement.

InotherlanguageslikeC,C+
+andJava,functioncanreturnatmostonevalue.ButinPython,afunction can return any number

Eg: Python program to return multiple values at a time using a return statement.

In [8]:

defcalc(a,b) # Here, 'a'&'b' are called positional


: arguments
sum=a+
b
sub=a-
b
returnsum,sub,mul,div
a,b,c,d=calc(100,50) #Positional
arguments
print(a,b,c,d)

150 50 5000 2.0

AlternateWay:

In
[10]:
defcalc(a,b):#PositionalArguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,d
of values.
150
50
5000
2.0

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…17/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[11]:
defcalc(a,b): # keyword arguments Arguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,div
t=calc(a=100,b=50)#keyword arguments Arguments
150
50
5000
2.0

In [12]:

defcalc(a,b):#keywordargumentsArguments
sum=a+
b
sub=a-
b
mul=a*
b
div=a/
b
returnsum,sub,mul,div
150
50
5000
2.0

c) Writea Pythonprogram todemonstrate Localand Global variables.

Python supports 2 types of variables.

1. Global Variables
2. Local Variables

1. Global Variables:

Thevariableswhicharedeclaredoutsideoffunctionarecalledglobalvariables.
These variables can be accessed in all functions of that module.

Consider the following example,

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…18/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[50]:
a=10 # Global Variables
deff1():
a=20 # Local variable to the function
print(a 'f1' # 20
)
deff2(): # 10
print(a
)
f1()
f2()

20
10

Supposeourrequirementis,wedon'twantlocalvariable.Canyoupleasereferthelocalvariableasthe
global variable only. How you can do that?

For that, one special keyword is used, called as global.

global keyword:

Wecan useglobal keywordfor thefollowing 2 purposes:

1. Todeclareglobalvariablesexplicitlyinsidefunction.
2. Tomakeglobalvariableavailabletothefunctionsothatwecanperformrequiredmodifications.

In [51]:

a=10
deff1():
a=777
print(a)
deff2():
print(a)
f1()
f2()

777
10

In [52]:

a=10
deff1():
globala
# To bring global variable to the function for required modification
a=777
# we are changing the value of the local variable
print(a)
deff2():
print(a)
f1()
f2()

777
777
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…19/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[55]:
deff1():
xy=10 # local variable of
print(xy 'f1()'
)
deff3():
print(xy)# local variableof 'f1()' can notaccessed by function
f1( 'f2()'
)
f3(
10

--------------------------------------------------------------------------
-
NameError Traceback(mostrecentcalllas t)
<ipython-input-55-b39491c6c549>in<module>
5

6f1()
---->7f3()

<ipython-input-55-b39491c6c549>inf3()
3 print(xy)
4 deff3():
----> 5

print(xy)#localvariableof'f1()'cannotaccessedbyfunct ion
'f2()'
6f1()
7f3()

Here,ifyoumake'xy'off1()asaglobalvariable,problemwillbesolved.Howcanyoumake'xy'asglob
al variable?

In
[56]:
deff1():
globalxy
xy = 10 # local variable of
print(xy 'f1()'
)
deff3():
print(xy)# local variableof 'f1()' can notaccessed by function
f1( 'f2()'
)
f3(
print(xy)#localvariableof'f1()'cannotaccessedbyfunct ion
'f2()'
10
10

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…20/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[57]:
deff1():
globalxy=1 # This syntax is invalid in Python
0
print(xy)
deff3():
print(xy)
f1()
f3()
File"<ipython-input-57-8cc65cca44b9>", line2
global xy = 10 #This syntax is invalid in Python
^
SyntaxError:invalid syntax

Another Example:

In [58]:

deff1():
global
a a =
888
print('f1 :',a)
deff2():
globala
a=999 # global variable 'a' is overrides the old value.
print('f2:',a)
f1()
f2()
f1 : 888
f2 : 999

In [59]:

deff1():
global
a a =
888
print('f1 :',a)
deff2():
global
a
a=999
print('f2 :',a)
deff3():
print('f3:',a)
f1()
f2()
f1 : 888
f2 : 999
f3 : 999

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…21/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [60]:

deff1():
global
a a =
888
print('f1 :',a)
deff2():
global
a
a=999
print('f2 :',a)
deff3():
print('f3:',a)
f3()
f1()
f3 : 999
f1 : 888
f2 : 999

In [61]:

deff1():
global
a a =
888
print('f1 :',a)
deff2():
global
a
a=999
print('f2 :',a)
deff3():
print('f3:',a)
f3()
f2()
f3 : 999
f2 : 999
f1 : 888

In [62]:

deff1():
global
a a =
888
print('f1 :',a)
deff2():
global
a
a=999
print('f2 :',a)
deff3():
a=1000
print('f3:',a)
f3()
f2()
f3 : 100
0
f2 : 999
f1 : 888
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…22/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Another Example:

In [63]:

deff1():
globala
a = 888 # global variable 'a' is overrides the old value.
print('f1 :',a)
deff2():
global
a
a=999
print('f2:',a)
f2()
f1()
f2 : 999
f1 : 888

Note:

Ifglobalvariableandlocalvariablehavingthesamename,thenwecanaccessglobalvariableinsidea
function using

In
[64]:
a=10 #global
deff1(): variable
a=777 #local
print(a variable
)
f1(
)
77
7
In
[65]:
a=10 #global
deff1(): variable
a=777 #local
print(a variable
)
print(globals()
['a'])
f1(
)
777
10

Another Example:

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…23/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [66]:

deff1():
a=10
# SyntaxError: name 'a' is assigned to before global declaration
global
a a =
50
print(a)
f1()
File"<ipython-input-66-
0a90027f8ff2>",line4 global a
^
SyntaxError:name 'a' is assigned to before global declaration

In [67]:

deff1():
global
a a =
10
a=50
print(a)
f1()
50

d) Demonstrate lambda functions in Python with suitable example programs.

Sometimes we can declare a function without any name,such type of nameless functions are
called
anonymous functionsorlambda functions.
The main purpose of anonymous function is just for instant use(i.e., for one time usage).

Normal Function:

We can define by using def keyword.

defsquareIt(n)
: return
n*n

lambda Function:

We can define by using lambda keyword

lambda n:n*n

Syntax of lambda Function:

lambda argument_list : expression

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…24/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Note:

ByusingLambdaFunctionswecanwriteveryconcisecodesothatreadabilityoftheprogramwillbe
improved.

Q1.Write a programto create a lambdafunction to findsquare of given number.

In [1]:

s=lambdan:n*n
print("TheSquareof4is:",s(4))
print("TheSquare of5 is :",s(5))

TheSquareof4is:16 The
Square of 5 is : 25

Q2.Write a programto create a Lambdafunction to find sumof 2 given numbers.

In [2]:

s=lambdaa,b:a+b
print("TheSum of10,20 is:",s(10,20))
print("TheSum of100,200
is:",s(100,200))
The Sum of 10,20 is: 30
The Sum of 100,200 is: 300

Q3.Writea program tocreate a LambdaFunction to findbiggest of given values.

In [3]:

s=lambdaa,b:aifa>belseb
print("TheBiggest of10,20
is:",s(10,20))
print("TheBiggest of100,200 is:",s(100,200))
The Biggest of 10,20 is: 20
The Biggest of 100,200 is: 200

Note:

LambdaFunctioninternallyreturnsexpressionvalueandwearenotrequiredtowritereturnstatement
explicitly.

Sometimeswecanpassafunctionasargumenttoanotherfunction.Insuchcaseslambdafunctionsare
best choice.
Wecanuselambdafunctionsverycommonlywithfilter(),map()andreduce()functions,becausethese
functions expect function as argument.

1. filter() function:

Wecanusefilter()functiontofiltervaluesfromthegivensequencebasedonsomecon
dition. For example, we have 20 numbers and if we want to retrieve only

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…25/28
17/06/20 Python Programming Lab Manual -
21 even numbers from them. RGMCET(Autonomous)

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…26/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Syntax:

filter(function,sequence)

Where,

functionargumentisresponsibletoperformconditional
check. sequence can be list or tuple or string.

Q1.Programtofilteronlyevennumbersfromthelistbyusingfilter()function. Without

lambda Function:

In [4]:
defisEven(x):
ifx%2==0:
returnTrue
else:
returnFalse
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1)

[0, 10, 20,


30]

WithlambdaFunction:

In
[5]:
l=[0,5,10,15,20,25,30]
l1=list(filter(lambdax:x
%2==0,l)) print(l1) #[0,10,20,30
l2=list(filter(lambdax:x%2! ]
=0,l)) print(l2) #[5,15,25
]
[0, 10, 20, 30]
[5, 15, 25]

2. map() function:

Foreveryelementpresentinthegivensequence,applysomefunctionalityandgeneratenewelement
with the required modification. For this requirement we should go for map() function.

Syntax:

map(function,sequence)

The function can be applied on each element of sequence and generates new sequence.

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…27/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Q1:Foreveryelementpresentinthelist,performdoubleandgeneratenewlistofdoubles. Without

lambda:

In [6]:
l=[1,2,3,4,5]
defdoubleIt(x)
:
return2*x
l1=list(map(doubleIt,l))
print(l1)
[2, 4, 6, 8, 10]

With lambda:

In [7]:

l=[1,2,3,4,5]
l1=list(map(lambdax:2*x,l)
) print(l1)

[2, 4, 6, 8, 10]

Q2: Find square of given numbers using map() function.

In [8]:

l=[1,2,3,4,5]
l1=list(map(lambdax:x*x,l)
) print(l1)

[1, 4, 9, 16, 25]

Wecan apply map() functionon multiple lists also.Butmake sure all listshould have same length.

Syntax:

map(lambda x,y:x*y,l1,l2))

x is from l1 and y is from l2

In [9]:

l1=[1,2,3,4]
l2=[2,3,4,5]
l3=list(map(lambdax,y:x*y,l1,l2)
) print(l3)

[2, 6, 12, 20]

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…28/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[10]:
l1=[1,2,3,4,5,6,7]#Theextraelementswillbe ignored
l2=[2,3,4,5]
l3=list(map(lambdax,y:x*y,l1,l2)
) print(l3)

[2, 6, 12, 20]

3. reduce() function:

reduce() function reduces sequence of elements into a single element by applying the
specified function.

Syntax:

reduce(function,sequence)

Note:

reduce() function present in functools module and hence we should write import statement.

Eg 1:

In [11]:

fromfunctoolsimport*
l=[10,20,30,40,50]
result=reduce(lambdax,y:x+y,
l) print(result) # 150

150

Eg 2:

In [12]:

fromfunctoolsimport*
l=sum([10,20,30,40,50
])
# result=reduce(lambda x,y:x*y,l)
print(l)#150
150

Eg 3:

In [13]:

fromfunctoolsimport*
l=[10,20,30,40,50]
result=reduce(lambdax,y:x*y,
l) print(result) #12000000

12000000

Eg 4:
localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -
RGMCET(Autonomous).ipynb?dow…29/28
17/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[14]:
fromfunctoolsimport*
result=reduce(lambdax,y:x+y,range(1,101))
print(result) #5050

5050

Good Luck

localhost:8889/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Python Programming Lab Manual -


RGMCET(Autonomous).ipynb?dow…30/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 12: Searching and Sorting Techniques

Implement the following Searching and Sorting techniques in Python by using functions.

i) Linear Search ii) Binary Search

iii) Selection Sort iv) Bubble Sort

v) Insertion Sort vi) Merge Sort viii) Quick


Sort

Searching Techniques:

Searchingistheprocessoffindingthelocationofatargetelementamongalistofelements.

Here, we are going to discuss about the following two searching techniques:

1. Sequential search or linear search


2. Binary search

1. Sequential search or linear search Technique:


This is the simplest of all searching techniques.
In this method the list is need not be in sorted order.
Thekeyelementwhichistobesearchediscomparedwitheachelementofthelistonebyone.Ifmatch
exists,
element is found. Otherwise end of list is reached, means search fails, element not found in
the list.

Procedure:

1. Read the search element from the user.


2. Compare the search element with the first element in the list.
3. If both are matched, then display "Given element is found!!!" and terminate the function.
4. If both are not matched, then compare search element with the next element in the list.
5. Repeat steps 3 and 4 until search element is compared with last element in the list.
6. Iflastelementinthelistalsodoesn'tmatch,thendisplay"Elementisnotfound!!!"andterminatethe
function.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Advantages:

It is a simple technique.
This technique works well for lists with smaller size.
The elements in the list need not be in any sorted order.

Disadvantage:

Thismethodisinefficientwhenlargenumberofelementsareplacedinlist,becausetimetakenfor search is
more.

Python program to implement Linear search technique.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[44]:
n=int(input("Enterthenumberofelementsinthearray:")
) i=0 flag=0
a=[iforiinrange(n)]
foriinrange(0,n):
a[i]=int(input("Enterthe{}elementofthearray:".format(i+1)))
foriinrange(0,n):
print (a[i])
key=int(input("EntertheKeyelementtobesearched"))
foriinrange(0,n):
ifa[i]==key:
print("Keyelementfoundat",i+1,'Position') flag
= 1
brea
k ifflag==0:
print("Keyelement notfound !!!")

Enterthenumberofelementsinthearray:3

Enter the 1 element of the array :33


Enterthe2elementofthearray:33
Enterthe3elementofthearray:33 33
33
33
EntertheKeyelementtobesearched33
Key element found at 1 Position

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[45]:
n=int(input("Enterthenumberofelementsinthearray:")
) i=0 flag=0
a=[iforiinrange(n)]
foriinrange(0,n):
a[i]=int(input("Enterthe{}elementofthearray:".format(i+1)))
foriinrange(0,n):
print (a[i])
key=int(input("EntertheKeyelementtobesearched"))
foriinrange(0,n
):
ifa[i]==key:
print("Keyelementfoundat",i+1,'Position') flag
= 1
brea
k ifflag==0:
print("Keyelement notfound !!!")

Enterthenumberofelementsinthearray:5 Enter the


1 element of the array :3
Enter the 2 element of the array :4
Enter the 3 element of the array :5
Enterthe4elementofthearray:22
Enterthe5elementofthearray:77 3
4
5
22
77
EntertheKeyelementtobesearched5555
Key element not found !!!

AlternativeWay:

In [2]:

n=int(input("Enterthevalueofn: "))
l=[int(x)forxininput("Enter{0}numbers:".format(n)).split()] key
=int(input("Enter an item to be check in the list
: ")) pos=-1
foriinrange(n):
if(l[i]==key):
pos = i
brea
k if(pos!=-
1):
print("Theelement{0}ispresentattheindexof{1}inthegivenlist". format(key,pos))
else:
print("Theelement {0}is notpresent in the given list".format(key))

Enter the value of n: 5


Enter 5 numbers : 3 6 9
4 5
Enter an item to be check in the list : 5
The element 5 is present at the index of 4 in the given list

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [4]:

n=int(input("Enterthevalueofn: "))
l=[int(x)forxininput("Enter{0}numbers:".format(n)).split()] key
=int(input("Enter an item to be check in the list
: ")) pos=-1
foriinrange(n):
if(l[i]==key):
pos = i
brea
k if(pos!=-
1):
print("Theelement{0}ispresentattheindexof{1}inthegivenlist". format(key,pos))
else:
print("Theelement {0}is notpresent in the given list".format(key))

Enter the value of n: 5


Enter 5 numbers : 7 77 77777 777 7777777
Enter an item to be check in the list :
7777
The element 7777 is not present in the given list

2. Binary Search Technique:

Binary search is another simple searching method.


Toimplementbinarysearchmethod,theelementsofthelistmustbeinsortedorder.Soyoucanapp
ly any one of the sorting technique before using the binary search (for example bubble
sort).
Biary Search method make use of divide and conquer strategy.

Procedure:

Binarysearchalgorithmworksontheprincipleofdivideandconquer.Forthisalgorithmtoworkproperly,
the data collection should be in the sorted form.
Binarysearchlooksforaparticularitembycomparingthemiddlemostitemofthecollection. If a
match occurs, then the index of item is returned.
Ifthemiddleitemisgreaterthantheitem,thentheitemissearchedinthesub-arraytotheleftofthe
middle item. Otherwise, the item is searched for in the sub-array to the right of the middle
item.
This process continues on the sub-array as well until the size of the sub-array reduces to zero.

How Binary Search Works?

For a binary search to work, it is mandatory for the target array to be sorted. We shall learn
the process of
binarysearchwithapictorialexample.Thefollowingisoursortedarrayandletusassumethatwenee
dto search the location of value 31 using binary search.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…5/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)
First, we shall determine half of the array by using the below formula −

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

mid = low + (high - low) / 2

Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Nowwecomparethevaluestoredatlocation4,withthevaluebeingsearched,i.e.31.Wefindthattheva
lue at location 4 is 27, which is not a match. As the value is greater than 27 and we have a
sorted array, so we also know that the target value must be in the upper portion of the array.

Wechangeourlowtomid+1andfindthenewmidvalueagain. low = mid

+1

mid = low + (high - low) / 2

Ournewmidis7now.Wecomparethe valuestoredatlocation7withourtargetvalue 31.

Thevaluestoredatlocation7isnotamatch,ratheritislessthanwhatwearelookingfor.So,thevaluem
ust be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Wecompare thevalue storedat location5 with ourtarget value.We findthat itis a match.

Weconclude thatthe target value31 is storedat location 5.

Advantage:

Binarysearchhalvesthesearchableitemsandthusreducesthecountofcomparisonstobemad
eto very less numbers.

Disadvantage:

This algorithm requires the list to be sorted,then only this method is applicable.

Python program to implement Binary search technique.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[2]:
defbinary_search(a,n,key):
low=0
high=n-1
while(low<=high):
mid=int((low+high)/2)
if(key==a[mid]):
return mid
elif(key<a[mid]
):
high=mid-1
else:
low=mid+1
return-1

n=int(input("Enterthenumberofelements:")) a=[i
for i in range(n)]
foriinrange(0,n):
a[i]=int(input("Enterthe{}elementofthearray:".format(i+1)))
k=int(input("Enter the key element to be searched :"))
position=binary_search(a,n,k)
if(position!=-1):
print("Key element found at ",(position))
else:
print("Key element not found !!!")

Enter the number of elements : 5


Enterthe1elementofthearray:23
Enterthe2elementofthearray:45
Enterthe3elementofthearray:67
Enterthe4elementofthearray:79
Enter the 5 element of the
array :90
Enterthekeyelementtobesearched:79

Key element found at3

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [1]:

defbinary_search(a,n,key):
low=0
high=n-1
while(low<=high):
mid=int((low+high)/
2) if(key==a[mid]):
return mid
elif(key<a[mid]
): high=mid-
1
else:
low=mid+1
return-1

n=int(input("Enterthenumberofelements:")) a=[i
for i in range(n)]
foriinrange(0,n):
a[i]=int(input("Enterthe{}elementofthearray:".format(i+1)))
k=int(input("Enter the key element to be searched :"))
position=binary_search(a,n,k)
if(position!=-1):
print("Key element found at ",(position))
else:
print("Key element not found !!!")
Enter the number of elements : 5
Enterthe1elementofthearray:11
Enterthe2elementofthearray:12
Enterthe3elementofthearray:13
Enterthe4elementofthearray:14
Enter the 5 element of the
array :15
Enterthekeyelementtobesearched:100

Key element not found !!!

How Linear search is different from Binary search?

Linearsearchstartsatthebeginningofalistofvalues,andchecks1by1inorderfortheresultyouare
looking for.
Abinarysearchstartsinthemiddleofasortedarray,anddetermineswhichside(ifany)thevalueyou
are looking for is on.

Sorting Techniques:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…10/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Sortingreferstoarrangingdatainaparticularformat.Sortingalgorithmspecifiesthewaytoarrangedataina
particular order. Most common orders are numerical or lexicographical orders.

Theimportanceofsortingliesinthefactthatdatasearchingcanbeoptimizedtoaveryhighlevel,ifdat
ais stored in a sorted manner.

Sorting is also used to represent data in more readable formats.

Belowweseefivesuchsortingtechniquesimplementationsinpython.

1. Selection Sort
2. Bubble Sort
3. Insertion Sort
4. Merge Sort
5. Quick Sort

1. Selection Sort:

Selection sort is also known as push-down sorting. As the name suggests the first element of the
list is
selected.Itiscomparedwithalltheelements.Ifanyelementisfoundtobelesserthantheselectedelement,
these two are interchanged. This procedure is repeated till all the elements in the list are sorted.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…11/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…12/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Advantages:

The main advantage of the selection sort is that it performs well on a small list.
Becauseitisanin-placesortingalgorithm,noadditionaltemporarystorageisrequiredbeyondwhatis
needed to hold the original list.
Its performance is easily influenced by the initial ordering of the items before the sorting
process.

Disadvantages:

Theprimarydisadvantageoftheselectionsortisitspoorefficiencywhendealingwithahugeli
stof items. The selection sort requires n-squared number of steps for sorting 'n'
elements.

Python program to implement Selection Sort technique:

In [3]:

defselectionSort(a):
foriinrange(len(a)):
least=i
forkinrange(i+1,len(a)
): ifa[k]<a[least]:
least=k
temp=a[least
]
a[least]=a[i
] a[i]=temp

a=[50,30,10,20,40,70,60]
print("Original list",a)
selectionSort(a) # Calling to the function
print("Selection Sort:",a)
Original list [50, 30, 10, 20, 40, 70, 60]
Selection Sort: [10, 20, 30, 40, 50, 60, 70]

AlternativeWay:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…13/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [6]:

a=list(map(int,input("EnterlistElements:").split()))
print("Beforesortingtheelementsinthelistare:",a)
for i in range(0,len(a)-1,1):
min=i
forjinrange(i+1,len(a),1
): if(a[j]<a[min]):
min =
j temp=a[min]
a[min]=a[i]
a[i] = temp
print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: 10 4 23 65 42 33


Before sorting the elements in the list are:[10, 4, 23, 65, 42, 33]
After sorting the elements in the list are:[4, 10, 23, 33, 42, 65]

In [7]:

a=list(map(int,input("EnterlistElements:").split()))
print("Beforesortingtheelementsinthelistare:",a)
for i in range(0,len(a)-1,1):
min=i
forjinrange(i+1,len(a),1
): if(a[j]<a[min]):
min =
j temp=a[min]
a[min]=a[i]
a[i] = temp
print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: -23 -45 1 2 -77 55


Before sorting the elements in the list are:[-23, -45, 1, 2, -77, 55]
After sorting the elements in the list are:[-77, -45, -23, 1, 2, 55]

2. Bubble Sort:

Thisisthesimplestandoldestsortingtechniquewhencomparedwithalltheothersortingtechniqu
es. It is also called as exchange sort.
In this sorting technique the adjacent elements are compared and interchanged if necessary.

Procedure:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

1. Comparefirstandsecondelements.Ifthefirstelementisgreaterthanthesecondele
ment,then interchange these two elements.
2. Comparesecondandthirdelements.Ifthesecondelementisgreaterthanthirdelementth
enmakean interchange.
3. Theprocess is repeated till the last and second last element is compared and swapped if
necessary.

Thiscompletesthefirstpass.Attheendofthefirstpass,thelargestelementwillgetitsexactfinal
position i.e., it occupies the last position.

Thestep-1tostep-3arerepeatedn-1timesfortheelementsbetween1ton-1becausethenthelementis

already sorted. After completion of n-1 passes, the list is in sorted order.

Advantages:

Itisrelativelyeasytowriteandunderst
and. Straight forward approach.
Works well for smallest list of elements.
Performance is good for nearly sorted
list.

Disadvantages:

Itrunsslowlyandhenceitisnotefficient,becauseEveniftheelementsaresorted,n-1iterationsare
required to sort. It is not used for sorting the list of larger size.
Itisinsufficientalgorithmbecausethenumberofiterationsincreaseswithincreaseinnumberof
elements to be sorted.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Python program to implement Bubble Sort technique:

In [1]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
forjinrange(0,len(a)-1-i,1):
if(a[j]>a[j+1]):
temp = a[j]
a[j]=a[j+1]
a[j+1]= temp
print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: 2 3 11 55 33 -6


Before sorting the elements in the list are:[2, 3, 11, 55, 33, -6]
After sorting the elements in the list are:[-6, 2, 3, 11, 33, 55]

In [2]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
forjinrange(0,len(a)-1-i,1):
if(a[j]>a[j+1]):
temp = a[j]
a[j]=a[j+1]
a[j+1]= temp
print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: -666 -333 -5 0 -66 1 4 6 3


Before sorting the elements in the list are:[-666, -333, -5, 0, -66, 1,
4, 6, 3]
After sorting the elements in the list are:[-666, -333, -66, -5, 0, 1,
3, 4, 6]

3. Insertion Sorting:

Theinsertionsortprocedureissimilartothewayweplaycards.Aftershufflingthecards,wepickeachcard
andinsertitintotheproperplacebyshifttheremainingcards.Thisprocessisrepeateduntilallthecardsin
the
hand are
in the correct sequence. So that cards in hand are arranged in ascending order.

Procedure:

Select the second element in the list and compare it with the first element.

Ifthefirstelementisgreaterthanthesecondelementthenthesecondelementisinsertedatfirstlocati
on by shifting the first element to the second position. Otherwise proceed with the next step.
Selectthethirdelementinthelistandcompareitwiththetwosortedelementsandinsertatthe
appropriate position.

Selectfourthelementandcompareitwithpreviousthreesortedelementsandinsertitinproperpositio
localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…16/28
16/06/20 Python Programming Lab Manual -
21 n among the elements which are compared.
RGMCET(Autonomous)

Repeat the process until we get sorted list. The entire list gets sorted within (n-1)thpass.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…17/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Advantages:

The main advantage of the insertion sort is its simplicity.


It also exhibits a good performance when dealing with a small list.
The insertion sort is an in-place sorting algorithm so the space requirement is minimal.

Disadvantages:

Thedisadvantageoftheinsertionsortisthatitdoesnotperformaswellasother,bettersorting
algorithms.
With'n-squared'stepsrequiredforevery'n'elementtobesorted,theinsertionsortdoesnotdealwell
with a huge list.
The insertion sort is particularly useful only when sorting a list of few items.

Python Program to implement Insertion Sort Technique:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…18/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[10]:
a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
j=i-1
temp=a[i]
while(j>=0):
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: 7 9 3 1 10 99


Before sorting the elements in the list are:[7, 9, 3, 1, 10, 99]
After sorting the elements in the list are:[1, 3, 7, 9, 10, 99]

In [11]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
j=i-1
temp=a[i]
while(j>=0):
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: 9999 99 9 999 99999


Before sorting the elements in the list are:[9999, 99, 9, 999, 99999]
After sorting the elements in the list are:[9, 99, 999, 9999, 99999]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…19/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[12]:
a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
j=i-1
temp=a[i]
while(j>=0)
:
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)


Enter list Elements: -666 -333 -5 0 -66 1 4 6 3
Before sorting the elements in the list are:[-666, -333, -5, 0, -66, 1,
4, 6, 3]
After sorting the elements in the list are:[-666, -333, -66, -5, 0, 1,
4, 6, 3]

In [14]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
j=i-1
temp=a[i]
while(j>=0)
:
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)


Enter list Elements: -6 -45 3
Beforesortingtheelementsinthelistare:[-6,-45,3]
After sorting the elements in the list are:[-45,
-6, 3]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…20/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a)-1,1):
j=i-1
temp=a[i]
while(j>=0):
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: -5 -4 -3 -2 -1


Before sorting the elements in the list are:[-5, -4, -3, -2, -1]
After sorting the elements in the list are:[-5, -4, -3, -2, -1]

In [17]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a),1):
j=i-1
temp=a[i]
while(j>=0):
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: -1 -2 -3 -4 -5


Before sorting the elements in the list are:[-1, -2, -3, -4, -5]
After sorting the elements in the list are:[-5, -4, -3, -2, -1]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…21/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [18]:

a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are:
",a) for i in range(0,len(a),1):
j=i-1
temp=a[i]
while(j>=0):
if(a[j]>temp):
a[j+1]=a[j] j
= j-1
else:
break
a[j+1]=temp

print("Aftersorting the elements inthe list are: ",a)

Enter list Elements: 7 -23 5 -45


Before sorting the elements in the list are:[7, -23, 5, -
45] After sorting the elements in the list are:[-45, -23,
5, 7]

4. Merge Sort:

MergesortwasinventedbyJohnVonNeumann(1903-1957).
This sorting method uses divide and conquer method.
Thebasicconceptofmergesortistodividethelistintotwosmallersub-listsofapproximatelyequalsize
and continue splitting process until each sub list contains only one element.
Afterthis,mergethetwopartscontainingoneelementintoonesortedlistandContinuemergingpa
rts until finally there is only one sorted list.
Merge sort is one of the most efficient sorting algorithm.

Procedure:

1. Consider the initial list and divide the list into two sub-lists.
2. Againthesesub-listsaredividedintomanynumbersofsub-listsuntileachandeverysub-
listcontains single element.
3. Combine these sub-lists into sorted order.
4. Finally we will get list of elements in sorted order.

Digrammatic representation of Merge Sort Process:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…22/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Example:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…23/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…24/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Advantages:

1. It can be applied to files of any size.


2. Goodfor linked lists. Can be implemented in such a way that data is accessed sequentially.
3. It perform in O(n log n ) in the worst case.

Disadvantages:

1. Merge Sort requires more space than other sort.

Python Program to Implement Merge Sort Technique:

In [8]:

defmergeSort(a)
:
iflen(a)>1:
mid=len(a)//2
left= a[:mid]
right=a[mid:]
mergeSort(left)
mergeSort(right)
i=0
j=0
k=0
whilei<len(left)andj<len(right):
ifleft[i]<right[j]:
a[k]=left[i
] i+=1
else:
a[k]=right[j
] j+=1
k+=1
whilei<len(left):
a[k]=left[i] i
+= 1
k+=1

whilej<len(right)
:
a[k]=right[j]
j+=1
k+=1
a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are: ",a)
mergeSort(a) print("Aftersorting the elements inthe list are:
Enter list Elements: 65 76 23 98 22 11 22
Before sorting the elements in the list are:[65, 76, 23, 98, 22, 11, 22]
After sorting the elements in the list are:[11, 22, 22, 23, 65, 76, 98]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…25/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
defmergeSort(a
):
iflen(a)>1
:
mid=len(a)//2
left = a[:mid]
right = a[mid:]
mergeSort(left)
mergeSort(right
) i=0
j=
0
k=
0
whilei<len(left)andj<len(right
): ifleft[i]<right[j]:
a[k] =
left[i] i+=1
else:
a[k]=right[
j] j+=1
k+=1
whilei<len(left): a[k]
=
left[i]
i+=1
k+=1

whilej<len(right): a[k]
= right[j]
j+=1
k+=1
a=list(map(int,input("EnterlistElements:").split()))
Enter list Elements: 2 3 6 1 4 5
Before sorting the elements in the list are:[2, 3, 6, 1, 4, 5]
After sorting the elements in the list are:[1, 2, 3, 4, 5, 6]

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…26/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[9]:
defmergeSort(a
):
iflen(a)>1:
mid=len(a)//2
left = a[:mid]
right = a[mid:]
mergeSort(left)
mergeSort(right
) i=0
j=0
k=0
whilei<len(left)andj<len(right):
ifleft[i]<right[j]:
a[k] =
left[i] i+=1
else:
a[k]=right[j
] j+=1
k+=1
whilei<len(left): a[k]
=
left[i]
i+=1
k+=1

whilej<len(right): a[k]
= right[j]
j+=1
k+=1
a=list(map(int,input("EnterlistElements:").split()))
print("Before sorting the elements in the list are: ",a)
mergeSort(a) print("Aftersorting the elements inthe list are:
",a)
Enter list Elements: 9999 9 999 99 9999999
Before sorting the elements in the list are:[9999, 9, 999, 99, 9999999]
After sorting the elements in the list are:[9, 99, 999, 9999, 9999999]

5. Quick Sort:

This sorting is also called as partition exchange sorting.


This method is based on divide and conquer technique.
Theentirelistisdividedintovariouspartitionsandsortingprocedureisappliedagainandagainonthe
partitions.

Procedure:

Divide the collection in two (roughly) equal parts by taking a pseudo-random element and
using it as a
pivot element.

Elementssmallerthanthepivotgetmovedtotheleftofthepivot,andelementslargerthanthepivo
tto the right of it.

Thisprocessisrepeatedforthecollectiontotheleftofthepivot,aswellasforthearrayofelementst
localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…27/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[9]:o the right of the pivot until the whole array is sorted.

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…28/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Digrammatic representation of Quick Sort Process:

Advantages:

Thequicksortisconsideredasthebestsortingalgorith
m. It is able to deal well with a huge list of items.
Because it sorts in place, no additional storage is

Disadvantages:

Theslightdisadvantageofquicksortisthatitsworst-caseperformanceissimilartoaverage
performances of the bubble, insertion or selections sorts.
If the list is already sorted, then bubble sort is much more efficient than quick sort.

Python Program to Implement Quick Sort Technique:

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…29/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…30/28
16/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Good Luck

localhost:8888/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…31/28
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Experiment 13: Regular Expressions

Introduction:

IfwewanttorepresentagroupofStringsaccordingtoaparticularformat/
patternthenweshouldgofor Regular Expressions. i.e., Regualr Expressions is a
declarative mechanism to represent a group of Strings accroding to particular
format/pattern.

Eg 1:

Wecanwritearegularexpressiontorepresentallmobilenumbers.(i.e.,Allmobilenumbershavinga
particular format i.e., exactly 10 numbers only)

Eg 2:

We can write a regular expression to represent all mail ids.

Eg 3:

We can write a regular expression to represent all java/python/C identifiers.

Note: Regular Expressions is language independent concept.

The main important application areas of Regular Expressions are as follows:

1. Todevelopvalidationframeworks/
validationlogic.Forexample,mailidvalidation,mobilenumber validation etc.
2. TodevelopPatternmatchingapplications(ctrl-finwindows,grepinUNIX etc).
3. TodevelopTranslatorslikecompilers,interpretersetc.Incompilerdesign,Lexicalanaly
sisphaseis internally implemented using Regular expressions only.
4. Todevelopdigitalcircuits.Forexample,BinaryIncrementor,Binaryadder,Binarysubtractor etc.
5. TodevelopcommunicationprotocolslikeTCP/IP,UDPetc.
(Protocolmeanssetofrules,tofollowthe rules during communication, we use regular
expressions).

a) Demonstratethefollowingin-builtfunctionstouseRegularExpressionsveryeasilyinour
applications.

i) compile() ii) finditer() iii) match() iv) fullmatch()

v) search() vi) findall() vii) sub() viii) subn() ix) split()

re module:

We can develop Regular Expression Based applications by using python module


known as re. Thismodulecontainsseveralin-
builtfunctionstouseRegularExpressionsveryeasilyinour applications.

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…1/20
18/06/20 Python Programming Lab Manual -
21 i) compile(): RGMCET(Autonomous)

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…2/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

re module contains compile() function to compile a pattern into RegexObject.

Forexample,ifyouwanttofindthepattern'python'inthegivenstring,firstyouneedtoconvertthispatte
rn into RegexObject form.

In [1]:

importre
pattern=re.compile("python
") print(type(pattern))

<class 're.Pattern'>

ii) finditer():

It returns an Iterator object which yields Match object for every Match.

In [ ]:

matcher=pattern.finditer("Learningpython isvery easy...")

On Match object we can call the following methods.

1. start() ==> Returns start index of the match

2. end()==> Returns end+1 index of the match

3. group()==> Returns the matched string

Q1:Write a Python programto find whether the givenpattern is available inthe given string or not?

In [2]:

importre
count=0
pattern=re.compile("pytho
n")
matcher=pattern.finditer("Learningpythonisveryeasy...")
formatchinmatcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences: ",count)
9 ... 15 ... python
The number of occurrences:1

Note: More Simplified form

Wecan passpattern directlyas argumentto finditer() function.

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…3/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[3]:
importre
count=0
matcher=re.finditer("ab","abaabab
a") formatchinmatcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences: ",count)

0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab
The number of occurrences:3

In [4]:

importre
count=0
matcher=re.finditer("ba","abaabab
a") formatchinmatcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences: ",count)

1 ... 3 ... ba
4 ... 6 ... ba
6 ... 8 ... ba
The number of occurrences:3

In [5]:

importre
count=0
matcher=re.finditer("bb","abaabab
a") formatchinmatcher:
count+=1
print(match.start(),"...",match.end(),"...",match.group())
print("The number of occurrences: ",count)

The number of

occurrences:0 In [6]:

importre
count=0
matcher=re.finditer("ab","abaabab
a") formatchinmatcher:
count+=1 print("start:{},end:{},group:
{}".format(match.start(),match.end(),match.group()))
print("The number of occurrences: ",count)

start:0,end:2,group:
ab
start:3,end:5,group:
ab
start:5,end:7,group:
ab
The number of occurrences:3

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…4/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
importre
count=0
matcher=re.finditer("ab","ababab
a") formatchinmatcher:
count+=1 print("start:{},end:{},group:
{}".format(match.start(),match.end(),match.group()))
print("The number of occurrences: ",count)

start:0,end:2,group:
ab
start:2,end:4,group:
ab
start:4,end:6,group:
ab
The number of occurrences:3

Required Information to understand Regular Expressions:

I. Character classes:

Wecan usecharacter classes tosearch agroup of characters.

1. [abc]===>Either a or b or c
2. [^abc] ===>Except a and b and c
3. [a-z]==>Any Lower case alphabet symbol
4. [A-Z]===>Any upper case alphabet symbol
5. [a-zA-Z]==>Any alphabet symbol
6. [0-9] Any digit from 0 to 9
7. [a-zA-Z0-9]==>Any alphanumeric character
8. [^a-zA-Z0-9]==>Except alphanumeric characters(Special Characters)

Example Programs:

In [8]:

importre
matcher=re.finditer("[abc]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
2........b

In [9]:

importre
matcher=re.finditer("[^abc]","a7b@k
9z") formatchinmatcher:
print(match.start(),".. .",match.group())

1.......7
3........@
4........k
localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Autono…5/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[7]:
5 9
6........z

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…6/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[10]:
importre
matcher=re.finditer("[a-z]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

0 ...... a
2 ...... b
4 ...... k
6 ...... z

In [11]:

importre
matcher=re.finditer("[0-9]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

1 7
5.......9

In
[12]:
importre
matcher=re.finditer("[A-Z]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group( # No uppercase
)) letters
In
[13]:
importre
matcher=re.finditer("[a-zA-Z]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

0 ...... a
2 ...... b
4 ...... k
6 ...... z

In [14]:

importre
matcher=re.finditer("[a-zA-Z0-9]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
1.......7
2.......b
4........k
5 9
6........z

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…7/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[15]:
importre
matcher=re.finditer("[^a-zA-Z0-9]","a7b@k9z")
formatchinmatcher:
print(match.start(),".. .",match.group())

3 @

In [16]:

importre
matcher=re.finditer("[abc]","abcabc")
formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
1.........b
2.........c
3.........a
4.........b
5.........c

In [48]:

importre
itr=re.finditer("[a-z]","a7b9c5k8z")
forminitr:
print(m.start(),"...",m.end(),"...",m.group())

0 ... 1. . . . .a
2 ... 3. . . . .b
4 ... 5. . . . .c
6 ... 7. . . . .k
8 ... 9. . . . .z

II. Pre defined Character classes:

\s ==> Space character

\S ==> Any character except space character

\d ==> Any digit from 0 to 9

\D ==> Any character except digit

\w ==> Any word character [a-zA-Z0-9]

\W ==> Any character except word character (only Special Characters includes)

. ==> Any character including special characters

Example Programs:

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…8/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[17]:
importre matcher=re.finditer("\
s","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

3 ......

In [18]:

importre matcher=re.finditer("\
S","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
1.......7
2.......b
4.......k
5.......@
6.......9
7.......z

In [19]:

importre matcher=re.finditer("\
d","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

1.......7
6.......9

In [20]:

importre matcher=re.finditer("\
D","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
2........b
3 ......
4........k
5........@
7.......z

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…9/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In [21]:

importre matcher=re.finditer("\
w","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
1.......7
2.......b
4........k
6.......9
7.......z

In [22]:

importre matcher=re.finditer("\
W","a7bk@9z") formatchinmatcher:
print(match.start(),".. .",match.group())

3 ......
5.......@

In [23]:

importre
matcher=re.finditer(".","a7bk@9z
") formatchinmatcher:
print(match.start(),".. .",match.group())

0........a
1 7
2.........b
3 ......
4.........k
5.........@
6 9
7........z

In [49]:

importre itr=re.finditer("\
d","a7b9c5k8z") forminitr:
print(type(m))
print(m.start(),"...",m.end(),"...",m.group(
))

<class 're.Match'>
1 ... 2. . .7
<class 're.Match'>
3 ... 4. . .9
<class 're.Match'>
5 ... 6. . .5
<class 're.Match'>
7 ... 8. . .8

III. Qunatifiers:

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…10/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

Wecanusequantifierstospecifythenumberofoccurrencestomatch

. a ==> Exactly one 'a'

a+ ==> Atleast one 'a'

a* ==> Any number of a's including zero number a?

==>Atmostone'a',i.e.,eitherzeronumberoronenumb

er a{m}

==> Exactly m number of a's

a{m,n} ==> Minimum m number of a's and Maximum n number of a's

Example Programs:

In [24]:

importre
matcher=re.finditer("a","abaabaaab")#Exactlyone'
a' formatchinmatcher:
print(match.start(),".. .",match.group())

0 ...... a
2 ...... a
3 ...... a
5 ...... a
6 ...... a
7 ...... a

In [25]:

importre
matcher=re.finditer("a+","abaabaaab")#Atleastone
'a' formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
2.......aa
5........aaa

In [26]:

importre
matcher=re.finditer("a*","abaabaaab")#Anyno.of'a'sincludingzer
o formatchinmatcher:
print(match.start(),".. .",match.group())

0 ...... a
1 ......
2 ...... aa
4 ......
5 ...... aaa
8 ......
9 ......

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Autono…11/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[27]:
importre
matcher=re.finditer("a?","abaabaaab")#Atmostone'
a' formatchinmatcher:
print(match.start(),".. .",match.group())

0.........a
1 ......
2.........a
3.........a
4 ......
5.........a
6.........a
7.........a
8 ......
9 ......

In [28]:

importre
matcher=re.finditer("a{3}","abaabaaab")#Exactly'3'numberof'a's
formatchinmatcher:
print(match.start(),".. .",match.group())

5.......aaa

In [29]:

importre
matcher=re.finditer("a{2,4}","abaabaa
ab") formatchinmatcher:
print(match.start(),".. .",match.group())

2.......aa
5.......aaa

In [30]:

importre
matcher=re.finditer("a{2,2}","abaabaa
ab") formatchinmatcher:
print(match.start(),".. .",match.group())

2.......aa
5.......aa

In [31]:

importre
matcher=re.finditer("a{1,4}","abaabaa
ab") formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a
2.......aa
5.......aaa

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…12/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[32]:
importre
matcher=re.finditer("a{2}a*","abaabaa
ab") formatchinmatcher:
print(match.start(),".. .",match.group())

2.......aa
5.......aaa

In [33]:
importre
matcher=re.finditer("[^a]","abaabaaab")#Except'a
' formatchinmatcher:
print(match.start(),".. .",match.group())

1.......b
4.......b
8.......b

Note:

^x==>Itwillcheckwhethertargetstringstartswithxorn

ot x$ ==> It will check whether target string ends

with x or not

In [34]:

importre
matcher=re.finditer("^a","abaabaaab")
formatchinmatcher:
print(match.start(),".. .",match.group())

0.......a

In [38]:

importre
matcher=re.finditer("a$","abaabaaab")
formatchinmatcher:
print(match.start(),".. .",match.group())#stringnotendswith'a'

In [37]:

importre
matcher=re.finditer("b$","abaabaaab")#Whetherthegivenstringend
sw formatchinmatcher:
print(match.start(),".. .",match.group())

8.......b

iii. match():

Wecanusematchfunctiontocheckthegivenpatternatbeginningoftargetstringor
localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -
RGMCET(Auton…13/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[32]:
not. If the match is available then we will get Match object, otherwise we
will get None.

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…14/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[39]:
importre
s=input("Enterpatterntocheck:")
m=re.match(s,"abcabdefg")#match()funct
ion ifm!=None:
print("MatchisavailableatthebeginningoftheString")
print("Start Index:",m.start(), "and End
Index:",m.end())
else:
print("Matchis not available atthe beginning of the String")
Enter pattern to check: abc
MatchisavailableatthebeginningoftheString
Start Index: 0 and End Index: 3

In [40]:

importre
s=input("Enterpatterntocheck:")
m=re.match(s,"abcabdefg")#match()funct
ion ifm!=None:
print("MatchisavailableatthebeginningoftheString")
print("Start Index:",m.start(), "and End
Index:",m.end())
else:
print("Matchis not available atthe beginning of the String")
Enter pattern to check: rgm
Match is not available at the beginning of the String

iv. fullmatch():

Wecanusefullmatch()functiontomatchapatterntoalloftargetstring.i.e.,completestringshouldbe
matched according to given pattern.
If complete string matched then this function returns Match object otherwise it returns None.

In [41]:

importre
s=input("Enterpatterntocheck
:")
m=re.fullmatch(s,"ababab")
ifm!=None:
print("FullStringMatched")
else:
print("FullStringnot Matched")
Enterpatterntocheck:ab Full
String not Matched

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…15/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[42]:
importre
s=input("Enterpatterntocheck
:")
m=re.fullmatch(s,"ababab")
ifm!=None:
print("FullStringMatched")
else:
print("FullStringnot Matched")
Enterpatterntocheck:ababa
b Full String Matched

In [43]:
importre
s=input("Enterpatterntocheck
:")
m=re.fullmatch(s,"ababab")
ifm!=None:
print("FullStringMatched")
else:
print("FullStringnot Matched")
Enterpatterntocheck:abababa
Full String not Matched

v. search():

We can use search() function to search the given pattern in the target string.
IfthematchisavailablethenitreturnstheMatchobjectwhichrepresentsfirstoccurrenceofthemat
ch. If the match is not available then it returns None.

In [44]:

importre
s=input("Enterpatterntocheck
:")
m=re.search(s,"abaabaaab")
ifm!=None:
print("Matchisavailable")
print("FirstOccurrenceofmatchwithstartindex:",m.start(),"andendindex:",m.en
d())
else:
print("Matchisnot available")
Enterpatterntocheck:aa
Match is available
First Occurrence of match with start index: 2 and end index: 4

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…16/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[45]:
importre
s=input("Enterpatterntocheck
:")
m=re.search(s,"abaabaaab")
ifm!=None:
print("Matchisavailable")
print("FirstOccurrenceofmatchwithstartindex:",m.start(),"andendindex:",m.en
d())
else:
print("Matchisnot available")
Enterpatterntocheck:bb
Match is not available

vi. findall():

This function is used to find all occurrences of the match.


This function returns a list object which contains all occurrences.

In [46]:

importre
l=re.findall("[0-9]","a7b9c5kz")
print(l)

['7', '9', '5']

vii. sub():

'sub' means substitution or replacement.

Syntax:

re.sub(regex,replacement,targetstring)

In the target string every matched pattern will be replaced with provided replacement.

In [50]:

importre
s=re.sub("[a-
z]","#","a7b9c5k8z") print(s)

#7#9#5#8#

Here, Every alphabet symbol is replaced with # symbol.

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…17/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[51]:
importre s=re.sub("\
d","#","a7b9c5k8z") print(s)

a#b#c#k#z

Here, Every digit is replaced with # symbol.

viii. subn():

It is exactly same as sub except it can also returns the number of replacements.
Thisfunctionreturnsatuplewherefirstelementisresultstringandsecondelementisnumberof
replacements.

(resultstring, number of replacements)

In [52]:

importre
t=re.subn("[a-z]","#","a7b9c5k8z")
print(t)
print("TheResultString:",t[0])
print("Thenumberof
replacements:",t[1])
('#7#9#5#8#', 5)
The Result String:
#7#9#5#8# The number of
replacements: 5

ix. split():

Ifwewanttosplitthegiventargetstringaccordingtoaparticularpatternthenweshouldgoforsplit
() function. This function returns list of all tokens.

In [53]:

importre
l=re.split(",","sunny,bunny,chinny,vinny,pinny")
print(l)
foriinl:
print(i)

['sunny','bunny','chinny','vinny','pinny
'] sunny
bunny
chinn
y
vinny
pinny

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…18/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[54]:
importre
l=re.split("\.","www.rgmcet.edu.i
n") fortinl:
print(t)

www
rgmce
t edu
in

In [55]:

importre
l=re.split("[.]","www.rgmcet.edu.in")
fortinl:
print(t)

www
rgmce
t edu
in

b) WriteaRegularExpressiontorepresentallRGMlanguage(Yourownlanguage)identifiers.

Rules:

1. The allowed characters are a-z,A-Z,0-9,#.


2. The first character should be a lower case alphabet symbol from a to k.
3. The second character should be a digit divisible by 3.
4. The length of identifier should be at least 2.

Regular Expression:

[a-k][3069][a-zA-Z0-9#]*

Writea python programto check whether thegiven string is RGMlanguage identifier or not?

In [56]:

importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:a7
a7 is not Yava Identifier

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…19/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[57]:
importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:zhd67
zhd67 is not Yava Identifier

In [58]:

importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:a
a is not Yava Identifier

In [59]:

importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:a09@
a09@ is not Yava Identifier

In [60]:

importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:f3jkgjidu
f3jkgjidu is valid Yava Identifier

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…20/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[61]:
importre
s=input('Enter Identifierto validate :')
m=re.fullmatch('[a-k][3069][a-zA-Z0-
9#]*',s) ifm!=None:
print(s,'isvalidYavaIdentifier')
else:
print(s,'isnotYavaIdentifier')

EnterIdentifiertovalidate:a6kk9z##
a6kk9z## is valid Yava Identifier

c) Writea RegularExpression to representall 10digit mobile numbers.

Rules:

1. Every number should contains exactly 10 digits.


2. The first digit should be 7 or 8 or 9

Regular Expression:

[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]

or

[7-9][0-9]{9}

or

[7-9]\d{9}

Writea Python Programto check whether thegiven number is validmobile number or not?

In [62]:

importre
s=input('EnterNumber :')
m=re.fullmatch('[7-9][0-9]
{9}',s) ifm!=None:
print(s,'isvalidMobilenumber')
else:
print(s,'isnotvalidMobilenumber')

Enter Number :9885768283


9885768283 is valid Mobile
number

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…21/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[63]:
importre
s=input('EnterNumber :')
m=re.fullmatch('[7-9][0-9]
{9}',s) ifm!=None:
print(s,'isvalidMobilenumber')
else:
print(s,'isnotvalidMobilenumber')

Enter Number :9646328281


9646328281 is valid Mobile
number

In [64]:

importre
s=input('EnterNumber :')
m=re.fullmatch('[7-9][0-9]
{9}',s) ifm!=None:
print(s,'isvalidMobilenumber')
else:
print(s,'isnotvalidMobilenumber')

Enter Number :6453124518


6453124518 is not valid Mobile number

In [65]:

importre
s=input('EnterNumber :')
m=re.fullmatch('[7-9][0-9]
{9}',s) ifm!=None:
print(s,'isvalidMobilenumber')
else:
print(s,'isnotvalidMobilenumber')

Enter Number :898989


898989 is not valid Mobile number

Few More Examples:

Q1.Write a Python Programto check whether thegiven mail id isvalid gmail id or not?

In [66]:

importre
s=input("EnterMail id:")
m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
ifm!=None:
print("ValidMailId");
else:
print("InvalidMailid")

EnterMailid:prathapnaidu81@gmail.com
Valid Mail Id

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…22/20
18/06/20 Python Programming Lab Manual -
21 RGMCET(Autonomous)

In
[67]:
importre
s=input("EnterMail id:")
m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
ifm!=None:
print("ValidMailId");
else:
print("InvalidMailid")

EnterMailid:prathapnaidu81
Invalid Mail id

Q2.WriteaPythonprogramtocheckwhethergivencarregistrationnumberisvalidTelanganaState
Registration number or not?

In [69]:

importre
s=input("EnterVehicleRegistrationNumber:"
) m=re.fullmatch("TS[012][0-9][A-Z]{2}\
d{4}",s) if m!=None:
print("ValidVehicleRegistration Number");
else:
print("InvalidVehicleRegistration Number")

EnterVehicleRegistrationNumber:TS07EA9999 Valid
Vehicle Registration Number

In [71]:
importre
s=input("EnterVehicleRegistrationNumber:"
) m=re.fullmatch("TS[012][0-9][A-Z]{2}\
d{4}",s) if m!=None:
print("ValidVehicleRegistration Number");
else:
print("InvalidVehicleRegistration Number")

EnterVehicleRegistrationNumber:AP07EA9999
Invalid Vehicle Registration Number

In [72]:

importre
s=input("EnterVehicleRegistrationNumber:"
) m=re.fullmatch("TS[012][0-9][A-Z]{2}\
d{4}",s) if m!=None:
print("ValidVehicleRegistration Number");
else:
print("InvalidVehicleRegistration Number")

EnterVehicleRegistrationNumber:TS123ek5678
Invalid Vehicle Registration Number

Good Luck

localhost:8891/nbconvert/html/Desktop/PythonLab Manual - RGMCET/Lab Manual - Final/Python Programming Lab Manual -


RGMCET(Auton…23/20
RAJEEVGANDHIMEMORIALCOLLEGEOFENGINEERING&TE
CHNOLOGY
(AUTONOMOUS)
DEPARTMENTOFCOMPUTERSCIENCE&ENGINEERING

EvaluationProcedureforInternalLaboratoryExaminations:

1. Of the 25 marks for internal, 10 marks will be awarded for day-to-day work and 10 marksto
be awarded for the Record work and 5 marks to be awarded by conducting an internal
laboratory test.
2. ConcernedTeachers haveto donecessarycorrectionswith explanations.
3. ConcernedLabteachersshouldentermarksinindexpage.
4. Internalexamwillbeconducted bytwoStaff members.

Dr.K.SubbaReddy
Professor&Head Dept.ofCSE.
RAJEEVGANDHIMEMORIALCOLLEGEOFENGINEERING&TE
CHNOLOGY
(AUTONOMOUS)
DEPARTMENTOFCOMPUTERSCIENCE&ENGINEERING

EvaluationProcedureforExternalLaboratoryExaminations:

1. For Practical subjects there is a continuous evaluation during the semester for 25 Sessional
marks and 50 end examination marks.
2. The end examination shall be conducted by the teacher concerned (Internal Examiner) and
another External Examiner, recommended by Head of the Department with the approval of
principal.

Evaluationprocedurefor externallabexamination:
1. Procedurefortheprogram 20M
2. Executionofthe program 15M
3. Vivavoce 15M

Total 50M

Dr.K.SubbaReddy
Professor &HeadDept.ofCSE.

You might also like