0% found this document useful (0 votes)
3 views173 pages

Core Python Material

The document provides an overview of Python, a high-level programming language created by Guido Van Rossum in 1989 and released to the public in 1991. It discusses Python's features, applications, data types, and identifiers, emphasizing its simplicity, readability, and versatility for various programming tasks. Additionally, it outlines the limitations of Python and the different flavors and versions available.

Uploaded by

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

Core Python Material

The document provides an overview of Python, a high-level programming language created by Guido Van Rossum in 1989 and released to the public in 1991. It discusses Python's features, applications, data types, and identifiers, emphasizing its simplicity, readability, and versatility for various programming tasks. Additionally, it outlines the limitations of Python and the different flavors and versions available.

Uploaded by

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

AVERIIK TECHNOLOGY

LANGUAGE
FUNDAMENTALS

AVERIIK TECHNOLOGY
1
AVERIIK TECHNOLOGY

Introduction
 Python is a general purpose high level programming language.

 Python was developed by Guido Van Rossamin 1989 while working at National
Research Institute at Netherlands.

 But officially Python was made available to public in [Link] official Date of Birth for
Python is : Feb 20th 1991.

 Python is recommended as first programming language for beginners.

Eg1:To print Hello world

Java:

1)public class HelloWorld


2){
3) ps vmain(String[]args)
4){
5) SOP("Helloworld");
6)}
7)}

C:

1)#include<stdio.h>
2)voidmain()
3){
4)print("Helloworld");
5)}

Python:
print("HelloWorld")

Eg2:To print the sum of 2 numbers

Java:

1)public class Add


2){
3) public static void main(String[]args)
4){
5) inta,b;

AVERIIK TECHNOLOGY
2
AVERIIK TECHNOLOGY

6) a=10;
7) b=20;
8) [Link]("TheSum:"+(a+b));
9) }
10)}

C:

1)#include <stdio.h>
2)
3)voidmain()
4){
5)inta,b;
6)a=10;
7)b=20;
9)}
8)printf("TheSum:%d",(a+b));

Python:

1)a=10
2)b=20
3)print("The Sum:",(a+b))

The name Python was selected from the TV Show


"The Complete Monty Python's Circus",which was broadcasted in BBC from 1969 to 1974.

Guido developed Python language by taking almost all programming features from
different languages

1. Functional Programming Features from C


2. Object Oriented Programming Features from C++
3. Scripting Language Features from PerlandShell Script
4. Modular Programming Features from Modula-3

Most of syntax in Python Derived from C and ABC languages.

Where we can use Python:

1) For developing Desktop Applications


2) For developing web Applications
3) For developing database Applications
4) For Network Programming

AVERIIK TECHNOLOGY
3
AVERIIK TECHNOLOGY

5) For developing games


6) For Data Analysis Applications
7) For Machine Learning
8) For developing ArtificialIntelligence Applications
9) For IoT
...
Note:
 Internally Google and Youtube use Python coding.
 NASA and Nework Stock Exchange Applications developed by Python.
 Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

Features of Python:

1) Simple and easy to learn:


 Python is a simple programming [Link] we read Python program,we can feel
like reading english statements.
 The syntaxes are very simple and only 30+ keryword are available.
 When compared with other languages,we can write programs with very less number
of lines. Hence more readability and simplicity.
 We can reduce development and cost of the project.

2) FreewareandOpenSource:
 WecanusePythonsoftwarewithoutanylicenceanditisfreeware.
 Itssourcecodeisopen,so thatwecanwecancustomizebasedonourrequirement.
 Eg:JythoniscustomizedversionofPythontoworkwithJava Applications.

3) HighLevelProgramminglanguage:
 Pythonishighlevelprogramminglanguageandhenceitisprogrammerfriendly
language.
 Beingaprogrammerwearenotrequiredtoconcentratelowlevelactivitieslike
memory management and security etc.

4) PlatformIndependent:
 OncewewriteaPythonprogram,itcanrunonanyplatformwithoutrewritingonce again.
 InternallyPVMisresponsibletoconvertintomachineunderstandableform.

5) Portability:
Python programs are portable. ie we can migrate from one platform to another
platformveryeasily. Pythonprogramswillprovidesameresultsonanypaltform.

AVERIIK TECHNOLOGY
4
AVERIIK TECHNOLOGY

6) DynamicallyTyped:
 In Python we are not required to declare type for variables. Whenever we are
assigningthevalue,basedonvalue,[Link] Python is
considered as dynamically typed language.
 ButJava,CetcareStaticallyTypedLanguagesb'zwehavetoprovidetypeatthe
beginning only.
 Thisdynamictypingnaturewillprovidemoreflexibilitytotheprogrammer.

7) BothProcedureOrientedandObjectOriented:
Python language supports both Procedure oriented (like C, pascal etc) and object
oriented(likeC++,Java)[Link]
reusability etc

8) Interpreted:
 [Link]
interpreter will take care that compilation.
 [Link] PVM
(Python Virtual Machine) is responsible to execute.

9) Extensible:
 WecanuseotherlanguageprogramsinPython.
 Themainadvantagesofthisapproachare:
 Wecan usealreadyexistinglegacynon-Pythoncode
 Wecanimproveperformanceoftheapplication

10) Embedded:
WecanusePythonprogramsinanyotherlanguageprograms.
[Link].

11) ExtensiveLibrary:
 Python hasarichinbuilt library.
 Beingaprogrammerwecanusethislibrarydirectlyandwearenotresponsibleto
implement the functionality. Etc.

LimitationsofPython:
1) Performancewisenotuptothemarkbecauseitisinterpretedlanguage.
2) NotusingformobileApplications.

AVERIIK TECHNOLOGY
5
AVERIIK TECHNOLOGY

FlavorsofPython:

1) CPython:
Itisthestandardflavor [Link] toworkwith ClanugageApplications.

2) JythonORJPython:
[Link]

3) IronPython:
Itisfor C#.Netplatform

4) PyPy:
ThemainadvantageofPyPyisperformancewillbeimprovedbecauseJITcompileris available
inside PVM.

5) RubyPython
ForRubyPlatforms

6) AnacondaPython
Itisspeciallydesignedforhandlinglargevolumeofdataprocessing.

PythonVersions:
 Python1.0VintroducedinJan1994
 Python2.0VintroducedinOctober2000
 Python3.0VintroducedinDecember2008

Note:Python3won'tprovidebackwardcompatibilityto [Link] guarantee that


Python2 programs will run in Python3.

Currentversions
Python 3.6.1 Python2.7.13

AVERIIK TECHNOLOGY
6
AVERIIK TECHNOLOGY

IDENTIFIERS
 ANamein Python Programiscalled Identifier.
 ItcanbeClassNameORFunctionNameORModuleNameORVariableName.

 a=10

RulestodefineIdentifiersinPython:
1. TheonlyallowedcharactersinPythonare

 alphabetsymbols(eitherlowercaseoruppercase)
 digits(0to9)
 underscoresymbol(_)

Bymistakeifweareusinganyothersymbollike$thenwewillget syntaxerror.

 cash=10√
 ca$h =20

2. Identifiershouldnotstartswithdigit

 123total 
 total123√

3. Identifiersarecasesensitive. OfcoursePythonlanguageiscasesensitivelanguage.

 total=10
 TOTAL=999
 print(total)#10
 print(TOTAL)#999

AVERIIK TECHNOLOGY
7
AVERIIK TECHNOLOGY

Identifier:
1) AlphabetSymbols(EitherUppercaseORLowercase)

2) IfIdentifierisstartwithUnderscore(_)thenitindicatesitisprivate.

3) IdentifiershouldnotstartwithDigits.

4) Identifiersarecase sensitive.

5) Wecannotusereservedwordsasidentifiers
Eg: def = 10 

6) Thereisnolengthlimitfor [Link]
lengthy identifiers.

7) Dollor($)SymbolisnotallowedinPython.

Q) WhichofthefollowingarevalidPython identifiers?
1) 123total 
2) total123√
3) java2share√
4) ca$h
5) _abc_abc_√
6) def
7) if

Note:

1) Ifidentifier startswith_symbolthenitindicatesthat itisprivate


2) Ifidentifierstartswith(TwoUnderScoreSymbols)indicatingthatstronglyprivate
identifier.
3) Iftheidentifierstartsandendswithtwounderscoresymbolsthentheidentifieris
language defined special name, which is also known as magic methods.

4) Eg: add

AVERIIK TECHNOLOGY
8
AVERIIK TECHNOLOGY

RESERVEDWORDS
InPythonsomewordsarereservedtorepresentsomemeaningorfunctionality. Such
types of words are called reserved words.

Thereare33reservedwordsavailablein Python.

 True,False,None
 and,or ,not,is
 if,elif, else
 while,for,break,continue,return,in,yield
 try,except,finally,raise,assert
 import,from,as,class,def, pass, global,nonlocal,lambda,del,with

Note:

1. AllReservedwordsinPythoncontainonlyalphabetsymbols.

2. Exceptthefollowing3reservedwords,allcontainonlylowercasealphabet symbols.

 True
 False
 None

Eg:a=true
a=True√

>>>import keyword
>>>[Link]
['False','None','True','and','as','assert','break','class','continue','def','del','elif','else',
'except','finally','for','from','global','if','import','in','is','lambda','nonlocal','not','or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']

AVERIIK TECHNOLOGY
9
AVERIIK TECHNOLOGY

DATATYPES
 DataTyperepresents thetypeofdatapresentinsidea variable.
 In Pythonwearenot required [Link] onvalueprovided,
[Link] PythonisdynamicallyTypedLanguage.

Pythoncontainsthefollowinginbuiltdata types

1) Int
2) Float
3) Complex
4) Bool
5) Str
6) Bytes
7) Bytearray
8) Range
9) List
10) Tuple
11) Set
12) Frozenset
13) Dict
14) None

10
a
a= 10
a= 20
ab 20

a= 10
b= 10 10

Note:Pythoncontainsseveralinbuilt functions

1) type()
to checkthetypeofvariable

2) id()
togetaddressofobject

AVERIIK TECHNOLOGY
10
AVERIIK TECHNOLOGY

3) print()
toprintthevalue

InPythoneverythingisanObject.

1) intData Type:
Wecanuseintdatatypetorepresentwholenumbers(integralvalues)
Eg:a= 10
type(a)#int

Note:
 InPython2wehavelongdatatypetorepresentverylargeintegralvalues.
 Butin Python3thereisnolongtypeexplicitlyandwecanrepresentlongvaluesalsoby using
int type only.

2) FloatDataType:
 Wecanusefloatdatatypetorepresentfloatingpointvalues(decimalvalues)
Eg:f= 1.234
type(f)float

 Wecanalsorepresentfloatingpointvaluesbyusingexponentialform
(Scientific Notation)
Eg:f=1.2e3insteadof'e'wecanuse'E'
print(f)1200.0

 Themainadvantageofexponentialformiswecanrepresentbigvaluesinless
memory.

***Note:
Wecanrepresentintvaluesindecimal, binary,[Link] can
represent float values only by using decimal form.

AVERIIK TECHNOLOGY
11
AVERIIK TECHNOLOGY

3) ComplexDataType:
 Acomplexnumberisoftheform

j2=-1
a+bj j=√−1
RealPartImaginaryPart

 ‘a’and‘b’containIntergers ORFloatingPointValues.

Eg:3 +5j
10+5.5j
0.5+0.1j

 Intherealpartifweuseintvalue thenwecanspecifythateitherbydecimal, octal, binary


or hexa decimal form.
 Butimaginarypartshouldbespecifiedonlybyusingdecimal form.

1)>>>a=0B11+5j
2)>>>a
3)(3+5j)
4)>>>a=3+0B11j
5) SyntaxError:invalidsyntax

 Evenwecanperform operationsoncomplextype values.

1)>>>a=10+1.5j
2)>>>b=20+2.5j
3)>>>c=a+b
4)>>>print(c)
5)(30+4j)

AVERIIK TECHNOLOGY
12
AVERIIK TECHNOLOGY

6)>>>type(c)
7)<class'complex'>

Note:Complexdatatypehassomeinbuiltattributestoretrievetherealpartand imaginary part

c=10.5+3.6j

[Link]10.5
[Link]3.6

WecanusecomplextypegenerallyinscientificApplicationsandelectricalengineering
Applications.

4) bool Data Type:


 Wecan usethisdatatypetorepresentboolean values.
 Theonlyallowedvaluesforthisdatatypeare:
 Trueand False

 InternallyPythonrepresentsTrueas1andFalseas0 b =

True
type(b)bool

Eg:
a =10
b=20
c=a<b
print(c)True

True+True2
True-False1

5) strDataType:
 strrepresentsStringdatatype.
 AStringisasequenceofcharactersenclosedwithinsinglequotesordouble
quotes.

 s1='durga'
 s1="durga"

AVERIIK TECHNOLOGY
13
AVERIIK TECHNOLOGY

 Byusingsinglequotesordoublequoteswecannotrepresentmultilinestring
literals.

 s1="durga
soft"

 Forthisrequirementweshouldgofortriplesinglequotes(''')ortripledouble
quotes(""")

 s1='''durga
soft'''

 s1="""durga
soft"""

 Wecan alsousetriplequotesto usesinglequoteordoublequoteinour String.


 '''Thisis"character''''
This i " Character '

 Wecanembedonestringinanother string
 '''This"Python classveryhelpful"forjava students'''

SlicingofStrings:
1) slicemeansapiece
2) []operatoriscalledsliceoperator,which canbeused toretrievepartsof String.
3) InPythonStringsfollowszerobasedindex.
4) Theindexcanbeeither+veor-ve.
5)+veindexmeansforwarddirectionfromLefttoRight
6) -veindexmeansbackwarddirectionfromRighttoLeft
-5 -4 -3 -2 -1
d u r g a
0 1 2 3 4
1)>>>s="durga"
2)>>>s[0]
3)'d'
4)>>>s[1]
5)'u'
6)>>>s[-1]
7)'a'
8)>>>s[40]

IndexError:stringindexoutofrange

AVERIIK TECHNOLOGY
14
AVERIIK TECHNOLOGY

1) >>>s[1:40]
2)'urga'
3)>>>s[1:]
4)'urga'
5)>>>s[:4]
6)'durg'
7)>>>s[:]
8) 'durga'
9) >>>
10)
11)>>>s*3
12)'durgadurgadurga'
13)
14)>>>len(s)
15)5

Note:

1) InPythonthefollowingdatatypesareconsideredasFundamentalData types

 int
 float
 complex
 bool
 str

2) InPython,wecanrepresentcharvaluesalsobyusingstrtypeand explicitlychartype is not


available.

1)>>>c='a'
2)>>>type(c)
3)<class'str'>

3) longDataTypeisavailablein Python2butnotinPython3.InPython3longvaluesalso we can


represent by using int type only.

4) InPythonwecanpresentcharValuealsobyusingstrTypeandexplicitlycharTypeis not
available.

AVERIIK TECHNOLOGY
15
AVERIIK TECHNOLOGY

TYPECASTING
֍[Link] or Type
coersion.
֍Thefollowingarevariousinbuilt functionsfortypecasting.

1) int()
2) float()
3) complex()
4) bool()
5) str()

֍ int():
Wecan usethisfunctiontoconvertvaluesfromothertypestoint

1) >>>int(123.987)
2)123
3)>>>int(10+5j)
4)TypeError:can'tconvertcomplextoint
5)>>>int(True)
6)1
7)>>>int(False)
8)0
9)>>>int("10")
10)10
11)>>>int("10.5")
12)ValueError:invalidliteralforint()withbase10:'10.5'
13)>>>int("ten")
14)ValueError:invalidliteralforint()withbase10:'ten'
15)>>>int("0B1111")
16)ValueError:invalidliteralforint()withbase10:'0B1111'

Note:

1) Wecanconvertfromanytypetointexceptcomplextype.
2) Ifwewanttoconvertstrtypetointtype,compulsarystrshouldcontainonlyintegral value
and should be specified in base-10.

AVERIIK TECHNOLOGY
16
AVERIIK TECHNOLOGY

֍ float():
Wecanusefloat()functiontoconvertothertypevaluestofloattype.

1) >>>float(10)
2)10.0
3)>>>float(10+5j)
4)TypeError:can'tconvertcomplexto float
5)>>>float(True)
6)1.0
7)>>>float(False)
8)0.0
9)>>>float("10")
10)10.0
11)>>>float("10.5")
12)10.5
13)>>>float("ten")
14)ValueError:couldnotconvert stringtofloat: 'ten'
15)>>>float("0B1111")
16)ValueError:couldnotconvert stringtofloat: '0B1111'

Note:
1) Wecanconvertanytypevaluetofloattypeexceptcomplex type.
2) Wheneverwearetryingtoconvertstrtypetofloattypecompulsarystrshouldbe either
integral or floating point literal and should be specified only in base-10.

֍ complex():
Wecanusecomplex()functiontoconvertothertypestocomplextype.

Form-1:complex(x)
Wecanusethisfunctiontoconvertxintocomplexnumberwithrealpartxandimaginary part 0.

Eg:

1) complex(10)==>10+0j
2) complex(10.5)===>10.5+0j
3) complex(True)==>1+0j
4) complex(False)==>0j
5) complex("10")==>10+0j
6) complex("10.5")==>10.5+0j
7)complex("ten")
8) ValueError:complex()argisamalformed string

AVERIIK TECHNOLOGY
17
AVERIIK TECHNOLOGY

Form-2:complex(x,y)

Wecanusethismethodtoconvertxandyintocomplexnumbersuchthatxwillbereal part and y


will be imaginary part.

Eg: complex(10, -2) 10-2j


complex(True,False)1+0j

֍ bool():
Wecanusethisfunctiontoconvertothertypevaluestobool type.

1) bool(0)False
2)bool(1) True
3) bool(10)True
4) bool(10.5)True
5) bool(0.178)True
6) bool(0.0)False
7) bool(10-2j)True
8) bool(0+1.5j)True
9) bool(0+0j)False
10) bool("True")True
11) bool("False")True
12) bool("")False

AVERIIK TECHNOLOGY
18
AVERIIK TECHNOLOGY

֍ str():
Wecanusethismethodtoconvertothertypevaluestostr type.

1)>>>str(10)
2) '10'
3) >>>str(10.5)
4) '10.5'
5) >>>str(10+5j)
6) '(10+5j)'
7)>>>str(True)
8)'True'

FundamentalDataTypesvsImmutability:
֍All Fundamental Data types are immutable. i.e once we creates an object,we cannot
[Link] thenwiththosechanges a new
object will be created. This non-chageable behaviour is called immutability.

֍In Python if a new object is required, then PVM won’t create object immediately. First it
will check is any object available with the required content or not. If available then
existing object will be reused. If it is not available then only a new object will be
[Link]
improved.

֍But theprobleminthisapproachis, several referencespointingto thesameobject, by


usingonereferenceifweareallowedtochangethecontentintheexistingobjectthen the
remaining references will be effected. To prevent this immutability concept is
required. According to this once creates an object we are not allowed to change
content. If we are trying to change with those changes a new object will be created.

1)>>>a=10
2)>>>b=10
3)>>>a is b
4)True
5)>>>id(a)
6)1572353952
7)>>>id(b)
8)1572353952
9)>>>

AVERIIK TECHNOLOGY
19
AVERIIK TECHNOLOGY

>>>a=10 >>> a=10+5j >>>a=True >>>a='durga'

6)>>>b=10
bytesDataType:
>>>b=10+5j >>> b=True >>>b='durga'
bytesdatatyperepresensagroupofbytenumbersjustlikeanarray.
>>> id(a) >>>aisb >>>aisb >>>aisb
1)x =[10,20,30,40]
3)type(b)
1572353952
2) bytes
b=bytes(x) False True True
10
>>> print(b[-1])
4)
id(b) 40
print(b[0]) >>> id(a) >>> id(a) >>> id(a)
>>>for i in b : print(i)7)
8)10
1572353952 15980256 1572172624 16378848
9)20
10)30
>>>aisb >>>id(b) >>>id(b) >>>id(b)
11)40

True 15979944 1572172624 16378848

Conclusion1:
Theonlyallowedvaluesforbytedatatypeare0to256. Bymistakeifwearetryingto provide any
other values then we will get value error.

Conclusion 2:
Oncewecreatesbytesdatatypevalue, wecannotchangeitsvalues,otherwisewewillget
TypeError.

AVERIIK TECHNOLOGY
20
AVERIIK TECHNOLOGY

Eg:

1)>>>x=[10,20,30,40]
2)>>>b=bytes(x)
3)>>>b[0]=100
4)TypeError:'bytes'objectdoesnotsupportitemassignment

7) bytearrayDataType:
bytearrayisexactlysameasbytesdatatypeexceptthatitselementscanbe modified.

Eg1:

1)x=[10,20,30,40]
2)b=bytearray(x)
3)for iinb:print(i)
4)10
5)20
6)30
7)40
8)b[0]=100
9) foriinb:print(i)
10)100
11)20
12)30
13)40

Eg 2:

1)>>>x =[10,256]
2)>>>b=bytearray(x)
3)ValueError: byte mustbeinrange(0,256)

8) ListDataType:
Ifwewanttorepresentagroupofvaluesasasingleentitywhereinsertionorder required
to preserve and duplicates are allowed then we should go for list data type.

1) InsertionOrderispreserved
2) HeterogeneousObjectsareallowed
3) Duplicatesare allowed
4) Growableinnature
5) Valuesshouldbeenclosedwithinsquarebrackets.

AVERIIK TECHNOLOGY
21
AVERIIK TECHNOLOGY

Eg:

1)list=[10,10.5,'durga',True,10]
2)print(list)#[10,10.5,'durga',True,10]

Eg:

1)list=[10,20,30,40]
2)>>>list[0]
3)10
4)>>> list[-1]
5)40
6)>>>list[1:3]
7)[20, 30]
8)>>>list[0]=100
9)>>>for iinlist:print(i)
10)...
11)100
12)20
13)30
14)40

[Link] size.

1)>>>list=[10,20,30]
2)>>>[Link]("durga")
3)>>>list
4)[10, 20, 30, 'durga']
5)>>>[Link](20)
6)>>>list
7)[10, 30, 'durga']
8)>>>list2=list*2
9)>>>list2
10)[10,30,'durga', 10,30,'durga']

Note:Anordered,mutable,heterogenouscollectionofeleemntsisnothingbutlist, where
duplicates also allowed.

AVERIIK TECHNOLOGY
22
AVERIIK TECHNOLOGY

9) TupleDataType:
 [Link] cannot
chage values.
 Tupleelementscanberepresentedwithinparenthesis.

Eg:

1) t=(10,20,30,40)
2)type(t)
3)<class'tuple'>
4)t[0]=100
5)TypeError:'tuple'objectdoesnotsupport item assignment
6)>>>[Link]("durga")
7)AttributeError:'tuple'objecthasnoattribute'append'
8)>>>[Link](10)
9)AttributeError:'tuple'objecthasnoattribute'remove'

Note:tupleisthereadonlyversionoflist

10) RangeDataType:
 rangeDataTyperepresentsasequenceof numbers.
 [Link]
immutable.

Form-1:range(10)
generatenumbersfrom0to9

Eg:
r=range(10)
foriinr: print(i) 0to9

Form-2:range(10,20)
generatenumbersfrom10to19

Eg:
r=range(10,20)
foriinr: print(i) 10to19

AVERIIK TECHNOLOGY
23
AVERIIK TECHNOLOGY

Form-3:range(10,20,2) 2
means increment value

Eg:
r=range(10,20,2)
foriinr:print(i)10,12,14,16,18

Wecan access elementspresentintherangeDataTypebyusingindex.

Eg:
r=range(10,20)
r[0] 10
r[15]IndexError:rangeobjectindexoutofrange We

cannot modify the values of range data type

Eg:
r[0]= 100
TypeError:'range'objectdoesnotsupportitemassignment We

can create a list of values with range data type

Eg:

1)>>>l=list(range(10))
2)>>>l
3)[0, 1,2,3,4,5,6, 7,8,9]

11) setDataType:
֍Ifwewanttorepresentagroupofvalueswithoutduplicateswhereorderisnot important then
we should go for set Data Type.

1) Insertionorderisnotpreserved
2) Duplicatesarenotallowed
3) Heterogeneousobjectsareallowed
4) Indexconceptisnot applicable
5) Itismutable collection
6) Growableinnature

AVERIIK TECHNOLOGY
24
AVERIIK TECHNOLOGY

Eg:

1) s={100,0,10,200,10,'durga'}
2)s# {0, 100,'durga', 200,10}
3)s[0]TypeError:'set'objectdoesnotsupport indexing

֍setisgrowableinnature,basedonourrequirementwecanincreaseordecreasethe size.

1)>>>[Link](60)
2)>>>s
3){0,100, 'durga', 200,10,60}
4)>>>[Link](100)
5)>>>s
6){0, 'durga',200,10,60}

12) frozensetDataType:
֍It is exactlysameas setexcept thatitis immutable.
֍Hencewecannotuseaddorremove functions.

1)>>>s={10,20,30,40}
2)>>>fs=frozenset(s)
3)>>>type(fs)
4)<class'frozenset'>
5)>>>fs
6)frozenset({40, 10,20,30})
7)>>>for iinfs:print(i)
8)...
9)40
10)10
11)20
12)30
13)
14)>>>[Link](70)
15)AttributeError:'frozenset'objecthasnoattribute'add'
16)>>>[Link](10)
17)AttributeError:'frozenset'objecthasnoattribute'remove'

AVERIIK TECHNOLOGY
25
AVERIIK TECHNOLOGY

13) dictDataType:
֍ Ifwewanttorepresentagroupof valuesaskey-valuepairsthenweshould gofor
dictdata type.

֍ Eg:d = {101:'durga',102:'ravi',103:'shiva'}

֍ Duplicate keys are not allowed but values can be duplicated. If we are trying to
insertanentrywithduplicatekeythenoldvaluewillbe replacedwithnewvalue.

Eg:

1) >>>d={101:'durga',102:'ravi',103:'shiva'}
2) >>>d[101]='sunny'
3) >>>d
4) {101:'sunny',102:'ravi',103:'shiva'}
5)
6) Wecancreateemptydictionaryasfollows
7) d={ }
8) Wecanaddkey-valuepairsas follows
9) d['a']='apple'
10) d['b']='banana'
11) print(d)

Note:dictismutableandtheorderwon’tbe preserved.

Note:

1) Ingeneralwecanusebytesandbytearraydatatypestorepresentbinaryinformation like
images, video files etc
2) [Link] Python3itisnotavailableandwecan
represent long values also by using int type only.
3) [Link] str
type.

AVERIIK TECHNOLOGY
26
AVERIIK TECHNOLOGY

SummaryofDatatypesinPython3
Datatype Description IsImmutable? Example
Int We can use to representImmutable >>>a=10
the whole/integral >>>type(a)
numbers <class'int'>

Float We can use to representImmutable >>> b=10.5


the decimal/floating >>>type(b)
point numbers <class'float'>

Complex We can use to Immutable >>> c=10+5j


represent the >>>type(c)
complexnumbers <class'complex'>
>>>[Link]
10.0
>>>[Link] 5.0

Bool We can use to Immutable >>>flag=True


representthelogical >>>flag=False
values(Onlyallowed >>>type(flag)
values are True and <class'bool'>
False)
Str Torepresent Immutable >>>s='durga'
sequence of >>>type(s)
Characters <class'str'>
>>>s="durga"
>>> s='''Durga Software
Solutions...Ameerpet'''
>>>type(s)
<class'str'>
bytes To represent a sequenceImmutable >>>list=[1,2,3,4]
of byte valuesfrom0- >>>b=bytes(list)
255 >>>type(b)
<class'bytes'>
bytearray To represent a sequenceMutable >>>list=[10,20,30]
of byte valuesfrom0- >>>ba=bytearray(list)
255 >>>type(ba)
<class'bytearray'>
range Torepresentarange of Immutable >>>r=range(10)
values >>> r1=range(0,10)
>>>r2=range(0,10,2)

AVERIIK TECHNOLOGY
27
AVERIIK TECHNOLOGY

list To represent an Mutable >>>l=[10,11,12,13,14,15]


orderedcollectionof >>>type(l)
objects <class'list'>
tuple To represent an Immutable >>>t=(1,2,3,4,5)
orderedcollectionsof >>>type(t)
objects <class'tuple'>
set To represent an Mutable >>>s={1,2,3,4,5,6}
unorderedcollection >>>type(s)
of unique objects <class'set'>
frozenset To represent an Immutable >>>s={11,2,3,'Durga',100,'Ramu'}
unorderedcollection >>> fs=frozenset(s)
of unique objects >>>type(fs)
<class'frozenset'>
dict Torepresentagroup of Mutable >>>
key value pairs d={101:'durga',102:'ramu',
103:'hari'}
>>>type(d)
<class'dict'>

14) NoneDataType:
 NonemeansnothingorNo value associated.
 Ifthevalueisnotavailable,thentohandlesuchtypeofcasesNoneintroduced.
 ItissomethinglikenullvalueinJava.

Eg:
defm1():
a=10

print(m1())
None

AVERIIK TECHNOLOGY
28
AVERIIK TECHNOLOGY

EscapeCharacters:
InStringliteralswecanuseesacpecharacterstoassociateaspecial meaning.

1)>>>s="durga\nsoftware"
2)>>>print(s)
3)durga
4)software
5)>>>s="durga\tsoftware"
6)>>>print(s)
7)durgasoftware
8)>>>s="Thisis "symbol"
9) File"<stdin>",line1
10)s="Thisis"symbol"
11) ^
12)SyntaxError:invalid syntax
13)>>>s="Thisis \"symbol"
14)>>>print(s)
15)Thisis"symbol

ThefollowingarevariousimportantescapecharactersinPython

1) \n NewLine
2) \t HorizontalTab
3) \r Carriage Return
4) \b BackSpace
5) \f FormFeed
6) \v VerticalTab
7) \' SingleQuote
8) \" DoubleQuote
9) \\ BackSlash Symbol
....

Constants:
 ConstantsconceptisnotapplicableinPython.
 Butitisconventionto useonlyuppercasecharactersifwedon’twanttochange value.

 MAX_VALUE = 10

 Itisjustconventionbutwecanchangethe value.

AVERIIK TECHNOLOGY
29
AVERIIK TECHNOLOGY

OPERATORS

AVERIIK TECHNOLOGY
30
AVERIIK TECHNOLOGY

 Operatorisasymbolthatperformscertain operations.
 Python providesthefollowingsetof operators

1) ArithmeticOperators
2) RelationalOperatorsORComparisonOperators
3) Logicaloperators
4) Bitwiseoeprators
5) Assignmentoperators
6) Specialoperators

1) ArithmeticOperators:
1)+  Addition

2)–  Subtraction

3)*  Multiplication

4)/  DivisionOperator

5)%  ModuloOperator

6)//  FloorDivisionOperator

7)**  ExponentOperatorORPowerOperator

Eg:[Link]

1) a=10
2)b=2
3)print('a+b=',a+b)
4)print('a-b=',a-b)
5)print('a*b=',a*b)
6)print('a/b=',a/b)
7)print('a//b=',a//b)
8)print('a%b=',a%b)
9)print('a**b=',a**b)

Output:
[Link] a+b
= 12
a-b= 8
a*b=20
a/b=5.0

AVERIIK TECHNOLOGY
31
AVERIIK TECHNOLOGY

a//b=5
a%b= 0
a**b=100

Eg:

1)a =10.5
2) b=2
3)
4) a+b=12.5
5) a-b= 8.5
6) a*b=21.0
7) a/b=5.25
8) a//b=5.0
9) a%b= 0.5
10)a**b=110.25

Eg:
10/25.0
10//25
10.0/25.0
10.0//25.0

Note:
֍/[Link] value.

֍But Floor division (//) can perform both floating point and integral arithmetic. If
[Link] result is
float type.

Note:
֍Wecan use+,*operatorsfor strtype also.
֍Ifwewanttouse+operatorforstrtypethencompulsorybothargumentsshouldbe str type
only otherwise we will get error.

1)>>>"durga"+10
2)TypeError:mustbestr,notint
3)>>>"durga"+"10"
4)'durga10'

֍Ifweuse*operatorforstrtypethencompulsoryoneargument shouldbeintand other


argument should be str type.

AVERIIK TECHNOLOGY
32
AVERIIK TECHNOLOGY

֍2*"durga""durg
a"*2
2.5*"durga"TypeError: can't multiply sequence by non-int of type
'float'"durga"*"durga"TypeError:can'tmultiplysequencebynon-intoftype'str'

֍+StringConcatenation Operator
֍*StringMultiplication Operator

Note:Foranynumberx,
x/0andx%0alwaysraises"ZeroDivisionError"

10/0
10.0/0
.....

2) RelationalOperators:>,>=,<,<=
1) a=10
2)b=20
3)print("a>bis",a>b)
4)print("a>=bis",a>=b)
5)print("a<bis",a<b)
6)print("a<=bis",a<=b)
7)
8)a >bisFalse
9)a >=bisFalse
10)a <bisTrue
11)a<=bisTrue

Wecanapplyrelationaloperatorsforstrtypesalso.

Eg2:

1)a="durga"
2)b="durga"
3)print("a>bis ",a>b)
4)print("a>=bis ",a>=b)
5)print("a<bis ",a<b)
6)print("a<=bis ",a<=b)
7)
8)a >bisFalse
9)a >=bisTrue
10)a <bisFalse
11)a <=bisTrue

AVERIIK TECHNOLOGY
33
AVERIIK TECHNOLOGY

Eg:

1)print(True>True)False
2)print(True>=True)True
3)print(10>True)True
4)print(False>True)False
5)
6)print(10>'durga')
7) TypeError:'>'notsupportedbetweeninstancesof'int'and'str'

Eg:

1)a=10
2)b=20
3)if(a>b):
4) print("aisgreaterthanb")
5)else:
6) print("aisnotgreaterthan b")

Output:aisnotgreaterthan b

Note:Chaining of relational operators is possible. In the chaining, if all comparisons


returnsTruethenonlyresultis [Link] result is
False

1)10<20True
2)10<20<30True
3)10<20<30<40True
4)10<20<30<40>50False

3) EqualityOperators:==,!=
Wecanapplytheseoperatorsfor anytypeevenforincompatibletypes also.

1)>>>10==20
2)False
3)>>>10!=20
4)True
5)>>>10==True
6)False
7)>>>False==False
8)True
9)>>>"durga"=="durga"
10)True
11)>>>10=="durga"

AVERIIK TECHNOLOGY
34
AVERIIK TECHNOLOGY

12)False

Note:[Link] returns
False then the result is False. Otherwise the result is True.

1)>>>10==20==30==40
2)False
3)>>>10==10==10==10
4)True

4) LogicalOperators:and,or,not
Wecan applyforall types.

ForbooleanTypes Behaviour:
andIfbothargumentsareTruethenonlyresultisTrue orIf
atleast one arugemnt is True then result is True not
Complement

TrueandFalseFalse
True or False True not
False True

Fornon-booleanTypes Behaviour:
0meansFalse
non-zeromeans True
emptystringisalwaystreatedas False

xandy:
Ifxisevaluatestofalsereturnxotherwisereturny Eg:
10 and20
0 and20

Iffirstargumentiszero thenresultiszerootherwiseresultisy

xor y:
IfxevaluatestoTruethen resultisxotherwiseresultisy

10 or20 10
0 or2020

AVERIIK TECHNOLOGY
35
AVERIIK TECHNOLOGY

not x:
IfxisevalutatestoFalsethenresultisTrueotherwiseFalse

not10False not
0 True

Eg:

1)"durga"and"durgasoft"==>durgasoft
2)""and"durga"==>""
3)"durga"and ""==>""
4)"" or"durga"==>"durga"
5)"durga"or""==>"durga"
6)not""==>True
7)not"durga"==>False

5) BitwiseOperators:
֍Wecan applytheseoperators bitwise.
֍Theseoperatorsare applicableonlyforintandbooleantypes.
֍Bymistakeifwearetryingtoapplyfor anyothertypethenwewillget Error.

֍&, |,^, ~,<<,>>

֍print(4&5)Valid
֍print(10.5 &5.6)
TypeError:unsupportedoperandtype(s)for&:'float'and'float'

֍print(True&True) Valid

֍&Ifboth bitsare1then onlyresultis1otherwiseresultis0


֍|If atleastonebitis1thenresultis1otherwiseresultis0
֍^Ifbits aredifferentthen onlyresultis1otherwiseresultis0
֍~bitwisecomplement operator
֍10&01
֍<<BitwiseLeftShift
֍>>BitwiseRightShift

֍print(4&5)4
֍print(4|5)5
֍print(4^5)1

AVERIIK TECHNOLOGY
36
AVERIIK TECHNOLOGY

Operator Description
& Ifbothbitsare1 thenonlyresultis1 otherwiseresultis0
| Ifatleastonebitis1thenresultis1 otherwiseresultis0
^ Ifbitsaredifferentthenonlyresultis1otherwiseresultis0
~ bitwisecomplementoperatori.e1means0and0means1
>> BitwiseLeftshiftOperator
<< BitwiseRightshift Operator

BitwiseComplementOperator (~):
Wehavetoapplycomplementfortotalbits. Eg:

print(~5)-6

Note:
֍Themostsignificantbitactsassignbit.0valuerepresents +venumberwhereas1 represents -
ve value.
֍Positivenumberswillberepesenteddirectlyinthememorywhereas -venumberswill be
represented indirectly in 2's complement form.

6) ShiftOperators:
<< Left ShiftOperator
Aftershiftingtheemptycellswehavetofillwithzero

print(10<<2)40

0 0 0 0 1 0 1 0

0 0 1 0 1 0 0 0

>>RightShift Operator
Aftershiftingtheemptycellswehavetofillwithsignbit.(0for +veand1for-ve)

print(10>>2)2

0 0 0 0 1 0 1 0

0 0 0 0 0 0 1 0

AVERIIK TECHNOLOGY
37
AVERIIK TECHNOLOGY

Wecanapplybitwiseoperatorsforbooleantypesalso

֍print(True&False)False
֍print(True| False)True
֍print(True^False)True
֍print(~True)-2
֍print(True<<2)4
֍print(True>>2)0

7) AssignmentOperators:
֍Wecan useassignmentoperatortoassignvaluetothevariable.
Eg:x=10

֍Wecancombineasignmentoperatorwithsomeotheroperatortoformcompound
assignment operator.
Eg:x+=10x =x+10

Thefollowingisthelistofallpossiblecompound assignmentoperatorsinPython.

 +=
 -=
 *=
 /=
 %=
 //=
 **=
 &=
 |=
 ^=
 >>=
 <<=

Eg:

1)x=10
2)x+=20
3)print(x)30

Eg:

1)x=10
2)x&=5
3)print(x)0

AVERIIK TECHNOLOGY
38
AVERIIK TECHNOLOGY

8) TernaryOperatorORConditionalOperator
Syntax:x=firstValueifconditionelse secondValue

IfconditionisTruethenfirstValuewillbeconsideredelsesecondValuewillbeconsidered.

Eg1:

1)a,b=10,20
2)x=30ifa<b else40
3)print(x) #30

Eg2:Readtwonumbersfromthekeyboardandprintminimum value

1)a=int(input("Enter FirstNumber:"))
2)b=int(input("EnterSecond Number:"))
3)min=aifa<belseb
4)print("Minimum Value:",min)

Output:
Enter First Number:10
EnterSecondNumber:30
Minimum Value: 10

Note:NestingofTernaryOperatoris Possible.

Q)ProgramforMinimumof3Numbers
1)a=int(input("Enter FirstNumber:"))
2)b=int(input("EnterSecond Number:"))
3)c=int(input("EnterThirdNumber:"))
4)min=aifa<b and a<celsebif b<c elsec
5)print("Minimum Value:",min)

Q)ProgramforMaximumof3Numbers
1)a=int(input("Enter FirstNumber:"))
2)b=int(input("EnterSecond Number:"))
3)c=int(input("EnterThirdNumber:"))
4)max=aif a>banda>celsebifb>celsec
5)print("MaximumValue:",max)

AVERIIK TECHNOLOGY
39
AVERIIK TECHNOLOGY

Eg:

1)a=int(input("Enter FirstNumber:"))
2)b=int(input("EnterSecond Number:"))
3)print("Bothnumbersareequal"ifa==belse"FirstNumberisLessthanSecondNu mber"if
a<b else "First Number Greater than Second Number")

Output:
D:\python_classes>[Link]
Enter First Number:10
EnterSecondNumber:10
Both numbers are equal

D:\python_classes>[Link]
Enter First Number:10
EnterSecondNumber:20
FirstNumberisLessthanSecondNumber

D:\python_classes>[Link]
Enter First Number:20
EnterSecondNumber:10
FirstNumberGreaterthanSecondNumber

9) SpecialOperators:
Python definesthefollowing2special operators
1) Identity Operators
2) Membershipoperators

1)IdentityOperators
 Wecanuseidentityoperatorsfor addresscomparison.
 Thereare2identityoperatorsare available
1) is
2) is not

 r1isr2returnsTrueifbothr1andr2arepointingtothesameobject.
 r1isnotr2returnsTrueifbothr1 andr2arenotpointingtothesameobject.

Eg:

1) a=10
2)b=10
3)print(a isb) True
4)x=True

AVERIIK TECHNOLOGY
40
AVERIIK TECHNOLOGY

5)y=True
6)print( xis y)True

Eg:
1) a="durga"
2) b="durga"
3) print(id(a))
4) print(id(b))
5) print(aisb)

Eg:

1) list1=["one","two","three"]
2) list2=["one","two","three"]
3) print(id(list1))
4) print(id(list2))
5) print(list1islist2)False
6) print(list1isnotlist2)True
7) print(list1== list2) True

Note:Wecanuseisoperatorforaddresscomparisonwhereas==operatorforcontent
comparison.

2)MembershipOperators:
 WecanuseMembershipoperatorstocheckwhetherthegivenobjectpresent inthe given
collection. (It may be String, List, Set, Tuple OR Dict)
 InReturnsTrueifthegivenobjectpresentin thespecified Collection
 notinRetrunsTrueifthegiven objectnotpresentinthespecified Collection

Eg:

1) x="hellolearningPythonisvery easy!!!"
2) print('h'inx) True
3) print('d'inx) False
4) print('d'notinx) True
5) print('Python'in x) True

Eg:

1) list1=["sunny","bunny","chinny","pinny"]
2) print("sunny"inlist1)True
3) print("tunny"inlist1)False
4) print("tunny"notinlist1)True

AVERIIK TECHNOLOGY
41
AVERIIK TECHNOLOGY

OperatorPrecedence:
Ifmultipleoperatorspresentthenwhichoperatorwillbeevaluatedfirstisdecidedby operator
precedence.

Eg:
print(3+10*2)23
print((3+10)*2)26

ThefollowinglistdescribesoperatorprecedenceinPython

1) ()Parenthesis
2) **Exponential Operator
3) ~,-BitwiseComplementOperator,UnaryMinusOperator
4) *,/,%,//Multiplication,Division,Modulo,Floor Division
5)+,-Addition, Subtraction
6) <<, >>Left andRightShift
7) &BitwiseAnd
8) ^BitwiseX-OR
9) |BitwiseOR
10) >,>=,<,<=,==,!=RelationalORComparisonOperators
11)=,+=,-=, *=...Assignment Operators
12) is,isnotIdentity Operators
13) in,not inMembership operators
14) notLogicalnot
15) andLogicaland
16) orLogicalor

1)a=30
2)b=20
3)c=10
4)d=5
5)print((a+b)*c/d)100.0
print((a+b)*(c/d))100.0
print(a+(b*c)/d)70.0
8)
9)3/2*4+3+(10/5)**3-2
10)3/2*4+3+2.0**3-2
11)3/2*4+3+8.0-2
12)1.5*4+3+8.0-2
13)6.0+3+8.0-2
14)15.0

AVERIIK TECHNOLOGY
42
AVERIIK TECHNOLOGY

MathematicalFunctions(mathModule)
֍AModuleiscollectionoffunctions, variablesandclasses etc.
֍math isamodulethatcontainsseveralfunctionstoperformmathematicaloperations.
֍Ifwewanttouseanymodulein Python,firstwehavetoimportthat module. import
math
֍Onceweimport amodulethenwecancallanyfunctionofthatmodule.

1)importmath
2)print([Link](16))
3)print([Link])

Output
4.0
3.141592653589793

֍[Link]
֍Oncewecreatealiasname,byusingthatwecanaccessfunctions andvariablesofthat module.

1)import mathas m
2)print([Link](16))
3)print([Link])

֍Wecanimportaparticularmember ofamoduleexplicitlyasfollows
from math import sqrt
frommathimportsqrt,p
֍Ifweimport amemberexplicitlythenitisnotrequiredtousemodulenamewhile accessing.

1)from mathimportsqrt,pi
2)print(sqrt(16))
3)print(pi)
4)print NameError:name([Link])'math'isnotdefined

AVERIIK TECHNOLOGY
43
AVERIIK TECHNOLOGY

ImportantFunctionsofmathModule:
1) ceil(x)
2) floor(x)
3) pow(x,y)
4) factorial(x)
5) trunc(x)
6) gcd(x,y)
7) sin(x)
8) cos(x)
9) tan(x)
10) ....

ImportantVariablesofmathModule:
pi3.14
e2.71
infinfinity
nannot anumber

Q) WriteaPython ProgramtofindAreaofCircle pi*r**2


1)from mathimportpi
2)r=16
3)print("Areaof Circleis:",pi*r**2)

Output:AreaofCircleis:804.247719318987

AVERIIK TECHNOLOGY
44
AVERIIK TECHNOLOGY

INPUTANDOUTPUTSTATEMENTS

ReadingDynamicInputfromtheKeyboard:
InPython2thefollowing2functionsareavailabletoreaddynamicinputfromthe keyboard.

1) raw_input()
2) input()

1)raw_input():
Thisfunctionalwaysreadsthedatafromthekeyboardintheformof StringFormat.
Wehavetoconvertthatstringtypetoourrequiredtypebyusingthecorresponding type
casting methods.

Eg:x=raw_input("EnterFirstNumber:")
print(type(x))Itwillalwaysprintstrtypeonlyfor anyinputtype

2)input():
input()[Link] required
to perform type casting.

x=input("EnterValue)t
ype(x)

10 int
"durga"str
10.5float
Truebool

***Note:
 Butin Python 3wehaveonlyinput()methodand raw_input()methodisnot available.
 Python3input()functionbehaviourexactlysameasraw_input()methodofPython2.
[Link].
 raw_input()functionof Python 2isrenamedasinput()functioninPython3.

1)>>>type(input("Entervalue:"))
2)Entervalue:10
3)<class'str'>
5)Entervalue:10.5
4)

7)
6)<class'str'>

AVERIIK TECHNOLOGY
45
AVERIIK TECHNOLOGY

8)Entervalue:True
9)<class'str'>

Q)Writeaprogramtoread2numbersfromthekeyboardandprint sum

1)x=input("Enter FirstNumber:")
2)y=input("EnterSecondNumber:")
3)i=int(x)
4)j=int(y)
5)print("The Sum:",i+j)

Enter First Number: 100


EnterSecondNumber:200
The Sum: 300
-----------------------------------------------------

1)x=int(input("EnterFirstNumber:"))
2)y=int(input("Enter Second Number:"))
3)print("The Sum:",x+y)

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

print("TheSum:",int(input("EnterFirstNumber:"))+int(input("EnterSecondNumber:")))

Q)WriteaProgramtoreadEmployeeDatafromtheKeyboardandprint
that Data
1)eno=int(input("EnterEmployee No:"))
2)ename=input("EnterEmployee Name:")
3)esal=float(input("EnterEmployeeSalary:"))
4)eaddr=input("EnterEmployeeAddress:")
5)married=bool(input("EmployeeMarried ?[True|False]:"))
6)print("PleaseConfirmInformation")
7)print("EmployeeNo:",eno)
8)print("EmployeeName:",ename)
9)print("EmployeeSalary :",esal)
10)print("EmployeeAddress :",eaddr)
11)print("EmployeeMarried?:",married)

D:\Python_classes>[Link]
Enter Employee No:100
Enter Employee Name:Sunny
Enter Employee Salary:1000
EnterEmployeeAddress:Mumbai

AVERIIK TECHNOLOGY
46
AVERIIK TECHNOLOGY

EmployeeMarried?[True|False]:True
Please Confirm Information

Employee No : 100
Employee Name : Sunny
Employee Salary : 1000.0
EmployeeAddress:Mumbai
Employee Married ? : True

Howtoreadmultiplevaluesfromthekeyboardinasingle
line:
1)a,b= [int(x)forxininput("Enter2 numbers:").split()]
2)print("Product is:",a*b)

D:\Python_classes>[Link]
Enter 2 numbers :10 20
Product is : 200

Note: split() function can take space as seperator by default .Butwecanpass


anything as seperator.

Q)Writeaprogramtoread3floatnumbersfromthekeyboardwith,
seperator and print their sum
1)a,b,c=[float(x)for xininput("Enter3 floatnumbers:").split(',')]
2)print("TheSum is:",a+b+c)

D:\Python_classes>[Link]
Enter3floatnumbers:10.5,20.6,20.1 The
Sum is : 51.2

eval():
evalFunctiontakeaStringandevaluatethe Result.

Eg:x = eval(“10+20+30”)
print(x)
Output:60

Eg:x=eval(input(“EnterExpression”))
Enter Expression:10+2*3/4
Output:11.5

AVERIIK TECHNOLOGY
47
AVERIIK TECHNOLOGY

eval()canevaluatetheInputtolist,tuple,set,etcbasedtheprovidedInput.

Eg:WriteaProgramtoaccept listfromthekeynboardonthedisplay

1)l=eval(input(“EnterList”))
2)print(type(l))
3)print(l)

COMMAND LINE ARGUMENTS


 [Link].
 TheArgumentwhicharepassingatthetimeofexecutionarecalledCommandLine
Arguments.

Eg:D:\Python_classespytest.py102030

CommandLineArguments

[Link]
present in SYS Module.

[Link] 10 20 30

Note:argv[0][Link] CommandLineArgument. argv[1]


represent First Command Line Argument.

Program:Tochecktypeof argvfromsys

import
argvprint(type(argv))

D:\Python_classes\[Link]

WriteaProgramtodisplayCommandLineArguments
1)from sysimportargv
2)print(“TheNumber ofCommandLineArguments:”,len(argv))
3)print(“TheList ofCommandLineArguments:”,argv)
4)print(“CommandLineArguments onebyone:”)
5)forxin argv:
6) print(x)

AVERIIK TECHNOLOGY
48
AVERIIK TECHNOLOGY

D:\Python_classes>pytest.py102030
TheNumberofCommand LineArguments: 4
TheListofCommandLineArguments:[‘[Link]’,‘10’,’20’,’30’]
Command Line Arguments one by one:
[Link]
10
20
30
---------------------------
1)from sysimportargv
2)sum=0
3)args=argv[1:]
4)forxin args:
5) n=int(x)
6)sum=sum+n
7)print("The Sum:",sum)

D:\Python_classes>pytest.py10203040
The Sum:100

Note 1:Usually space is seperator between command line arguments. If our command
lineargumentitselfcontainsspacethenweshouldenclosewithindoublequotes(butnot single
quotes)

1)from sysimportargv
2)print(argv[1])

D:\Python_classes>[Link]
Sunny

D:\
Python_classes>[Link]'SunnyLeone''Sunny

D:\
Python_classes>[Link]"SunnyLeone"Sunn
y Leone

Note2:WithinthePythonprogramcommandlineargumentsareavailableintheString form.
Based on our requirement, we can convert into corresponding type by using type casting
methods.

1)from sysimportargv
2)print(argv[1]+argv[2])
3)print(int(argv[1])+int(argv[2]))

AVERIIK TECHNOLOGY
49
AVERIIK TECHNOLOGY

D:\Python_classes>pytest.py1020
1020
30

Note3:Ifwearetryingtoaccesscommandlineargumentswithoutofrangeindexthen we will
get Error.

1)from sysimportargv
2)print(argv[100])

D:\Python_classes>pytest.py1020
IndexError: list index out of range

Note:InPythonthereisargparsemoduletoparsecommandlineargumentsanddisplay some
help messages whenever end user enters wrong input.

input()
raw_input()

CommandLineArguments

OutputStatements:
Wecanuseprint()functiontodisplay output.

Form-1:print()withoutanyargument
Just it prints new line character

Form-2:

1)print(String):
2)print("Hello World")
3)Wecanuse escapecharactersalso
4)print("Hello \n World")
5)print("Hello\tWorld")
6)Wecan userepetetionoperator (*) in the string
7)print(10*"Hello")
8)print("Hello"*10)
9)Wecanuse+operatoralso
10)print("Hello"+"World")

AVERIIK TECHNOLOGY
50
AVERIIK TECHNOLOGY

Note:
֍IfbothargumentsareStringtypethen+ operatoractsasconcatenationoperator.
֍If oneargumentisstringtypeandsecondisanyothertypelikeintthenwewillget Error.
֍Ifbothargumentsarenumbertypethen+operatoractsasarithmeticaddition operator.

Note:

1)print("Hello"+"World")
2)print("Hello","World")

HelloWorld
HelloWorld

Form-3:print()withvariablenumberofarguments

1)a,b,c=10,20,30
2)print("TheValuesare:",a,b,c)

Output:TheValuesare:102030

[Link] using
"sep" attribute

1)a,b,c=10,20,30
2)print(a,b,c,sep=',')
3)print(a,b,c,sep=':')

D:\Python_classes>[Link]
10,20,30
10:20:30

Form-4:print()withendattribute

1)print("Hello")
2)print("Durga")
3)print("Soft")

Output:
Hello
Durga
Soft

AVERIIK TECHNOLOGY
51
AVERIIK TECHNOLOGY

Ifwewantoutputinthesamelinewithspace

1)print("Hello",end='')
2)print("Durga",end='')
3)print("Soft")

Output:HelloDurgaSoft

Note:Thedefault valueforendattributeis\n,whichisnothingbutnewline character.

Form-5:print(object) statement

Wecanpassanyobject(likelist, tuple,setetc)asargumenttotheprint()statement.

1)l=[10,20,30,40]
2)t=(10,20,30,40)
3)print(l)
4)print(t)

Form-6:print(String,variablelist)

Wecanuseprint()statementwith Stringandanynumberofarguments.

1)s="Durga"
2)a =48
3)s1="Java"
4)s2="Python"
5)print("Hello",s,"YourAge is",a)
6)print("Youareteaching",s1,"and",s2)

Output:
Hello DurgaYourAgeis48
You areteachingjavaand Python

Form-7:print(formattedstring)

1) %i int
2) %dint
3) %ffloat
4) %sStringtype

Syntax:print("formattedstring"%(variablelist))

AVERIIK TECHNOLOGY
52
AVERIIK TECHNOLOGY

Eg 1:

1)a=10
2)b=20
3)c=30
4)print("avalue is %i"%a)
5)print("bvalueis %dandc valueis%d"%(b,c))

Output
avalueis 10
bvalueis20andcvalueis30 Eg 2:

1)s="Durga"
2)list=[10,20,30,40]
3)print("Hello %s...The ListofItemsare%s"%(s,list))

Output:HelloDurga...TheListofItemsare[10,20,30,40]

Form-8:print()withreplacementoperator{}
Eg:

1)name = "Durga"
2)salary = 10000
3)gf= "Sunny"
4)print("Hello{0}yoursalaryis{1}andYourFriend{2}iswaiting". format(name,salary,gf))

5)print("Hello{x}yoursalaryis{y}andYourFriend{z}iswaiting".
format(x=name,y=salary,z=gf))

Output
HelloDurgayoursalaryis10000andYourFriendSunnyiswaiting
HelloDurgayoursalaryis10000 andYourFriendSunnyiswaiting

AVERIIK TECHNOLOGY
53
AVERIIK TECHNOLOGY

FLOW
CONTROL

AVERIIK TECHNOLOGY
54
AVERIIK TECHNOLOGY

ControlFlow

Flowcontroldescribestheorderinwhichstatementswillbeexecutedatruntime.

Conditional Statements Transfer Statements Iterative Statements

break for
continue while
pass

1) if
I. Conditional
2) if-elif Statements
3) if-elif-else
1) if
ifcondition:statement OR

if condition :
statement-1
statement-2
statement-3

Ifconditionistruethenstatementswillbeexecuted. Eg:

1) name=input("EnterName:")
2)ifname=="durga":
3) print("HelloDurgaGoodMorning")
4)print("Howareyou!!!")

D:\Python_classes>[Link]
Enter Name:durga
HelloDurgaGoodMorning How
are you!!!

AVERIIK TECHNOLOGY
55
AVERIIK TECHNOLOGY

D:\Python_classes>[Link]
Enter Name: Ravi
How areyou!!!

2) if-else:
ifcondition:
Action-1
else:
Action-2

ifconditionistruethenAction-1 willbeexecuted otherwiseAction-2will be executed.

1) name=input("EnterName:")
2)ifname=="durga":
3) print("HelloDurgaGoodMorning")
4)else:
5) print("HelloGuestGood Moring")
6)print("Howareyou!!!")

D:\Python_classes>[Link]
Enter Name:durga
HelloDurgaGoodMorning How
are you!!!

D:\Python_classes>[Link]
Enter Name:Ravi
HelloGuestGoodMoring
How are you!!!

3) if-elif-else:
ifcondition1:
Action-1
elifcondition2:
Action-2
elifcondition3:
Action-3
elifcondition4:
Action-4
...
else:
DefaultAction

Basedconditionthecorrespondingactionwillbe executed.

AVERIIK TECHNOLOGY
56
AVERIIK TECHNOLOGY

1) brand=input("EnterYourFavouriteBrand:")
2)ifbrand=="RC":
3) print("Itischildrensbrand")
4)elifbrand=="KF":
5) print("Itisnotthatmuchkick")
6)elifbrand=="FO":
7) print("BuyonegetFreeOne")
8)else:
9) print("OtherBrandsarenotrecommended")

D:\Python_classes>py [Link]
EnterYourFavouriteBrand:RC
It is childrens brand

D:\Python_classes>py [Link]
EnterYourFavouriteBrand:KF It
is not that much kick

D:\Python_classes>[Link]
EnterYourFavouriteBrand:KALYANI
Other Brands are not recommended

Note:
1) [Link].
1) If
2) if–else
3) if-elif-else
4) if-elif
2) Thereisnoswitchstatementin Python

Q) Write aProgramtofindBiggest
ofgiven2NumbersfromtheCommad Prompt?
1) n1=int(input("EnterFirstNumber:"))
2)n2=int(input("Enter SecondNumber:"))
3)ifn1>n2:
4) print("BiggestNumberis:",n1)
5)else:
6) print("BiggestNumberis:",n2)

D:\Python_classes>[Link]
Enter First Number:10
EnterSecondNumber:20
Biggest Number is: 20

AVERIIK TECHNOLOGY
57
AVERIIK TECHNOLOGY

Q) Write aProgramtofindBiggest
ofgiven3NumbersfromtheCommad Prompt?
1) n1=int(input("EnterFirstNumber:"))
2)n2=int(input("Enter SecondNumber:"))
3)n3=int(input("EnterThirdNumber:"))
4)ifn1>n2andn1>n3:
5) print("BiggestNumberis:",n1)
6)elifn2>n3:
7) print("BiggestNumberis:",n2)
8)else:
9) print("BiggestNumberis:",n3)

D:\Python_classes>[Link]
Enter First Number:10
EnterSecondNumber:20
Enter Third Number:30
Biggest Number is: 30

D:\Python_classes>[Link]
Enter First Number:10
EnterSecondNumber:30
Enter Third Number:20
Biggest Number is: 30

Q)Writeaprogramtofindsmallestofgiven2 numbers?
Q)Writeaprogramtofindsmallestofgiven3 numbers?
Q)Writeaprogramtocheckwhetherthegivennumberisevenorodd?

Q)WriteaProgramtoCheckwhetherthegivenNumberisinbetween 1
and 100?
1)n=int(input("Enter Number:"))
2)ifn>=1andn<=10 :
3) print("Thenumber",n,"isinbetween 1to10")
4)else:
5) print("Thenumber",n,"isnotinbetween1to10")

AVERIIK TECHNOLOGY
58
AVERIIK TECHNOLOGY

Q)WriteaProgramtotakeaSingleDigitNumberfromtheKeyBoard and
Print is Value in English Word?
1)0ZERO
2)1ONE
3)
4)n=int(input("Enteradigitfrom oto9:"))
5)ifn==0:
6) print("ZERO")
7)elifn==1:
8) print("ONE")
9)elifn==2:
10) print("TWO")
11)elifn==3:
12) print("THREE")
13)elifn==4:
14) print("FOUR")
15)elifn==5:
16) print("FIVE")
17)elifn==6:
18) print("SIX")
19)elifn==7:
20) print("SEVEN")
21)elifn==8:
22) print("EIGHT")
23)elifn==9:
24) print("NINE")
25)else:
26) print("PLEASEENTERA DIGITFROM0TO9")

AVERIIK TECHNOLOGY
59
AVERIIK TECHNOLOGY

II. IterativeStatements
֍Ifwewanttoexecuteagroupofstatementsmultipletimesthenweshouldgofor Iterative
statements.
֍Pythonsupports2typesofiterative statements.
1) forloop
2) whileloop

1)forloop:
Ifwewanttoexecutesomeactionforeveryelementpresentinsomesequence (it may
be string or collection) then we should go for for loop.

Syntax:forxinsequence:
Body

Wheresequencecanbestringoranycollection.
Bodywillbeexecutedforeveryelementpresentinthe sequence.

Eg1:Toprintcharacterspresentinthegivenstring

1) s="SunnyLeone"
2)forxins:
3) print(x)

Output
S
u
n
n
y

L
e
o
n
e

Eg2:Toprintcharacterspresentinstringindexwise:

1)s=input("EntersomeString: ")
2)i=0
3)forxins:
4)print("Thecharacterpresentat",i,"indexis:",x)
5) i=i+1

AVERIIK TECHNOLOGY
60
AVERIIK TECHNOLOGY

D:\Python_classes>py [Link]
EntersomeString:SunnyLeone
The character present at0 index is : S
The character present at1 index is : u
The character present at2 index is : n
The character present at3 index is : n
The character present at4 index is : y
The character present at5 index is : The
character present at6 index is : L The
character present at7 index is : e The
character present at8 index is : o The
character present at9 index is : n
Thecharacterpresentat10indexis:e

Eg3:To printHello10times

1)forxin range(10):
2)print("Hello")

Eg4:To displaynumbersfrom0to10

1)forxin range(11):
2)print(x)

Eg5:To displayoddnumbersfrom0to20

1)forxin range(21):
2)if(x%2!=0):
3) print(x)

Eg6:Todisplaynumbersfrom10to 1indescending order

1)forxin range(10,0,-1):
2)print(x)

Eg7:Toprintsumof numberspresenstinsidelist

1)list= eval(input("Enter List:"))


2)sum=0;
3)forxinlist:
5)print("TheSum=",sum)
4) sum=sum+x;

AVERIIK TECHNOLOGY
61
AVERIIK TECHNOLOGY

D:\Python_classes>[Link]
Enter List:[10,20,30,40]
TheSum=100

D:\Python_classes>[Link]
Enter List:[45,67]
TheSum=112

2)whileloop:
Ifwewanttoexecuteagroupofstatementsiterativelyuntilsomeconditionfalse,then we
should go for while loop.

Syntax:whilecondition:
body

Eg:Toprintnumbersfrom1to10byusingwhileloop

1) x=1
2)while x <= 10:
3) print(x)
4)x=x+1

Eg:Todisplaythesumoffirstn numbers

1)n=int(input("Enter number:"))
2)sum=0
3)i=1
4)whilei<=n:
5) sum=sum+i
6)i=i+1
7)print("Thesumoffirst",n,"numbers is:",sum)

Eg:WriteaprogramtopromptusertoentersomenameuntilenteringDurga

1)name=""
2)whilename!="durga":
3) name=input("EnterName:")
4)print("Thanksforconfirmation")

AVERIIK TECHNOLOGY
62
AVERIIK TECHNOLOGY

InfiniteLoops:
1)i=0;
2)whileTrue:
3) i=i+1;
4)print("Hello",i)

NestedLoops:
Sometimeswecantakealoopinsideanotherloop,whicharealsoknownasnested loops.

1)for iinrange(4):
2)for jin range(4):
3) print("i=",i,"j=",j)

Output
D:\Python_classes>[Link]
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

Q)WriteaProgramtodispaly*'sinRightAngledTriangledForm
* 1) n=int(input("Enternumberofrows:"))
** 2) for i in range(1,n+1): forjinrange(1,i+1):
*** 3) print("*",end="")
**** 4)
***** 5) print() AlternativeWay
****** 1)n =int(input("Enternumber ofrows:"))
******* 2)for iinrange(1,n+1):
3)print("*"*i)

AVERIIK TECHNOLOGY
63
AVERIIK TECHNOLOGY

Q)WriteaProgramtodisplay*'sinPyramidStyle(Also
known as EquivalentTriangle)
*
** 1)n=int(input("Enternumberof rows:"))
***
**** 2)for i inrange(1,n+1):
3)print(""* (n-i),end="")
*****
****** 4)print("*"*i)
*******

III. TransferStatements
1)break:
Wecanusebreakstatementinsideloopstobreakloopexecutionbasedonsome condition.

1)for iinrange(10):
2)ifi==7:
3) print("processingisenough..plzbreak")
4) break
5)print(i)

D:\Python_classes>[Link]
0
1
2
3
4
5
6
processingisenough..plzbreak Eg:

1) cart=[10,20,600,60,70]
2)foritemin cart:
3) ifitem>500:
4) print("Toplacethisorderinsurencemustberequired")
5) break
6) print(item)

AVERIIK TECHNOLOGY
64
AVERIIK TECHNOLOGY

D:\Python_classes>[Link]
10
20
Toplacethisorderinsurencemust berequired

2)continue:
Wecanusecontinuestatementtoskipcurrentiterationandcontinuenextiteration.

Eg1:Toprintodd numbersin therange0to9

1) for iinrange(10):
2)ifi%2==0:
3) continue
4)print(i)

D:\Python_classes>[Link]
1
3
5
7
9

Eg2:

1)cart=[10,20,500,700,50,60]
2)foritemin cart:
3) ifitem>=500:
4) print("Wecannotprocessthisitem :",item)
5) continue
6) print(item)

D:\Python_classes>[Link]
10
20
Wecannotprocessthisitem:500
Wecannotprocessthisitem:700 50
60

AVERIIK TECHNOLOGY
65
AVERIIK TECHNOLOGY

Eg3:

1)numbers=[10,20,0,5,0,30]
2)for ninnumbers:
3) ifn==0:
4) print("Heyhowwecandividewithzero..just skipping")
5) continue
6) print("100/{}= {}".format(n,100/n))

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

LoopswithelseBlock:
 Insideloopexecution, ifbreakstatementnotexecuted,thenonlyelsepartwillbe
executed.
 elsemeansloopwithoutbreak.

1)cart=[10,20,30,40,50]
2)foritemin cart:
3) ifitem>=500:
4) print("Wecannotprocessthisorder")
5) break
6) print(item)
7)else:
8) print("Congrats...allitemsprocessed successfully")

Output
10
20
30
40
50
Congrats...allitemsprocessedsuccessfully

AVERIIK TECHNOLOGY
66
AVERIIK TECHNOLOGY

Eg:

1)cart=[10,20,600,30,40,50]
2)foritemin cart:
3) ifitem>=500:
4) print("Wecannotprocessthisorder")
5) break
6) print(item)
7)else:
8) print("Congrats...allitemsprocessed successfully")

Output D:\
Python_classes>[Link] 10
20
Wecannotprocessthis order

Q)Whatisthedifferencebetweenforloopandwhileloopin
Python?
֍Wecan useloopstorepeat code execution
֍Repeat codeforeveryitemin sequence forloop
֍Repeat code aslongasconditionistruewhile loop

Q)Howtoexitfromtheloop?Byusingbreakstatement

Q)Howtoskipsomeiterationsinsideloop?Byusingcontinuestatement.

Q)Whenelsepartwillbeexecutedwrtloops?Ifloopexecutedwithout break

3)pass statement:
 pass isakeywordinPython.
 Inourprogrammingsyntacticallyifblockisrequiredwhichwon'tdoanythingthenwe can
define that empty block with pass keyword.

pass
|-Itisanemptystatement
|-Itisnull statement
|-Itwon'tdo anything

Eg:if True:
SyntaxError:unexpectedEOFwhileparsing if
True: pass valid

AVERIIK TECHNOLOGY
67
AVERIIK TECHNOLOGY

def m1():
SyntaxError:unexpectedEOFwhileparsing

def m1(): pass

UseCaseofpass:
Sometimesintheparentclasswehavetodeclareafunction withemptybodyandchild class
responsible to provide proper implementation. Such type of empty body we can define
by using pass keyword. (It is something like abstract method in Java)
Eg:defm1():pass

1) foriinrange(100):
2)ifi%9==0:
3) print(i)
4)else:pass

D:\Python_classes>[Link]
0
9
18
27
36
45
54
63
72
81
90
99

del Statement:
 delisakeywordinPython.
 Afterusingavariable,itis highlyrecommendedtodeletethatvariableifitisnolonger
required,so that the corresponding object is eligible for Garbage Collection.
 Wecandeletevariablebyusingdel keyword.

1)x=10
2)print(x)
3)delx

AVERIIK TECHNOLOGY
68
AVERIIK TECHNOLOGY

AfterdeletingavariablewecannotaccessthatvariableotherwisewewillgetNameError.

1)x=10
2)delx
3)print(x)

NameError:name'x'isnotdefined.

Note:[Link] delete
the elements present inside immutable object.

1)s="durga"
2)print(s)
3)delsvalid
4)del s[0]TypeError: 'str'object doesn'tsupportitem deletion

DifferencebetweendelandNone:
Inthecasedel,thevariablewillberemovedandwecannotaccessthatvariable(unbind
operation)

1)s="durga"
2)dels
3) print(s)NameError:name's'isnotdefined.

ButinthecaseofNoneassignmentthevariablewon'tberemovedbutthecorresponding object
is eligible for Garbage Collection (re bind operation). Hence after assigning with None
value, we can access that variable.

1) s="durga"
2)s=None
3) print(s)None

AVERIIK TECHNOLOGY
69
AVERIIK TECHNOLOGY

STRING
DATATYPE

AVERIIK TECHNOLOGY
70
AVERIIK TECHNOLOGY

ThemostcommonlyusedobjectinanyprojectandinanyprogramminglanguageisString only.
Hence we should aware complete information about String data type.

What is String?
Anysequenceofcharacterswithineithersinglequotesordoublequotesisconsideredasa String.

Syntax:
s = 'durga'
s="durga"

Note:In most of other languges like C, C++, Java, a single character with in single quotes
[Link] is
treated as String only.

Eg:
>>> ch ='a'
>>>type(ch)
<class'str'>

Howtodefinemulti-lineStringLiterals?
Wecandefinemulti-lineStringliteralsbyusingtriplesingleordoublequotes.

Eg:
>>>s='''durgasoft
waresolutions'''

Wecanalsousetriplequotestousesinglequotesordoublequotesassymbolinside String
literal.

1) s = 'Thisis'singlequotesymbol'Invalid
2) s = 'Thisis \'singlequotesymbol'Valid
3) s= "Thisis'singlequotesymbol"Valid
4) s= 'Thisis" doublequotessymbol'Valid
5) s='The"PythonNotes"by'durga'isveryhelpful'Invalid
6) s="The"PythonNotes"by'durga'isveryhelpful"Invalid
7) s= 'The\"PythonNotes\"by\'durga\'isveryhelpful'Valid
8) s='''The"PythonNotes"by'durga'isveryhelpful'''Valid

AVERIIK TECHNOLOGY
71
AVERIIK TECHNOLOGY

HowtoAccess Characters ofa String?


Wecanaccess charactersof astringbyusingthefollowingways.
1) Byusingindex
2) Byusingslice operator

1)AccessingCharactersByusingIndex:
 Pythonsupportsboth +veand-veIndex.
 +veIndexmeansLefttoRight (Forward Direction)
 -veIndexmeansRighttoLeft(BackwardDirection)
Eg:s='durga'

1)>>>s='durga'
2)>>>s[0]
3)'d'
4)>>>s[4]
5)'a'
6)>>>s[-1]
7)'a'
8)>>>s[10]
9)IndexError:stringindexoutofrange

Note:Ifwearetryingtoaccesscharactersofastringwithoutofrangeindexthenwewill get error


saying: IndexError

Q)WriteaProgramtoAcceptsome
StringfromtheKeyboardanddisplayitsCharacters by Index wise (both
Positive and Negative Index)

[Link]:

1)s=input("Enter Some String:")


2)i=0
3)forxin s:
4)print("Thecharacterpresentatpositiveindex{}andatnEgativeindex{}is{}".fo rmat(i,i-len(s),x))

5) i=i+1

Output:D:\python_classes>[Link]
Enter Some String:durga
Thecharacterpresentatpositiveindex0andatnEgativeindex -5isd
Thecharacterpresentatpositiveindex1andatnEgativeindex -4isu
Thecharacterpresent atpositiveindex 2 andatnEgativeindex -3isr
Thecharacterpresentatpositiveindex3andatnEgativeindex -2isg
Thecharacterpresentatpositiveindex4andatnEgativeindex -1isa
AVERIIK TECHNOLOGY
72
AVERIIK TECHNOLOGY

2)AccessingCharactersbyusingSliceOperator:
 Syntax:s[bEginindex:endindex:step]

 BeginIndex:Fromwherewehavetoconsiderslice(substring)
 EndIndex:Wehavetoterminatetheslice(substring)atendindex-1
 Step:Incremented Value.

Note:
 IfwearenotspecifyingbEginindexthenitwillconsiderfrombEginningofthe string.
 Ifwearenotspecifyingendindexthenitwill consideruptoendofthe string.
 Thedefaultvalueforstepis1.

1)>>>s="LearningPythonisveryvery easy!!!"
2)>>>s[1:7:1]
3)'earnin'
4)>>>s[1:7]
5)'earnin'
6)>>>s[1:7:2]
7)'eri'
8)>>>s[:7]
9)'Learnin'
10)>>>s[7:]
11)'gPythonisveryveryeasy!!!'
12)>>>s[::]
13)'LearningPythonisveryveryeasy!!!'
14)>>>s[:]
15)'LearningPythonisveryveryeasy!!!'
16)>>>s[::-1]
17)'!!!ysaeyrev yrevsinohtyPgninraeL'

BehaviourofSliceOperator:
1) s[bEgin:end:step]
2) Stepvaluecanbeeither+veor–ve
3) If+vethenitshouldbeforwarddirection(lefttoright)andwe havetoconsiderbEgin to end-
1
4) If-vethenitshouldbebackwarddirection (righttoleft)andwehavetoconsiderbEgin to
end+1.

***Note:
 Inthebackwarddirectionifendvalueis-1thenresultisalwaysempty.
 Intheforwarddirectionifendvalueis0thenresultisalways empty.

AVERIIK TECHNOLOGY
73
AVERIIK TECHNOLOGY

InForwardDirection:
defaultvalueforbEgin:0
defaultvalueforend:lengthofstring default
value for step: +1

InBackwardDirection:
defaultvalueforbEgin: -1
defaultvalueforend:-(lengthofstring+1)

Note:Eitherforwardorbackwarddirection,wecantakeboth+veand -vevaluesfor bEgin and end


index.

SliceOperatorCaseStudy:
1) S='abcdefghij'
2) s[1:6:2]'bdf'
3) s[::1]'abcdefghij'
4) s[::-1]'jihgfedcba'
5) s[3:7:-1]''
6) s[7:4:-1]'hgf'
7) s[0:10000:1]'abcdefghij'
8) s[-4:1:-1]'gfedc'
9) s[-4:1:-2]'gec'
10) s[5:0:1]''
11) s[9:0:0]ValueError:slicestepcannotbezero
12) s[0:-10:-1]''
13) s[0:-11:-1]'a'
14) s[0:0:1]''
15) s[0:-9:-2]''
16) s[-5:-9:-2]'fd'
17) s[10:-1:-1]''
18) s[10000:2:-1]'jihgfed'

Note:SliceoperatorneverraisesIndexError

MathematicalOperatorsforString:
WecanapplythefollowingmathematicaloperatorsforStrings.
1)+ operatorfor concatenation
2)* operatorfor repetition

 print("durga"+"soft")durgasoft
 print("durga"*2)durgadurga

AVERIIK TECHNOLOGY
74
AVERIIK TECHNOLOGY

Note:
1) Touse+operatorforStrings,compulsorybothargumentsshouldbestrtype.
2) Touse*operatorforStrings,compulsoryoneargumentshouldbestrandother
argument should be int.

len()in-builtFunction:
Wecanuselen()functiontofindthenumberofcharacterspresentinthestring. Eg:
s = 'durga'
print(len(s))5

Q) Writea Program to access each Character of String


inForwardandBackwardDirectionbyusingwhileLoop?
1) s="LearningPythonisveryeasy!!!"
2)n=len(s)
3)i=0
4)print("Forward direction")
5)whilei<n:
6) print(s[i],end='')
7) i+=1
8)print("Backward direction")
9)i=-1
10)whilei>=-n:
11) print(s[i],end='')
12) i= i-1

Alternativeways:
1)s= "Learning Pythonisveryeasy!!!"
2)print("Forward direction")
3)for iins:
4) print(i,end='')
5) print("Forwarddirection")
6)for iins[::]:
7) print(i,end='')
8)
9)print("Backward direction")
10)foriins[::-1]:
11) print(i,end='')

AVERIIK TECHNOLOGY
75
AVERIIK TECHNOLOGY

CheckingMembership:
Wecancheckwhetherthecharacterorstringisthememberofanotherstringornotby using in
and not in operators

s='durga'
print('d'ins)Trueprint('z'i
ns)False

1)s =input("Entermain string:")


2)subs=input("Entersubstring:")
3)ifsubsins:
4) print(subs,"isfoundinmainstring")
5)else:
6) print(subs,"isnotfoundinmain string")

Output:
D:\python_classes>[Link]
Entermainstring:durgasoftwaresolutions
Enter sub string:durga
durgaisfoundinmain string

D:\python_classes>[Link]
Entermainstring:durgasoftwaresolutions
Enter sub string:python
pythonisnotfoundinmain string

ComparisonofStrings:
 Wecanusecomparisonoperators(<,<=,>,>=)andequalityoperators (==,!=)for
strings.
 Comparisonwillbeperformedbasedonalphabeticalorder.

1)s1=input("Enterfirst string:")
2)s2=input("EnterSecondstring:")
3)ifs1==s2:
4) print("Bothstringsareequal")
5)elifs1<s2:
6) print("FirstStringislessthanSecondString")
7)else:
8) print("FirstStringisgreaterthanSecond String")

Output:D:\
python_classes>[Link]
Enter first string:durga

AVERIIK TECHNOLOGY
76
AVERIIK TECHNOLOGY

EnterSecondstring:durga
Both strings are equal

D:\python_classes>[Link]
Enter first string:durga
EnterSecond string:ravi
FirstStringislessthanSecond String

D:\python_classes>[Link]
Enter first string:durga
EnterSecond string:anil
FirstStringisgreaterthanSecondString

RemovingSpacesfromtheString:
Wecan usethefollowing3 methods

1) rstrip()Toremovespacesatrighthandside
2) lstrip()Toremovespacesatlefthandside
3) strip()Toremovespacesboth sides

1)city=input("Enteryour cityName:")
2)scity=[Link]()
3)ifscity=='Hyderabad':
4) print("HelloHyderbadi..Adab")
5)elifscity=='Chennai':
6) print("HelloMadrasi...Vanakkam")
7)elifscity=="Bangalore":
8) print("Hello Kannadiga...Shubhodaya")
9)else:
10) print("yourenteredcityisinvalid")

FindingSubstrings:
Wecan usethe following4 methods

Forforwarddirection:
1) find()
2) index()

Forbackwarddirection:
1) rfind()
2) rindex()

AVERIIK TECHNOLOGY
77
AVERIIK TECHNOLOGY

find():
[Link](substring)
[Link] get -1.

1)s="LearningPythonisveryeasy"
2)print([Link]("Python"))#9
3) print([Link]("Java"))#-1
4)print([Link]("r"))#3
5)print([Link]("r"))#21

Note:Bydefaultfind()[Link] boundaries
to search.

[Link](substring,bEgin,end)
Itwill alwayssearchfrombEginindexto end-1 index.

1)s="durgaravipavanshiva"
2)print([Link]('a'))#4
3)print([Link]('a',7,15))#10
4)print([Link]('z',7,15))#-1

index():
index()methodisexactlysameasfind()method exceptthatifthespecifiedsubstringis not
available then we will get ValueError.

1)s=input("Enter mainstring:")
2)subs=input("Enter substring:")
3)try:
4) n=[Link](subs)
5)exceptValueError:
6) print("substringnotfound")
7)else:
8) print("substringfound")

Output:
D:\python_classes>[Link]
Entermainstring:learningpythonisveryeasy Enter
sub string:python
substringfound

78 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

D:\python_classes>[Link]
Entermainstring:learningpythonisveryeasy
Enter sub string:java
substringnotfound

Q)ProgramtodisplayallPositionsofSubstringinagivenMain
String
1)s=input("Enter mainstring:")
2)subs=input("Enter substring:")
3)flag=False
4)pos=-1
5)n=len(s)
6)whileTrue:
7) pos=[Link](subs,pos+1,n)
8)ifpos==-1:
9) break
10)print("Foundatposition",pos)
11) flag=True
12)ifflag==False:
13) print("NotFound")

Output:
D:\python_classes>[Link]
Entermainstring:abbababababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Foundatposition11

D:\python_classes>[Link]
Entermainstring:abbababababacdefg
Enter sub string:bb
Foundatposition1

CountingsubstringinthegivenString:
Wecanfindthenumberofoccurrences ofsubstringpresentinthegivenstringbyusing count()
method.
1) [Link](substring)Itwillsearchthroughoutthestring.
2) [Link](substring,bEgin,end)ItwillsearchfrombEginindextoend-1 index.

79 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

1)s="abcabcabcabcadda"
2)print([Link]('a'))
3)print([Link]('ab'))
4)print([Link]('a',3,7))

Output:
6
4
2

ReplacingaStringwithanotherString:
[Link](oldstring,newstring)
insides,everyoccurrenceofoldStringwillbereplacedwithnewString.

Eg1:
s="LearningPythonisverydifficult"s1 =
[Link]("difficult","easy")print(s1)

Output:LearningPythonisveryeasy

Eg2:Alloccurrenceswillbereplaced s =
"ababababababab"
s1=[Link]("a","b")print(s1)

Output:bbbbbbbbbbbbbb

Q)StringObjectsareImmutablethenhowwecanchangetheContent by
using replace() Method
 Once we creates string object, we cannot change the [Link] non changeable
[Link]
anymethod,thenwiththosechangesanewobjectwillbecreatedandchangeswon't be
happend in existing object.
 Hencewithreplace()methodalsoanewobjectgotcreatedbutexistingobjectwon't be
changed.

Eg:
s="abab"
s1 = [Link]("a","b")print(s,"is
available at :",id(s))
print(s1,"isavailableat:",id(s1))

80 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Output:
ababisavailableat:4568672
bbbbisavailableat: 4568704

Intheaboveexample,originalobjectisavailableandwecanseenewobjectwhichwas created
because of replace() method.

SplittingofStrings:
 Wecansplitthegivenstringaccordingtospecifiedseperatorbyusingsplit() method.
 l= [Link](seperator)
 [Link]()methodis List.

1)s="durgasoftware solutions"
2)l=[Link]()
3)forxin l:

4) print(x)

Output:
durga
software
solutions

1)s="22-02-2018"
2)l=[Link]('-')
3)forxin l:
4)print(x)

Output:
22
02
2018

JoiningofStrings:
WecanjoinaGroupofStrings(ListORTuple)wrtthegivenSeperator.
s=[Link](group of strings)

Eg 1:
t=('sunny','bunny','chinny')s
= '-'.join(t)
print(s)

Output:sunny-bunny-chinny

81 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Eg 2:
l=['hyderabad','singapore','london','dubai']s =
':'.join(l)
print(s)

Output:hyderabad:singapore:london:dubai

ChangingCaseofaString:
Wecanchangecaseof astringbyusingthefollowing4 methods.

1) upper()Toconvert allcharacterstoupper case


2) lower()Toconvertallcharacterstolower case
3) swapcase()Convertsalllowercasecharacterstouppercase andalluppercase
characters to lower case
4) title()[Link] be
upper case and all remaining characters should be in lower case.
5) capitalize()Onlyfirstcharacterwillbeconverted touppercaseandallremaining
characters can be converted to lower case

1) s='learningPythonisvery Easy'
2)print([Link]())
3)print([Link]())
4)print([Link]())
5)print([Link]())
6)print([Link]())

Output:
LEARNINGPYTHONISVERYEASY
learning python is very easy
LEARNINGpYTHONISVERYeASY
LearningPythonIsVeryEasy
Learningpythonisvery easy

CheckingStartingandEndingPartoftheString:
Pythoncontainsthefollowingmethodsforthispurpose
1) [Link](substring)
2) [Link](substring)

1)s= 'learningPython isveryeasy'


2)print([Link]('learning'))
3)print([Link]('learning'))
4)print([Link]('easy'))

82 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Output:
True
False
True

ToCheckTypeofCharactersPresentinaString:
Pythoncontainsthefollowingmethodsforthispurpose.

1) isalnum():ReturnsTrueif allcharactersarealphanumeric(ato z,Ato Z,0to9 )


2) isalpha():ReturnsTrueifallcharactersareonlyalphabetsymbols(atoz,AtoZ)
3) isdigit(): ReturnsTrueifallcharactersaredigitsonly(0to9)
4) islower():ReturnsTrueifallcharactersarelowercasealphabetsymbols
5) isupper():ReturnsTrueifallcharactersareuppercaseaplhabet symbols
6) istitle(): ReturnsTrueifstringisintitlecase
7) isspace():ReturnsTrueifstringcontainsonly spaces

Eg:
1) print('Durga786'.isalnum())True
2) print('durga786'.isalpha())False
3) print('durga'.isalpha())True
4) print('durga'.isdigit())False
5) print('786786'.isdigit())True
6) print('abc'.islower())True
7) print('Abc'.islower())False
8) print('abc123'.islower())True
9) print('ABC'.isupper())True
10) print('LearningpythonisEasy'.istitle())False
11) print('LearningPythonIsEasy'.istitle())True
12) print(' '.isspace())True

Demo Program:

1) s=input("Enteranycharacter:")
2)[Link]():
3) print("AlphaNumericCharacter")
4) [Link]():
5) print("Alphabetcharacter")
6) [Link]():
7) print("Lowercasealphabetcharacter")
8) else:
9) print("Uppercasealphabetcharacter")
10) else:
11) print("itisadigit")
12)[Link]():

83 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

13) print("Itisspace character")


14)else:
15) print("NonSpaceSpecialCharacter")

D:\python_classes>[Link]
Enter any character:7
AlphaNumericCharacter
it is a digit

D:\python_classes>[Link]
Enter any character:a
AlphaNumericCharacter
Alphabet character
Lowercasealphabet character

D:\python_classes>[Link]
Enter any character:$
NonSpaceSpecial Character

D:\python_classes>[Link]
Enter any character:A
AlphaNumericCharacter
Alphabet character
Uppercasealphabet character

FormattingtheStrings:
Wecanformatthestringswithvariablevaluesbyusingreplacementoperator{}and format()
method.

1)name = 'durga'
2)salary = 10000
3)age= 48
4)print("{}'s salary is{}andhis ageis {}".format(name,salary,age))
5)print("{0}'s salaryis {1}andhis ageis {2}".format(name,salary,age))
6)print("{x}'s salaryis {y}and his ageis{z}".format(z=age,y=salary,x=name))

Output:
durga'ssalaryis10000andhisageis48
durga'ssalaryis10000andhisageis48
durga'ssalaryis10000andhis ageis48

84 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

ImportantProgramsregardingStringConcept

Q1)WriteaProgramtoReversethegiven String
Input: durga
Output:agrud

1stWay:
1)s=input("EnterSome String:")
2)print(s[::-1])

2ndWay:
1)s=input("EnterSome String:")
2)print(''.join(reversed(s)))

3rdWay:
1)s=input("EnterSome String:")
2)i=len(s)-1
3)target=''
4)whilei>=0:
5) target=target+s[i]
6)i=i-1
7)print(target)

Q2)ProgramtoReverseOrderofWords
Input: Learning Python is very Easy
Output:EasyVeryisPythonLearning

1)s=input("Enter Some String:")


2)l=[Link]()
3)l1=[]
4)i=len(l)-1
5)whilei>=0:
6) [Link](l[i])
7) i=i-1
8)output=''.join(l1)
9)print(output)

Output:EnterSomeString:LearningPythonisveryeasy!!
easy!!! very is Python Learning

85 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Q3)ProgramtoReverseInternalContentofeach Word
Input: Durga Software Solutions
Output:agruDerawtfoSsnoituloS

1) s=input("EnterSomeString:")
2)l=[Link]()
3)l1=[]
4)i=0
5)whilei<len(l):
6)[Link](l[i][::-1])
7) i=i+1
8)output=''.join(l1)
9)print(output)

Q4)WriteaProgramtoPrintCharactersatOddPositionandEven
Position for the given String?
1stWay:
s = input("Enter Some
String:")print("CharactersatEvenPosition:",s[0
::2])print("Characters at Odd
Position:",s[1::2])

2ndWay:
1)s=input("Enter Some String:")
2)i=0
3)print("Characters atEven Position:")
4)while i< len(s):
5) print(s[i],end=',')
6) i=i+2
7)print()
8)print("Characters atOdd Position:")
9)i=1
10)whilei<len(s):
11) print(s[i],end=',')
12) i=i+2

86 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Q5)ProgramtoMergeCharactersof2StringsintoaSingleString
by taking Characters alternatively
Input:s1= "ravi"
s2="reja"
Output: rtaevjia

1)s1=input("EnterFirstString:")
2)s2=input("EnterSecondString:")
3)output=''
4)i,j=0,0
5)whilei<len(s1)orj<len(s2):
6) ifi<len(s1):
7) output=output+s1[i]
8) i+=1
9) ifj<len(s2):
10) output=output+s2[j]
11) j+=1
12)print(output)

Output:
Enter First String:durga
EnterSecondString:ravisoft
druarvgiasoft

Q6)WriteaProgramtoSorttheCharactersoftheStringandFirst
Alphabet Symbols followed by Numeric Values
Input: B4A1D3
Output:ABD134

1)s=input("Enter Some String:")


2)s1=s2=output=''
3)forxin s:
4) [Link]():
5) s1=s1+x
6) else:
7) s2=s2+x
8)forxin sorted(s1):
9) output=output+x
10)for xinsorted(s2):
11) output=output+x
12)print(output)

87 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Q7)WriteaProgramforthefollowing Requirement
Input: a4b3c2
Output:aaaabbbcc

1)s=input("Enter Some String:")


2)output=''
3)forxin s:

4)[Link]():
5) output=output+x
6) previous=x
7)else:
9)print(output)
8) output=output+previous*(int(x)-1)

Note: chr(unicode) The corresponding character


ord(character)Thecorrespondingunicodevalue

Q8)WriteaProgramtoperformthefollowingActivity
Input: a4k3b2
Outpt:aeknbd

1)s=input("Enter Some String:")


2)output=''
3)forxin s:
4)[Link]():
5) output=output+x
6) previous=x
7)else:
9)print(output)
8) output=output+chr(ord(previous)+int(x))

Q9)WriteaProgramtoRemoveDuplicateCharactersfromthe
given Input String?
Input:ABCDABBCDABBBCCCDDEEEF
Output:ABCDEF

1)s=input("EnterSome String:")
2)l=[]
3)forxin s:
4)ifxnot in l:
5) [Link](x)
6)output=''.join(l)
7)print(output)

88 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Q10)WriteaProgramtofindtheNumberofOccurrencesofeach
Character present in the given String?
Input:ABCABCABBCDE
Output:A-3,B-4,C-3,D-1,E-1

1)s=input("EntertheSome String:")
2)d={}
3)forxin s:
4)ifxin [Link]():
5) d[x]=d[x]+1
6)else:
7) d[x]=1
8)fork,[Link]():
9) print("{}={}Times".format(k,v))

Q11)WriteaProgramtoperformthefollowingTask?
Input: 'one two three four five six seven'
Output:'oneowtthreeruoffivexisseven'

1)s=input('EnterSomeString:')
2)l=[Link]()
3)l1=[]
4)i=0
5)whilei<len(l):
6)ifi%2==0:
7) [Link](l[i])
8)else:
9) [Link](l[i][::-1])
10)i=i+1
11)output=''.join(l1)
12)print('OriginalString:',s)
13)print('outputString:',output)

Output:
D:\durgaclasses>[Link]
EnterSomeString:onetwothreefourfivesixseven
Original String: one two three four five six seven
output String: one owt three ruof five xis seven

89 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

FormattingtheStrings:
֍Wecanformatthestringswithvariablevaluesbyusingreplacementoperator{}and format()
method.
֍Themainobjectiveofformat()methodtoformatstringintomeaningfuloutput form.

Case-1:Basicformattingfordefault,positionalandkeywordarguments

1)name = 'durga'
2)salary = 10000
3)age= 48
4)print("{}'s salary is{}andhis ageis {}".format(name,salary,age))
5)print("{0}'s salaryis {1}andhis ageis {2}".format(name,salary,age))
6)print("{x}'s salaryis {y}and his ageis{z}".format(z=age,y=salary,x=name))

Output:
durga'ssalaryis10000andhisageis48
durga'ssalaryis10000andhisageis48
durga'ssalaryis10000and hisageis48

Case-2:FormattingNumbers d

Decimal IntEger
fFixedpointnumber(float).Thedefaultprecisionis6 b
Binary format
oOctalFormat
xHexaDecimalFormat(Lowercase)
XHexaDecimalFormat (Uppercase)

Eg-1:

1) print("TheintEgernumberis:{}".format(123))
2)print("TheintEger number is: {:d}".format(123))
3)print("TheintEger number is: {:5d}".format(123))
4)print("TheintEger number is: {:05d}".format(123))

Output:
The intEger number is: 123
The intEger number is: 123
The intEger number is:123
TheintEgernumberis:00123

90 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Eg-2:

1)print("Thefloatnumberis: {}".format(123.4567))
2)print("Thefloatnumberis: {:f}".format(123.4567))
3)print("Thefloatnumberis: {:8.3f}".format(123.4567))
4)print("Thefloatnumberis: {:08.3f}".format(123.4567))
5)print("Thefloatnumberis: {:08.3f}".format(123.45))
6)print("Thefloatnumberis: {:08.3f}".format(786786123.45))

Output:
The float number is: 123.4567
Thefloatnumberis:123.456700
The float number is:123.457 The
float number is: 0123.457 The
float number is: 0123.450
Thefloatnumber is: 786786123.450

Note:
֍{:08.3f}
֍Totalpositionsshouldbeminimum8.
֍Afterdecimalpointexactly3digitsareallowed.Ifitislessthen0swillbeplacedinthe last
positions
֍If totalnumberis< 8positionsthen0willbeplaced inMSBs
֍Iftotalnumberis>8positionsthenallintEgral digitswill beconsidered.
֍Theextradigits wecan takeonly0

Note:FornumbersdefaultalignmentisRightAlignment(>)

Eg-3:PrintDecimalvalueinbinary,octalandhexadecimalform

1)print("Binary Form:{0:b}".format(153))
2)print("Octal Form:{0:o}".format(153))
3)print("HexadecimalForm:{0:x}".format(154))
4)print("HexadecimalForm:{0:X}".format(154))

Output:
BinaryForm:10011001
Octal Form:231
HexadecimalForm:9a
HexadecimalForm:9A

Note:Wecanrepresentonlyintvaluesinbinary,octalandhexadecimalanditisnot possible for


float values.

91 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Note:
1) {:5d}IttakesanintEgerargumentandassignsaminimumwidthof5.
2) {:8.3f}Ittakesafloatargumentandassignsaminimumwidthof8 including"."and after
decimal point excatly 3 digits are allowed with round operation if required
3) {:05d}Theblankplacescanbefilledwith0.Inthisplaceonly0 allowed.

Case-3:Numberformattingforsigned numbers
֍Whiledisplayingpositivenumbers,ifwewant toinclude+ thenwehaveto write
{:+d} and {:+f}
֍Usingplusfor-venumbersthereisnouseandfor -venumbers-signwillcome automatically.

1) print("intvaluewith sign:{:+d}".format(123))
2)print("intvaluewithsign:{:+d}".format(-123))
3)print("float valuewith sign:{:+f}".format(123.456))
4)print("floatvaluewithsign:{:+f}".format(-123.456))

Output:
intvaluewithsign:+123 int
value with sign:-123
floatvaluewithsign:+123.456000 float
value with sign:-123.456000

Case-4:Numberformattingwith alignment

֍<,>,^ and= areusedforalignment


֍<LeftAlignmenttotheremainingspace
֍^Centeralignmentto theremainingspace
֍>Rightalignmenttotheremainingspace
֍= Forces the signed(+) (-) to the left most position

Note:DefaultAlignmentfornumbersisRightAlignment. Ex:

1)print("{:5d}".format(12))
2)print("{:<5d}".format(12))
3)print("{:<05d}".format(12))
4)print("{:>5d}".format(12))
5)print("{:>05d}".format(12))
6)print("{:^5d}".format(12))
7)print("{:=5d}".format(-12))
8)print("{:^10.3f}".format(12.23456))
9)print("{:=8.3f}".format(-12.23456))

92 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

Output:
12
12
12000
12
00012
12
-12
12.235
-12.235

Case-5:Stringformattingwithformat()
Similartonumbers,wecanformatStringvaluesalsowithformat() method. [Link](string)

1)print("{:5d}".format(12))
2)print("{:5}".format("rat"))
3)print("{:>5}".format("rat"))
4)print("{:<5}".format("rat"))
5)print("{:^5}".format("rat"))
6)print("{:*^5}".format("rat"))#Insteadof*wecanuseanycharacter(like+,$,aetc)

Output:
12
rat
rat
rat
rat
*rat*

Note:Fornumbersdefaultalignmentisrightwhereasforstringsdefaultalignmentis left

Case-6:TruncatingStringswithformat()method

1)print("{:.3}".format("durgasoftware"))
2)print("{:5.3}".format("durgasoftware"))
3)print("{:>5.3}".format("durgasoftware"))
4)print("{:^5.3}".format("durgasoftware"))
5)print("{:*^5.3}".format("durgasoftware"))

Output:
dur
dur
dur

93 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

dur
*dur*

Case-7:Formattingdictionarymembersusingformat()

1)person={'age':48,'name':'durga'}
2)print("{p[name]}'sageis: {p[age]}".format(p=person))

Output:
durga'sageis: 48
Note: pisaliasnameofdictionary
persondictionarywearepassingaskeywordargument

More convinient way is to use **person

1)person={'age':48,'name':'durga'}
2)print("{name}'s ageis: {age}".format(**person))

Output:durga'sageis:48

Case-8:Formattingclassmembersusingformat()

1)classPerson:
2)age=48
3) name="durga"
4)print("{[Link]}'sageis :{[Link]}".format(p=Person()))

Output:durga'sageis:48

1)classPerson:
2) definit(self,name,age):
3) [Link]=name
4) [Link]=age
5)print("{[Link]}'sageis :{[Link]}".format(p=Person('durga',48)))
6)print("{[Link]}'sageis :{[Link]}".format(p=Person('Ravi',50)))

Note:[Link] reference
variable in the template string

Case-9:DynamicFormattingusingformat()

1)string="{:{fill}{align}{width}}"
2)print([Link]('cat',fill='*',align='^',width=5))
3)print([Link]('cat',fill='*',align='^',width=6))

94 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

4)print([Link]('cat',fill='*',align='<',width=6))
5)print([Link]('cat',fill='*',align='>',width=6))

Output:
*cat*
*cat**
cat***
***cat

Case-10:DynamicFloatformat template

1)num="{:{align}{width}.{precision}f}"
2)print([Link](123.236,align='<',width=8,precision=2))
3)print([Link](123.236,align='>',width=8,precision=2))

Output:
123.24
123.24

Case-11:FormattingDatevalues

1)importdatetime
2)#datetimeformatting
3)date=[Link]()
4)print("It'snow:{:%d/%m/%Y%H:%M:%S}".format(date))

Output:It'snow:09/03/201812:36:26

Case-12:Formattingcomplexnumbers

1)complexNumber=1+2j
2)print("RealPart:{[Link]}andImaginary Part:{[Link]}".format(complexNumber))

Output:RealPart:1.0andImaginaryPart:2.0

95 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

LIS
DATASTRUCTUR
E

96 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

֍Ifwewanttorepresentagroupofindividualobjectsasasingle entitywhereinsertion order


preserved and duplicates are allowed, then we should go for List.
֍insertionorder preserved.
֍duplicateobjectsare allowed.
֍heterogeneousobjectsare allowed.
֍Listisdynamicbecausebasedonourrequirementwecanincreasethe sizeand decrease the
size.
֍InListtheelementswillbeplacedwithinsquarebracketsandwithcomma seperator.
֍Wecandifferentiateduplicateelementsbyusingindexandwecanpreserveinsertion order
by using index. Hence index will play very important role.
֍Pythonsupportsbothpositiveandnegativeindexes.+veindexmeansfromleftto right
where as negative index means right to left.
[10,"A","B",20,30, 10]

-6 -5 -4 -3 -2 -1
10 A B 20 30 10
0 1 2 3 4 5
֍List [Link].

CreationofListObjects:
1) Wecancreateemptylistobjectasfollows...

1) list=[]
2)print(list)
3)print(type(list))
4)
5)[]
6)<class'list'>

2) Ifweknowelements alreadythenwecancreatelist asfollowslist =[10,20,30,40]

3) WithDynamicInput:

1) list=eval(input("EnterList:"))
2)print(list)
3)print(type(list))

D:\Python_classes>[Link]
Enter List:[10,20,30,40]
[10,20,30,40]
<class'list'>

97 AVERIIK TECHNOLOGY
AVERIIK TECHNOLOGY

4) Withlist()Function:

1) l=list(range(0,10,2))
2)print(l)
3)print(type(l))

D:\Python_classes>[Link]
[0, 2, 4, 6, 8]
<class'list'>

Eg:

1)s="durga"
2)l=list(s)
3)print(l)

D:\Python_classes>[Link]
['d', 'u', 'r', 'g', 'a']

5) Withsplit()Function:

1) s="LearningPythonisveryveryeasy!!!"
2)l=[Link]()
3)print(l)
4)print(type(l))

D:\Python_classes>[Link]
['Learning','Python','is','very','very','easy','!!!']
<class'list'>

Note:Sometimeswecantakelistinsideanotherlist, suchtypeoflistsarecallednested lists.


[10,20, [30,40]]

AccessingElementsofList:
Wecanaccesselementsofthelisteitherbyusingindexorbyusingslice operator(:)

1)Byusing Index:
֍Listfollowszerobasedindex. ieindexoffirstelementiszero.
֍Listsupportsboth +veand-veindexes.
֍+veindexmeant forLeftto Right
֍-veindex meantforRight toLeft
֍list=[10, 20,30,40]

AVERIIK TECHNOLOGY
98
AVERIIK TECHNOLOGY

-4 -3 -2 -1
list 10 20 30 40
0 1 2 3

֍print(list[0])10
֍print(list[-1])40
֍print(list[10])IndexError:listindexoutofrange

2)ByusingSliceOperator:
Syntax:list2= list1[start:stop:step]

StartItindicatestheIndexwhereslicehastoStart Default
Value is 0

StopItindicatestheIndexwhereslicehastoEnd
DefaultValueismaxallowedIndexofListieLength oftheList

Stepincrementvalue
DefaultValueis1

1)n=[1,2,3,4,5,6,7,8,9,10]
2) print(n[2:7:2])
3)print(n[4::2])
4) print(n[3:7])
5) print(n[8:2:-2])
6) print(n[4:100])

Output D:\
Python_classes>[Link] [3,
5, 7]
[5,7,9]
[4, 5,6,7]
[9,7,5]
[5, 6,7,8,9,10]

AVERIIK TECHNOLOGY
99
AVERIIK TECHNOLOGY

ListvsMutability:
OncewecreatesaListobject, wecanmodifyitscontent. HenceList objectsare mutable.

1)n=[10,20,30,40]
2)print(n)
3)n[1]=777
4)print(n)

D:\Python_classes>[Link]
[10, 20, 30, 40]
[10,777,30,40]

TraversingtheElementsofList:
Thesequentialaccess ofeach elementinthelistiscalled traversal.

1)ByusingwhileLoop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2)i=0
3)while I<len(n):
4)print(n[i])
5) i=i+1

D:\Python_classes>[Link]
0
1
2
3
4
5
6
7
8
9
10

2)Byusingfor Loop:
1) n=[0,1,2,3,4,5,6,7,8,9,10]
2)for n1inn:
3) print(n1)

AVERIIK TECHNOLOGY
100
AVERIIK TECHNOLOGY

D:\Python_classes>[Link]
0
1
2
3
4
5
6
7
8
9
10

3)TodisplayonlyEvenNumbers:
1)n=[0,1,2,3,4,5,6,7,8,9,10]
2)for n1inn:
3)ifn1%2==0:
4) print(n1)

D:\Python_classes>[Link]
0
2
4
6
8
10

4)TodisplayElementsbyIndexwise:
1) l=["A","B","C"]
2)x=len(l)
3)for iinrange(x):
4)print(l[i],"isavailableatpositiveindex:",i,"andatnegativeindex:",i-x)

D:\Python_classes>[Link]
Aisavailableatpositiveindex:0andat negativeindex:-3
Bis availableat positiveindex:1and atnegativeindex:-2
Cisavailableat positiveindex:2and atnegativeindex:-1

AVERIIK TECHNOLOGY
101
AVERIIK TECHNOLOGY

ImportantFunctionsofList:
I. TogetInformationaboutList:
1) len():
Returnsthenumberofelementspresentinthelist
Eg:n= [10,20,30,40]
print(len(n)4

2) count():
Itreturnsthenumberofoccurrencesofspecifiediteminthelist

1) n=[1,2,2,2,2,3,3]
2)print([Link](1))
3)print([Link](2))
4)print([Link](3))
5)print([Link](4))

D:\Python_classes>[Link]
1
4
2
0

3) index():
Returnstheindexoffirstoccurrenceofthespecifieditem.

1) n =[1,2,2,2,2,3,3]
2)print([Link](1))0
3)print([Link](2))1
4)print([Link](3))5
5)print([Link](4))ValueError:4is notinlist

Note:If the specified element not present in the list then we will get [Link]
beforeindex()methodwehavetocheckwhetheritempresentinthelistornotbyusingin
operator.
print( 4in n)False

AVERIIK TECHNOLOGY
102
AVERIIK TECHNOLOGY

II. ManipulatingElementsofList:
1) append()Function:
Wecanuseappend()function toadditemat theendofthelist.

1) list=[]
2)[Link]("A")
3)[Link]("B")
4)[Link]("C")
5)print(list)

D:\Python_classes>[Link]
['A', 'B', 'C']

Eg:Toaddallelementstolistupto100whicharedivisibleby10

1)list=[]
2)for iinrange(101):
3)ifi%10==0:
5)print(list)
4) [Link](i)

D:\Python_classes>[Link]
[0, 10,20, 30, 40,50,60,70,80,90,100]

2) insert() Function:
Toinsertitematspecifiedindex position

1) n=[1,2,3,4,5]
2)[Link](1,888)
3)print(n)

D:\Python_classes>[Link]
[1, 888, 2, 3, 4, 5]

1)n=[1,2,3,4,5]
2)[Link](10,777)
3)[Link](-10,999)
4)print(n)

D:\Python_classes>[Link]
[999, 1, 2, 3, 4, 5, 777]

AVERIIK TECHNOLOGY
103
AVERIIK TECHNOLOGY

Note:Ifthespecifiedindexisgreaterthanmaxindexthenelementwillbeinsertedatlast
position. If the specified index is smaller than min index then element will be inserted at
first position.

Differencesbetweenappend()andinsert()
append() insert()
InListwhenweaddanyelementitwill InListwecaninsertanyelementin
come in last i.e. it will be last element. particular index number

3) extend()Function:
Toaddallitemsofonelistto anotherlist
[Link](l2)
allitemspresentinl2willbeaddedto l1

1) order1=["Chicken","Mutton","Fish"]
2)order2=["RC","KF","FO"]
3)[Link](order2)
4)print(order1)

D:\Python_classes>[Link]
['Chicken','Mutton','Fish','RC','KF','FO']

1)order = ["Chicken","Mutton","Fish"]
2)[Link]("Mushroom")
3)print(order)

D:\Python_classes>[Link]
['Chicken','Mutton','Fish','M','u','s','h','r','o','o','m']

4) remove() Function:
Wecanusethisfunctiontoremove [Link] multiple
times then only first occurrence will be removed.

1) n=[10,20,10,30]
2)[Link](10)
3)print(n)

D:\Python_classes>[Link]
[20, 10, 30]

Ifthespecifieditemnotpresentinlistthenwewillget ValueError

AVERIIK TECHNOLOGY
104
AVERIIK TECHNOLOGY

1)n=[10,20,10,30]
2)[Link](40)
3)print(n)

ValueError:[Link](x):xnotinlist

Note:Hencebeforeusingremove()methodfirstwehavetocheckspecifiedelement present in
the list or not by using in operator.

5) pop() Function:
 Itremovesandreturnsthelastelementofthelist.
 Thisisonlyfunctionwhichmanipulateslistandreturnssome element.

1) n=[10,20,30,40]
2)print([Link]())
3)print([Link]())
4)print(n)

D:\Python_classes>[Link]
40
30
[10,20]

Ifthelistis emptythenpop()functionraisesIndexError

1)n=[]
2)print([Link]())IndexError:popfromemptylist

Note:
1) pop()istheonlyfunctionwhichmanipulatesthelistandreturnssomevalue
2) Ingeneralwecanuseappend()andpop()functionstoimplementstack datastructure by
using list,which follows LIFO(Last In First Out) order.

Ingeneralwecanusepop()[Link] remove
elements based on index.

[Link](index)Toremoveandreturnelementpresentatspecifiedindex. [Link]()
To remove and return last element of the list

1) n=[10,20,30,40,50,60]
2)print([Link]())60
3) print([Link](1))20
4)print([Link](10))IndexError:pop indexoutofrange

AVERIIK TECHNOLOGY
105
AVERIIK TECHNOLOGY

Differencesbetweenremove()andpop()
remove() pop()
1)Wecanusetoremovespecialelement from 1)Wecanusetoremovelastelement from
the List. the List.
2) Itcan’treturnanyvalue. 2)Itreturnedremovedelement.
3)Ifspecialelementnotavailablethenwe 3) IfListisemptythenwegetError.
getVALUE ERROR.

Note:[Link] decrease the


size.

append(),insert(),extend()forincreasingthesize/growablenature
remove(), pop() for decreasing the size /shrinking nature

III) OrderingElementsofList:

1) reverse():
Wecanusetoreverse()orderofelementsof list.

1) n=[10,20,30,40]
2)[Link]()
3)print(n)

D:\Python_classes>[Link]
[40, 30, 20, 10]

2) sort():
[Link] according to
default natural sorting order thenwe should go for sort()method.

1) FornumbersDefaultNatural sortingOrderisAscending Order


2) ForStringsDefaultNaturalsortingorderisAlphabeticalOrder

1)n=[20,5,15,10,0]
2)[Link]()
3)print(n)[0,5,10,15,20]
5)s=["Dog","Banana","Cat","Apple"]
4)

7)print(s)['Apple','Banana','Cat','Dog']
6)[Link]()

AVERIIK TECHNOLOGY
106
AVERIIK TECHNOLOGY

Note:Tousesort()function,compulsorylistshouldcontainonlyhomogeneouselements.
Otherwise we will get TypeError

1)n=[20,10,"A","B"]
2)[Link]()
3)print(n)

TypeError:'<'notsupportedbetweeninstancesof'str'and'int'

Note:InPython2ifListcontainsbothnumbersandStringsthensort()functionfirstsort
numbers followed by strings

1)n=[20,"B",10,"A"]
2)[Link]()
3)print(n)# [10,20,'A','B']

Butin Python 3itisinvalid.

ToSortinReverseofDefaultNaturalSortingOrder:
Wecansortaccordingtoreverseofdefaultnaturalsortingorderbyusingreverse=True
argument.

1)n=[40,10,30,20]
2)[Link]()
3)print(n)[10,20,30,40]
4)[Link](reverse =True)
5)print(n)[40,30,20,10]
6)[Link](reverse =False)
7)print(n)[10,20,30,40]

AliasingandCloningofList Objects:
Theprocessofgivinganotherreferencevariabletotheexistinglistiscalledaliasing.

1) x=[10,20,30,40]
10 20 30 40
2) y=x print(id(x))
x
3) y
4)print(id(y))

Theprobleminthisapproachisbyusingonereferencevariableifwearechanging content, then


those changes will be reflected to the other reference variable.

1) x=[10,20,30,40] 10 20 30 40
2) y =x 777
3) y[1]= 777 x
y
AVERIIK TECHNOLOGY
107
AVERIIK TECHNOLOGY

4)print(x)[10,777,30,40]

Toovercomethisproblemweshouldgoforcloning.
Theprocessofcreatingexactlyduplicateindependentobjectiscalledcloning.

Wecanimplementcloningbyusingsliceoperator orbyusingcopy()function.

1) ByusingSlice Operator:
1) x=[10,20,30,40]
2)y =x[:]
3)y[1]= 777
4)print(x)[10, 20,30,40]
5)print(y)[10,777,30, 40]

10 20 30 40
x
10 20 30 40
777
y
2) Byusingcopy() Function:
1) x=[10,20,30,40]
2)y =[Link]()
3)y[1]= 777
4)print(x)[10, 20,30,40]
5)print(y)[10,777,30, 40]

10 20 30 40
x

10 20 30 40
777
y

Q)Differencebetween=Operatorandcopy() Function
֍=Operatormeantfor aliasing
֍copy()Functionmeantforcloning

AVERIIK TECHNOLOGY
108
AVERIIK TECHNOLOGY

UsingMathematicalOperatorsforListObjects:
Wecan use+ and* operatorsforList objects.

1) ConcatenationOperator(+):
Wecanuse+toconcatenate2 listsintoasinglelist

1) a= [10,20,30]
2)b = [40, 50,60]
3)c=a+b
4)print(c)[10,20,30,40, 50, 60]

Note:Touse+operatorcompulsorybothargumentsshouldbelistobjects, otherwisewe will


get TypeError.

Eg:
c=a+40TypeError:canonlyconcatenatelist(not"int")to list. c =
a+[40] Valid

2) RepetitionOperator(*):
Wecanuserepetitionoperator*torepeatelementsoflistspecifiednumberoftimes.

1) x =[10,20, 30]
2)y =x*3
3)print(y)[10,20, 30,10, 20, 30,10,20,30]

ComparingListObjects
WecanusecomparisonoperatorsforList objects.

1) x= ["Dog","Cat", "Rat"]
2)y=["Dog", "Cat","Rat"]
3)z =["DOG","CAT","RAT"]
4)print(x== y)True
5)print(x ==z)False
6)print(x!=z)True

Note:Wheneverweareusingcomparisonoperators (==,!=)forListobjectsthenthe following


should be considered
1) TheNumberof Elements
2) TheOrderof Elements
3) TheContentofElements(CaseSensitive)
Note:WheneverweareusingrelatationalOperators(<,<=,>,>=)betweenListObjects, only 1 ST
Element comparison will be performed.

AVERIIK TECHNOLOGY
109
AVERIIK TECHNOLOGY

1)x =[50,20, 30]


2)y=[40,50,60,100,200]
3)print(x>y)True
4)print(x>=y)True
5)print(x<y)False
6)print(x<=y)False

Eg:

1)x = ["Dog", "Cat", "Rat"]


2)y=["Rat", "Cat", "Dog"]
3)print(x>y)False
4)print(x>=y)False
5)print(x<y)True
6)print(x<=y)True

MembershipOperators:
Wecancheckwhetherelementisamemberofthelistornotbyusingmemebership operators.

1) inOperator
2) notinOperator

1)n=[10,20,30,40]
2)print(10inn)
3) print(10notinn)
4)print(50inn)
5)print(50 notinn)

Output
True
False
False
True

clear()Function:
Wecanuseclear()functiontoremoveallelementsof List.

1)n=[10,20,30,40]
2)print(n)
3)[Link]()
4)print(n)

AVERIIK TECHNOLOGY
110
AVERIIK TECHNOLOGY

Output D:\
Python_classes>[Link]
[10, 20, 30, 40]
[]

NestedLists:
[Link] lists.

1)n=[10,20,[30,40]]
2)print(n)
3)print(n[0])
4)print(n[2])
5)print(n[2][0])
6)print(n[2][1])

Output D:\
Python_classes>[Link]
[10, 20, [30, 40]]
10
[30,40]
30
40

Note:Wecanaccessnestedlistelementsbyusingindexjustlikeaccessingmulti dimensional
array elements.

NestedListasMatrix:
InPythonwecanrepresentmatrixbyusingnestedlists.

1)n=[[10,20,30],[40,50,60],[70,80,90]]
2)print(n)
3)print("Elements byRowwise:")
4)for rinn:
5) print(r)
6)print("Elements byMatrixstyle:")
7)for iinrange(len(n)):
8) for jin range(len(n[i])):
9) print(n[i][j],end='')
10) print()

AVERIIK TECHNOLOGY
111
AVERIIK TECHNOLOGY

Output
D:\Python_classes>[Link]
[[10,20,30],[40,50,60],[70,80,90]]

Elements byRowwise:
[10,20,30]
[40,50,60]
[70,80,90]

ElementsbyMatrix style:
10 20 30
40 50 60
70 80 90

ListComprehensions:
Itisveryeasyandcompactwayofcreatinglistobjectsfromanyiterableobjects (Like
List, Tuple, Dictionary, Range etc) based on some condition.

Syntax:list =[expressionforiteminlistif condition]

1)s= [x*xforxinrange(1,11)]
2)print(s)
3)v =[2**xforxinrange(1,6)]
4)print(v)
5)m=[xforxinsifx%2==0]
6)print(m)

D:\Python_classes>[Link]
[1,4,9,16,25,36, 49,64, 81, 100]
[2, 4,8,16,32]
[4,16,36,64, 100]

1)words=["Balaiah","Nag","Venkatesh","Chiranjeevi"]
2)l=[w[0]forw inwords]
3)print(l)

Output:['B','N','V','C']

1)num1=[10,20,30,40]
2)num2=[30,40,50,60]
3)num3=[iforiin num1 ifinotinnum2]
4)print(num3)[10,20]
5)
6)commonelementspresent innum1andnum2

AVERIIK TECHNOLOGY
112
AVERIIK TECHNOLOGY

7)num4=[i for iinnum1ifiin num2]


8)print(num4)[30, 40]

Eg:

1)words="thequickbrown foxjumps overthelazy dog".split()


2)print(words)
3)l=[[[Link](),len(w)] forwinwords]
4)print(l)

Output
['the','quick','brown','fox','jumps','over','the','lazy','dog']
[['THE',3],['QUICK',5],['BROWN',5],['FOX',3],['JUMPS',5],['OVER',4],
['THE',3],['LAZY',4],['DOG',3]]

Q)WriteaProgramtodisplayUniqueVowelspresentinthegiven
Word?
1)vowels=['a','e','i','o','u']
2)word=input("Entertheword tosearchfor vowels: ")
3)found=[]
4)for letter inword:
5)ifletter in vowels:
6) ifletternotinfound:
7) [Link](letter)
8)print(found)
9)print("Thenumberofdifferent vowelspresentin",word,"is",len(found))

D:\Python_classes>[Link]
Enterthewordtosearchforvowels:durgasoftwaresolutions ['u',
'a', 'o', 'e', 'i']
The number of different vowels present in durgasoftwaresolutions is 5

ListoutallFunctionsofListandwritea ProgramtousetheseFunctions

AVERIIK TECHNOLOGY
113
AVERIIK TECHNOLOGY

TUPLE
DATASTRUCTUR
E

AVERIIK TECHNOLOGY
114
AVERIIK TECHNOLOGY

1) Tupleisexactlysameas [Link] object,


we cannot perform any changes in that object.
2) HenceTupleisReadonlyversionof List.
3) Ifourdataisfixedandneverchangesthenweshouldgo for Tuple.
4) InsertionOrderispreserved
5) Duplicatesare allowed
6) Heterogeneousobjectsareallowed.
7) Wecanpreserveinsertionorderandwecandifferentiateduplicateobjectsbyusing
index. Hence index will play very important role in Tuple also.
8) Tuplesupportboth+veand -veindex.+veindexmeansforwarddirection (fromleftto right)
and -ve index means backward direction (from right to left)
9) WecanrepresentTupleelementswithinParenthesisandwithcommaseperator.
10) Parenethesisareoptionalbutrecommendedtouse.

1)t=10,20,30,40
2)print(t)
3)print(type(t))
4)
5)Output
6)(10, 20,30,40)
7)
8)<class'tuple'>
9) t=()
10)print(type(t)tuple

Note:[Link] should
ends with comma, otherwise it is not treated as tuple.

1) t=(10)
2) print(t)
3) print(type(t))
4)
5) Output
6) 10
7) <class'int'>

Eg:

1) t=(10,)
2) print(t)
3) print(type(t))
4)
5) Output
6) (10,)
7) <class'tuple'>

AVERIIK TECHNOLOGY
115
AVERIIK TECHNOLOGY

Q) WhichofthefollowingarevalidTuples?
1) t=()
2) t =10,20,30,40
3) t=10
4) t=10,
5) t=(10)
6) t=(10,)
7) t = (10,20,30,40)

TupleCreation:
1) t = ()
CreationofEmpty Tuple

2) t = (10,)
t=10,
CreationofSinglevaluedTuple,ParenthesisareOptional, shouldendswith Comma

3) t=10,20, 30
t = (10,20,30)
CreationofmultivaluesTuples&ParenthesisareOptional.

4) Byusingtuple() Function:
1)list=[10,20,30]
2) t=tuple(list)
3) print(t)
4)
5) t=tuple(range(10,20,2))
6) print(t)

AccessingElementsofTuple:
Wecan accesseitherbyindexorbysliceoperator

1) By using Index:
1) t = (10,20,30,40, 50,60)
2)print(t[0])10
3)print(t[-1])60
4)print(t[100])IndexError:tupleindex outofrange

AVERIIK TECHNOLOGY
116
AVERIIK TECHNOLOGY

2) ByusingSlice Operator:
1) t=(10,20,30,40,50,60)
2)print(t[2:5])
3)print(t[2:100])
4)print(t[::2])

Output
(30,40,50)
(30,40,50,60)
(10,30,50)

TuplevsImmutability:
 Oncewecreatestuple,wecannot changeits content.
 Hencetupleobjectsareimmutable.

Eg:
t =(10,20, 30,40)
t[1]=70TypeError:'tuple'objectdoesnotsupportitem assignment

MathematicalOperatorsforTuple:
Wecan apply+and *operatorsfor tuple

1) ConcatenationOperator (+):
1) t1=(10,20,30)
2)t2=(40,50,60)
3) t3=t1+t2
4)print(t3)(10,20,30,40,50,60)

2) MultiplicationOperatorORRepetitionOperator(*)
1) t1=(10,20,30)
2)t2=t1*3
3)print(t2)(10,20,30,10,20,30,10,20,30)

AVERIIK TECHNOLOGY
117
AVERIIK TECHNOLOGY

ImportantFunctionsofTuple:
1) len()
Toreturnnumberofelements presentinthetuple.

Eg:t=(10,20,30,40)
print(len(t))4

2) count()
Toreturnnumberofoccurrencesofgivenelementinthetuple

Eg:t = (10,20,10,10,20)
print([Link](10))3

3) index()
 Returnsindexoffirstoccurrenceofthegivenelement.
 Ifthespecifiedelementisnotavailablethenwewillget ValueError.

Eg:t = (10,20,10,10,20)
print([Link](10))0
print([Link](30))ValueError:[Link](x):xnotin tuple

4) sorted()
Tosortelementsbasedondefaultnaturalsortingorder

1)t=(40,10,30,20)
2)t1=sorted(t)
3)print(t1)
4)print(t)

Output
[10,20,30,40]
(40,10,30,20)

Wecansortaccordingtoreverseofdefaultnaturalsortingorderasfollows t1 =
sorted(t, reverse = True)
print(t1)[40,30,20,10]

AVERIIK TECHNOLOGY
118
AVERIIK TECHNOLOGY

5) min()Andmax()Functions:
Thesefunctionsreturnminandmaxvaluesaccordingtodefaultnaturalsortingorder.

1)t=(40,10,30,20)
2)print(min(t))10
3)print(max(t)) 40

6) cmp():
֍Itcomparestheelementsofboth tuples.
֍If bothtuplesareequalthen returns0
֍If thefirsttupleisless than secondtuplethenitreturns-1
֍If thefirsttupleisgreater thansecondtuplethenitreturns+1

1)t1=(10,20,30)
2)t2=(40,50,60)
3)t3=(10,20,30)
4)print(cmp(t1,t2))-1
5)print(cmp(t1,t3))0
6)print(cmp(t2,t3))+1

Note:cmp()functionisavailableonlyinPython2 but notinPython3

TuplePackingandUnpacking:
Wecan createatuplebypackingagroup of variables.

Eg:
a =10
b=20
c=30
d=40
t =a,b,c,d
print(t)(10,20,30,40)

 Herea,b, c, darepacked [Link] packing.


 TupleunpackingisthereverseprocessofTuplepacking.
 Wecan unpack aTupleandassignitsvaluestodifferent variables.

1)t=(10,20,30,40)
2)a,b,c,d=t
3)print("a=",a,"b=",b,"c=",c,"d=",d)

Output:a= 10 b= 20c=30 d=40

AVERIIK TECHNOLOGY
119
AVERIIK TECHNOLOGY

Note:Atthetimeoftupleunpackingthenumberofvariablesandnumberofvalues should be
same, otherwise we will get ValueError.

Eg:
t=(10,20,30,40)
a,b,c=tValueError:toomanyvaluestounpack(expected 3)

TupleComprehension:
 TupleComprehensionisnotsupportedbyPython.
 t = (x**2forx in range(1,6))
 Herewearenot gettingtupleobject andwearegettinggenerator object.

1)t=(x**2forxinrange(1,6))
2)print(type(t))
3)forxin t:
4)print(x)

D:\Python_classes>[Link]
<class'generator'>
1
4
9
16
25

Q)WriteaProgramtotakeaTuple ofNumbersfromtheKeyboardand
Print its Sum and Average?
1)t=eval(input("Enter Tupleof Numbers:"))
2)l=len(t)
3)sum=0
4)forxin t:
5) sum=sum+x
6)print("The Sum=",sum)
7)print("The Average=",sum/l)

D:\Python_classes>[Link]
EnterTupleofNumbers:(10,20,30,40)
The Sum= 100
TheAverage=25.0

D:\Python_classes>[Link]
EnterTupleofNumbers:(100,200,300)

AVERIIK TECHNOLOGY
120
AVERIIK TECHNOLOGY

TheSum=600
TheAverage=200.0

DifferencesbetweenListandTuple:
 ListandTupleareexactlysame exceptsmalldifference:Listobjectsaremutablewhere as
Tuple objects are immutable.
 Inbothcasesinsertionorderispreserved, duplicateobjectsareallowed,heterogenous
objects are allowed, index and slicing are supported.

Lis Tupl
t e
1)ListisaGroupofCommasepareated Values 1)TupleisaGroupofCommasepareated Values
within Square Brackets and Square within Parenthesis and Parenthesis are
Brackets are mandatory. optional.
Eg: i= [10,20, 30,40] Eg:t= (10, 20,30,40)
t=10,20,30, 40
2)List Objects are Mutable i.e. once we 2)[Link] we
createsListObjectwecanperformany creates Tuple Object we cannot change
changes in that Object. its content.
Eg: i[1]=70 t[1]=70ValueError:tupleobject
doesnotsupportitem assignment.
3)IftheContentisnotfixedandkeepon 3)Ifthecontentisfixedandneverchanges then
changing then we should go for List. we should go for Tuple.
4)ListObjectscannotusedasKeysfor 4)TupleObjectscanbeusedasKeysfor
Dictionries because Keys should be Dictionries because Keys should be
Hashable and Immutable. Hashable and Immutable.

AVERIIK TECHNOLOGY
121
AVERIIK TECHNOLOGY

SE
DATASTRUCTUR
E

AVERIIK TECHNOLOGY
122
AVERIIK TECHNOLOGY

 Ifwewanttorepresentagroupofunique valuesasasingleentitythenweshouldgo for set.


 Duplicatesarenot allowed.
 [Link].
 Indexingandslicingnotallowedfortheset.
 Heterogeneouselementsareallowed.
 Setobjectsaremutablei.e oncewecreatessetobjectwecanperformanychangesin that
object based on our requirement.
 Wecanrepresentsetelementswithincurlybracesandwithcommaseperation
 Wecanapplymathematicaloperationslikeunion, intersection,differenceetconset
objects.

CreationofSetObjects:
1)s={10,20,30,40}
2)print(s)
3)print(type(s))

Output
{40,10,20,30}
<class'set'>

Wecan createsetobjectsbyusingset()Functions=set(any sequence)

Eg1:

1)l=[10,20,30,40,10,20,10]
2)s=set(l)
3)print(s)#{40,10,20, 30}

Eg2:

1)s=set(range(5))
2)print(s) #{0,1,2,3,4}

Note:
֍Whilecreatingemptyset wehaveto takespecial care.
֍Compulsoryweshoulduseset()function.
֍s = {}Itistreated asdictionarybutnotemptyset.

1)s={}
2)print(s)
3)print(type(s))

AVERIIK TECHNOLOGY
123
AVERIIK TECHNOLOGY

Output
{}
<class'dict'>

Eg:

1)s=set()
2)print(s)
3)print(type(s))

Output
set()
<class'set'>

ImportantFunctionsofSet:
1) add(x):
Addsitemxto theset.

1) s={10,20,30}
2)[Link](40);
3)print(s)#{40,10,20, 30}

2) update(x,y,z):
1) Toaddmultipleitemstotheset.
2) ArgumentsarenotindividualelementsandtheseareIterableobjectslikeList, Range etc.
3) AllelementspresentinthegivenIterableobjectswillbeaddedtotheset.

1)s={10,20,30}
2)l=[40,50,60,10]
3)[Link](l,range(5))
4)print(s)

Output:{0,1,2,3,4, 40,10, 50,20,60,30}

Q)Whatisthedifferencebetweenadd()andupdate()Functions
in Set?
4) Wecanuseadd()toaddindividualitemtotheSet,whereaswecanuseupdate()
function to add multiple items to Set.
5) add()functioncantakeonlyoneargumentwhereasupdate()functioncantakeany
number of arguments but all arguments should be iterable objects.

AVERIIK TECHNOLOGY
124
AVERIIK TECHNOLOGY

Q) Whichofthefollowingarevalidforsets?
1) [Link](10)
2) [Link](10,20,30)TypeError:add()takesexactlyoneargument(3given)
3) [Link](10)TypeError:'int'objectisnot iterable
4) [Link](range(1,10,2),range(0,10,2))

3) copy():
1) Returnscopyoftheset.
2) Itiscloned object.

1)s={10,20,30}
2)s1=[Link]()
3)print(s1)

4) pop():
Itremovesandreturnssomerandomelementfromtheset.

1)s={40,10,30,20}
2)print(s)
3)print([Link]())
4)print(s)

Output
{40,10,20,30}
40
{10,20, 30}

5) remove(x):
1) Itremovesspecifiedelementfromtheset.
2) IfthespecifiedelementnotpresentintheSetthenwewillget KeyError.

1)s ={40, 10, 30,20}


2)[Link](30)
3)print{(s)40,10, 20}
4)[Link](50 KeyError:)50

6) discard(x):
1) Itremovesthespecifiedelementfromtheset.
2) Ifthespecifiedelementnotpresentintheset thenwewon'tget any error.

1)s = {10,20, 30}


2)[Link](10)

AVERIIK TECHNOLOGY
125
AVERIIK TECHNOLOGY

3) print {(s)20,30}
4)[Link](50)
5)print{(s)20,30}

Q)Whatisthedifference betweenremove()anddiscard()functionsinSet?
Q)Explaindifferencesbetweenpop(),remove()anddiscard()functionsinSet?

7) clear():
ToremoveallelementsfromtheSet.

1)s={10,20,30}
2)print(s)
3)[Link]()
4)print(s)

Output
{10,20, 30}
set()

MathematicalOperationsontheSet:
1) union():
 [Link](y)Wecan usethisfunctiontoreturnall elementspresentinbothsets
 [Link](y)ORx|y.

1)x ={10,20,30,40}
2)y ={30,40,50,60}
3)print([Link](y)){10, 20,30, 40,50,60}
4)print(x|y){10,20,30, 40,50, 60}

2) intersection():
 [Link](y)ORx&y.
 Returnscommonelementspresentinbothxandy.

1)x= {10,20, 30,40}


2)y={30,40,50,60}
3)print ([Link](y)){40,30}
4)print(x&y){40,30}

AVERIIK TECHNOLOGY
126
AVERIIK TECHNOLOGY

3) difference():
 [Link](y)ORx-y.
 Returnstheelementspresent inxbutnotin y.

1)x ={10,20,30,40}
2)y ={30,40,50,60}
3)print([Link](y))10,20
4)print(x-y){10,20}
5)print(y-x){50,60}

4) symmetric_difference():
 x.symmetric_difference(y)ORx^y.
 Returnselementspresentin eitherxORybutnotin both.

1)x ={10,20,30,40}
2)y ={30,40,50,60}
3)print (x.symmetric_difference(y)){10,50,20, 60}
4)print(x^y){10, 50,20,60}

MembershipOperators:(in,notin)
1)s=set("durga")
2)print(s)
3)print('d'ins)
4)print('z'ins)

Output
{'u','g','r','d','a'}
True
False

SetComprehension:
Setcomprehensionispossible.

1)s={x*xforxinrange(5)}
2)print(s){0,1,4,9,16}
3)
4)s={2**xforxinrange(2,10,2)}
5)print(s){16,256,64,4}

AVERIIK TECHNOLOGY
127
AVERIIK TECHNOLOGY

SetObjectswon'tsupportindexingandslicing:
1)s={10,20,30,40}
2)print(s[0])TypeError:'set'objectdoesnotsupport indexing
3)print(s[1:3])TypeError:'set'objectisnotsubscriptable

Q)WriteaProgramtoeliminateDuplicatesPresentintheList?
Approach-1 Approach-2

1) l=eval(input("EnterListofvalues:")) 1) l=eval(input("EnterListofvalues:"))
2) s=set(l) 2) l1=[]
3) print(s) 3) forxin l:
4) ifxnot in l1:
D:\Python_classes>[Link] 5) [Link](x)
EnterListofvalues: [10,20,30,10,20,40] 6) print(l1)
{40,10,20,30}
D:\Python_classes>py [Link]
EnterListofvalues:[10,20,30,10,20,40] [10,
20, 30, 40]

Q)WriteaProgramtoPrintdifferentVowelsPresentinthegiven
Word?
1)w=input("Enterwordtosearchfor vowels:")
2)s=set(w)
3)v={'a','e','i','o','u'}
4)d=[Link](v)
5)print("Thedifferent vowel presentin",w,"are",d)

D:\Python_classes>[Link]
Enterwordtosearchforvowels:durga
Thedifferentvowelpresentindurgaare{'u','a'}

AVERIIK TECHNOLOGY
128
AVERIIK TECHNOLOGY

DICTIONAR
Y
DATA
STRUCTURE

AVERIIK TECHNOLOGY
129
AVERIIK TECHNOLOGY

֍WecanuseList,TupleandSettorepresentagroup ofindividualobjectsasasingle entity.


֍Ifwewanttorepresent agroupofobjectsaskey-valuepairsthenweshouldgofor Dictionary.

Eg:
 rollno-----name
 phonenumber--address
 ipaddress----domainname

֍Duplicatekeysarenotallowedbut valuescanbeduplicated.
֍Hetrogeneousobjectsareallowedfor bothkeyand values.
֍Insertionorderisnot preserved
֍Dictionariesaremutable
֍Dictionariesaredynamic
֍indexingandslicingconceptsarenotapplicable

Note:InC++andJavaDictionariesareknownas"Map"whereasinPerlandRubyitis known as
"Hash"

HowtoCreateDictionary?
 d={} OR d=dict()
 [Link]

1)d[100]="durga"
2)d[200]="ravi"
3)d[300]="shiva"
4)print(d){100:'durga',200: 'ravi',300:'shiva'}

 Ifweknow datainadvancethenwecancreatedictionaryasfollows

 d={100:'durga',200:'ravi', 300:'shiva'}
 d={key:value,key:value}

Howto AccessDatafromtheDictionary?
Wecan access databyusingkeys.

1)d={100:'durga',200:'ravi', 300:'shiva'}
2)print(d[100])#durga
3)print(d[300]) #shiva

Ifthespecifiedkeyisnot availablethenwewillget KeyError

AVERIIK TECHNOLOGY
130
AVERIIK TECHNOLOGY

print(d[400])KeyError:400

Wecanpreventthisbycheckingwhetherkeyisalreadyavailableornotbyusing
has_key() function or by using in operator.

d.has_key(400)Returns1ifkeyisavailableotherwisereturns0

Buthas_key()functionisavailableonlyin [Link] compulsory we


have to use in operator.

if400 in d:
print(d[400])

Q) WriteaProgramtoEnterNameandPercentageMarksin a
Dictionary and Display Information on the Screen
1) rec={}
2)n=int(input("Enternumber ofstudents: "))
3)i=1
4)while i<=n:
5) name=input("EnterStudentName:")
6)marks=input("Enter%of MarksofStudent:")
7) rec[name]=marks
8)i=i+1
9)print("Nameof Student","\t","%of marks")
10)for xinrec:
11) print("\t",x,"\t\t",rec[x])

D:\Python_classes>[Link]
Enter number of students: 3
Enter Student Name: durga
Enter%ofMarksofStudent:60% Enter
Student Name: ravi
Enter%ofMarksofStudent:70% Enter
Student Name: shiva
Enter %ofMarks of Student:80%

Name of Student % of marks


--------------- ------------
durga 60%
ravi 70 %
shiva 80%

AVERIIK TECHNOLOGY
131
AVERIIK TECHNOLOGY

HowtoUpdateDictionaries?
֍d[key]= value
֍Ifthekeyisnotavailablethenanewentrywillbeaddedtothedictionarywiththe specified key-
value pair
֍Ifthekeyisalreadyavailablethenoldvaluewillbereplacedwithnew value.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print(d)
3)d[400]="pavan"
4)print(d)
5)d[100]="sunny"
6)print(d)

Output
{100:'durga',200:'ravi',300:'shiva'}
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}
{100:'sunny',200:'ravi',300:'shiva',400:'pavan'}

HowtoDeleteElementsfromDictionary?
1) deld[key]
 Itdeletesentryassociatedwiththespecifiedkey.
 Ifthekeyisnotavailablethenwewillget KeyError.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print(d)
3)deld[100]
4)print(d)
5)deld[400]

Output
{100:'durga',200:'ravi',300:'shiva'}
{200:'ravi',300:'shiva'}
KeyError:400

2) [Link]()
Toremoveallentriesfromthedictionary.

1) d={100:"durga",200:"ravi",300:"shiva"}
2)print(d)
3)[Link]()
4)print(d)

AVERIIK TECHNOLOGY
132
AVERIIK TECHNOLOGY

Output
{100:'durga',200:'ravi',300:'shiva'}
{}

3) deld
[Link].

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print(d)
3)deld
4)print(d)

Output
{100:'durga',200:'ravi',300:'shiva'}
NameError: name 'd'is not defined

ImportantFunctionsofDictionary:
1) dict():
Tocreatea dictionary

 d=dict()Itcreatesemptydictionary
 d=dict({100:"durga",200:"ravi"})Itcreatesdictionarywith specifiedelements
 d= dict([(100,"durga"),(200,"shiva"),(300,"ravi")])
Itcreatesdictionarywiththegivenlistoftuple elements

2) len()
Returnsthenumberof itemsinthe dictionary.

3) clear():
Toremoveallelementsfromthedictionary.

4) get():
Toget thevalueassociatedwith thekey

[Link](key)
[Link] wont
raise any error.

AVERIIK TECHNOLOGY
133
AVERIIK TECHNOLOGY

[Link](key,defaultvalue)
Ifthekeyisavailablethenreturnsthecorrespondingvalueotherwisereturnsdefault value.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print(d[100]) durga
3)print(d[400]) KeyError:400
4)print([Link](100))durga
5)print([Link](400))None
6)print([Link](100,"Guest"))durga
7)print([Link](400,"Guest"))Guest

5) pop():
[Link](key)
 Itremovestheentryassociatedwiththespecifiedkeyandreturnsthe
corresponding value.
 Ifthespecifiedkeyisnotavailablethenwewillget KeyError.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print([Link](100))
3)print(d)
4)print([Link](400))

Output
durga
{200:'ravi',300:'shiva'}
KeyError:400

6) popitem():
Itremovesanarbitraryitem(key-value)fromthedictionatyandreturnsit.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print(d)
3)print([Link]())
4)print(d)

Output
{100:'durga',200:'ravi',300:'shiva'}
(300,'shiva')
{100:'durga',200:'ravi'}
IfthedictionaryisemptythenwewillgetKeyError d={}
print([Link]())==>KeyError:'popitem():dictionaryisempty'

AVERIIK TECHNOLOGY
134
AVERIIK TECHNOLOGY

7) keys():
Itreturnsallkeysassociatedeith dictionary.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print([Link]())
3)forkin [Link]():
4)print(k)

Output
dict_keys([100,200, 300])
100
200
300

8) values():
Itreturnsallvaluesassociatedwiththe dictionary.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print([Link]())
3)[Link]():
4)print(v)

Output
dict_values(['durga','ravi','shiva'])
durga
ravi
shiva

9) items():
Itreturnslistoftuplesrepresentingkey-valuepairs. [(k,v),
(k,v),(k,v)]

1)d={100:"durga",200:"ravi",300:"shiva"}
2)fork,[Link]():
3) print(k,"--",v)

Output
100--durga
200--ravi
300--shiva

AVERIIK TECHNOLOGY
135
AVERIIK TECHNOLOGY

10) copy():
Tocreateexactlyduplicatedictionary(clonedcopy) d1 =
[Link]();

11) setdefault():
[Link](k,v)
 Ifthekeyisalreadyavailablethenthisfunctionreturnsthecorrespondingvalue.
 Ifthekeyisnotavailablethenthespecifiedkey-valuewillbeaddedasnewitemto the
dictionary.

1)d={100:"durga",200:"ravi",300:"shiva"}
2)print([Link](400,"pavan"))
3)print(d)
4)print([Link](100,"sachin"))
5)print(d)

Output
pavan
{100:'durga',200:'ravi',300:'shiva',400:'pavan'} durga
{100:'durga',200:'ravi',300:'shiva',400:'pavan'}

12) update():
[Link](x)
Allitemspresentinthedictionaryxwillbeaddedtodictionaryd

Q) WriteaProgramtotakeDictionaryfromtheKeyboardand
print the Sum of Values?
1) d=eval(input("Enterdictionary:"))
2)s=sum([Link]())
3)print("Sum= ",s)

Output
D:\Python_classes>[Link]
Enterdictionary:{'A':100,'B':200,'C':300}
Sum=600

AVERIIK TECHNOLOGY
136
AVERIIK TECHNOLOGY

Q) Write
aProgramtofindNumberofOccurrencesofeachLetterpresent in
the given String?
1) word=input("Enteranyword:")
2)d={}
3)forxinword:
4) d[x]=[Link](x,0)+1
5)fork,v [Link]():
6) print(k,"occurred",v,"times")

Output D:\
Python_classes>[Link]
Enter any word: mississippim
occurred1times
i occurred 4 timess
occurred 4
timespoccurred2ti
mes

Q)WriteaProgramtofindNumberofOccurrencesofeachVowelpresent
in the given String?
1)word=input("Enteranyword: ")
2)vowels={'a','e','i','o','u'}
3)d={}
4)forxinword:
5) ifxinvowels:
6) d[x]=[Link](x,0)+1
7)fork,vinsorted([Link]()):
8) print(k,"occurred",v,"times")

Output
D:\Python_classes>[Link]
Enteranyword:doganimaldoganimal a
occurred4times
i occurred2times
ooccurred2times

AVERIIK TECHNOLOGY
137
AVERIIK TECHNOLOGY

Q) Write a Program to accept Student Name and Marks from


[Link]
by taking Student Name as Input?

1)n=int(input("Enterthenumberofstudents:"))
2)d={}
3)for iinrange(n):

4)name=input("EnterStudentName:")
5)marks=input("EnterStudentMarks:")

7)whileTrue:
6)d[name]=marks
9)marks=[Link](name,-1)
8)name=input("EnterStudentNametogetMarks:")

10)ifmarks==-1:
11) print("StudentNotFound")
12)else:
13) print("TheMarksof",name,"are",marks)
14)option=input("Doyouwanttofind anotherstudent marks[Yes|No]")
15)ifoption=="No":
16) break
17)print("Thanksforusingourapplication")

Output D:\Python_classes>py
[Link]
Enterthenumberofstudents:5

EnterStudentName:sunny
Enter Student Marks: 90

EnterStudentName:banny
Enter Student Marks: 80

EnterStudentName:chinny
Enter Student Marks: 70

EnterStudentName:pinny
Enter Student Marks: 60

EnterStudentName:vinny
Enter Student Marks: 50

EnterStudentNametogetMarks:sunny The
Marks of sunny are 90

AVERIIK TECHNOLOGY
138
AVERIIK TECHNOLOGY

Doyouwanttofindanotherstudentmarks[Yes|No]Yes

Enter Student Name to get Marks: durga


StudentNotFound

Doyouwanttofindanotherstudentmarks[Yes|No]No Thanks
for using our application

Dictionary Comprehension:
Comprehensionconceptapplicablefordictionariesalso.

1)squares={x:x*xforxinrange(1,6)}
2)print(squares)
3)doubles={x:2*xforxinrange(1,6)}
4)print(doubles)

Output
{1: 1,2:4,3:9,4:16, 5:25}
{1: 2,2:4,3:6,4:8,5:10}

AVERIIK TECHNOLOGY
139
AVERIIK TECHNOLOGY

FUNCTION
S

AVERIIK TECHNOLOGY
140
AVERIIK TECHNOLOGY

֍If a group of statements is repeatedly required then it is not recommended to write


[Link] unit
and we can call that unit any number of times based on our requirement without
rewriting. This unit is nothing but function.

֍Themainadvantageoffunctionsiscode Reusability.
֍Note:Inotherlanguagesfunctionsareknownasmethods,procedures,subroutinesetc

֍Pythonsupports2typesoffunctions
1) BuiltinFunctions
2) UserDefinedFunctions

1)Builtin Functions:
Thefunctionswhicharecomingalongwith Pythonsoftwareautomatically, arecalled built
in functions or pre defined functions.
Eg:id()
type()
input()
eval()
etc..

2)UserDefined Functions:
Thefunctionswhicharedevelopedbyprogrammerexplicitlyaccordingtobusiness
requirements, are called user defined functions.

SyntaxtoCreateUserdefinedFunctions:
def function_name(parameters):
""" doc string"""
----
-----
returnvalue

Note:Whilecreatingfunctionswecanuse2 keywords
1) def (mandatory)
2) return(optional)

Eg1:WriteafunctiontoprintHello

[Link]
1)defwish():
2)print("HelloGoodMorning")
3)wish()

AVERIIK TECHNOLOGY
141
AVERIIK TECHNOLOGY

4)wish()
5)wish()

Parameters
[Link], thenatthetime of
calling,compulsory we should provide values otherwise,otherwise we will geterror.
Eg:Writeafunctiontotakenameofthestudentasinputandprintwishmessageby name.

1)defwish(name):
3)wish("Durga")
2) print("Hello",name,"GoodMorning")

4)wish("Ravi")

D:\Python_classes>[Link]
Hello DurgaGood Morning
Hello RaviGood Morning

Eg:Writeafunctiontotakenumberasinputandprintitssquarevalue

1)defsquareIt(number):
2)print("TheSquareof",number,"is",number*number)
3)squareIt(4)
4)squareIt(5)

D:\Python_classes>[Link]
The Square of 4 is 16
TheSquareof5is25

ReturnStatement:
Functioncantakeinputvaluesasparametersandexecutesbusinesslogic, andreturns output
to the caller with return statement.

Q)WriteaFunctiontoaccept2NumbersasInputandretur
n Sum
1)defadd(x,y):
2)returnx+y
3)result=add(10,20)
4)print("Thesumis",result)
5)print("Thesumis",add(100,200))

AVERIIK TECHNOLOGY
142
AVERIIK TECHNOLOGY

D:\Python_classes>[Link]
The sum is 30
The sumis300

IfwearenotwritingreturnstatementthendefaultreturnvalueisNone.

1)deff1():
2)print("Hello")
3)f1()
4)print(f1())

Output
Hello
Hello
None

Q)WriteaFunctiontocheckwhetherthegivenNumberisEven
OR Odd?
1)defeven_odd(num):
2)ifnum%2==0:
3) print(num,"isEvenNumber")
4)else:
5) print(num,"isOddNumber")
6)even_odd(10)
7)even_odd(15)

Output D:\
Python_classes>[Link] 10
is Even Number
15is Odd Number

Q) WriteaFunctiontofindFactorialofgivenNumber?
1)deffact(num):
2) result=1
3) whilenum>=1:
4) result=result*num
5) num=num-1
6) returnresult
7)for iinrange(1,5):
8) print("TheFactorialof",i,"is:",fact(i))

AVERIIK TECHNOLOGY
143
AVERIIK TECHNOLOGY

Output D:\
Python_classes>[Link]
The Factorial of 1 is : 1
The Factorial of 2 is : 2
The Factorial of 3 is : 6
TheFactorialof4is:24

ReturningMultipleValuesfromaFunction:
InotherlanguageslikeC,C++andJava,[Link] Python, a
function can return any number of values.

Eg1:

1)defsum_sub(a,b):
2)sum=a+b
3) sub=a-b
4)returnsum,sub
5)x,y=sum_sub(100,50)
6)print("TheSum is :",x)
7)print("TheSubtractionis:",y)

Output
TheSumis:150
TheSubtractionis:50

Eg2:

1) defcalc(a,b):
2) sum=a+b
3) sub=a-b
4) mul=a*b
5) div=a/b
6) returnsum,sub,mul,div
7)t=calc(100,50)
8)print("TheResultsare")
9)for iint:
10) print(i)

Output
TheResultsare
150
50
5000
2.0

AVERIIK TECHNOLOGY
144
AVERIIK TECHNOLOGY

TypesofArguments
deff1(a,b):
------
------
------
f1(10,20)

a,bareformalargumentswhereas10,20areactualarguments. There

are 4 types are actual arguments are allowed in Python.


1) Positional Arguments
2) KeywordArguments
3) DefaultArguments
4) VariableLengthArguments

1)PositionalArguments:
 Thesearetheargumentspassedtofunctionincorrectpositionalorder. def
sub(a, b):
print(a-b)

sub(100, 200)
sub(200, 100)

 Thenumberofargumentsandpositionofarguments [Link] the


order then result may be changed.
 Ifwechangethenumber ofargumentsthenwewill geterror.

2)KeywordArguments:
[Link].

1)defwish(name,msg):
2)print("Hello",name,msg)
3)wish(name="Durga",msg="GoodMorning")
4)wish(msg="GoodMorning",name="Durga")

Output
HelloDurgaGoodMorning
Hello DurgaGood Morning
Heretheorderofargumentsisnotimportantbutnumberofargumentsmustbematched.

AVERIIK TECHNOLOGY
145
AVERIIK TECHNOLOGY

Note:[Link] have to
take positional arguments and then keyword arguments,otherwise we will get
syntaxerror.

1)defwish(name,msg):
2)print("Hello",name,msg)
3)wish("Durga","GoodMorning")Valid
4)wish("Durga",msg="GoodMorning")Valid
5) wish(name="Durga","GoodMorning")Invalid
6) SyntaxError:positionalargumentfollowskeywordargument

3)DefaultArguments:
Sometimeswecanprovidedefaultvaluesforourpositionalarguments.

1) defwish(name="Guest"):
2) print("Hello",name,"GoodMorning")
3)wish("Durga")
4)wish()

Output
HelloDurgaGoodMorning
HelloGuestGoodMorning
Ifwearenotpassinganynamethenonlydefaultvaluewillbeconsidered.

***Note:
Afterdefaultargumentsweshouldnottakenondefaultarguments.

1)defwish(name="Guest",msg="GoodMorning"):Valid
2)defwish(name,msg="GoodMorning"):Valid
3)defwish(name="Guest",msg):Invalid

SyntaxError:non-defaultargumentfollowsdefaultargument

4)VariableLengthArguments:
 Sometimeswecanpassvariablenumberofargumentstoourfunction, suchtypeof
arguments are called variable length arguments.
 Wecandeclareavariablelength argumentwith* symbolasfollows
 def f1(*n):
 Wecancallthisfunctionbypassinganynumberofargumentsincludingzeronumber.
 Internallyallthesevaluesrepresentedintheformoftuple.

AVERIIK TECHNOLOGY
146
AVERIIK TECHNOLOGY

1)defsum(*n):
2) total=0
3) forn1inn:
4) total=total+n1
5) print("TheSum=",total)
6)
7)sum()
8)sum(10)
9)sum(10,20)
10)sum(10,20,30,40)

Output
TheSum=0
TheSum=10
TheSum=30
TheSum=100

Note:Wecanmixvariablelengthargumentswithpositionalarguments.

1)deff1(n1,*s):
2) print(n1)
3) for s1in s:
4) print(s1)
5)
6)f1(10)
7)f1(10,20,30,40)
8)f1(10,"A",30,"B")

Output
10
10
20
30
40
10
A 30
B

Note:Aftervariablelengthargument,ifwearetakinganyotherargumentsthenwe should provide


values as keyword arguments.

AVERIIK TECHNOLOGY
147
AVERIIK TECHNOLOGY

1)deff1(*s,n1):
2) for s1in s:
3) print(s1)
4) print(n1)
5)
6)f1("A","B",n1=10)

Output
A
B
10
f1("A","B",10)Invalid
TypeError:f1()missing1requiredkeyword-onlyargument: 'n1'

Note:Wecandeclarekeywordvariablelengtharguments also.

 Forthiswehavetouse**.
 deff1(**n):
 Wecancallthisfunctionbypassinganynumberofkeywordarguments. Internally
these keyword arguments will be stored inside a dictionary.

1)defdisplay(**kwargs):
2)for k,vin [Link]():
3) print(k,"=",v)
4)display(n1=10,n2=20,n3=30)
5)display(rno=100,name="Durga",marks=70,subject="Java")

Output
n1=10
n2=20
n3=30
rno = 100
name=Durga
marks = 70
subject=Java

AVERIIK TECHNOLOGY
148
AVERIIK TECHNOLOGY

Case Study:
def f(arg1,arg2,arg3=4,arg4=8):
print(arg1,arg2,arg3,arg4)

1) f(3,2)3248

2) f(10,20,30,40)10203040

3) f(25,50,arg4=100)25504100

4) f(arg4=2,arg1=3,arg2=4)3442

5) f() Invalid
TypeError:f()missing2requiredpositionalarguments:'arg1'and'arg2'

6) f(arg3=10,arg4=20, 30,40)Invalid
SyntaxError:positionalargumentfollowskeywordargument
[Afterkeywordargumentsweshouldnottakepositional arguments]

7) f(4, 5, arg2= 6)Invalid


TypeError:f()gotmultiplevaluesforargument'arg2'

8) f(4, 5, arg3= 5, arg5=6)Invalid


TypeError:f()gotanunexpectedkeywordargument'arg5'

Note:Function vsModulevsLibrary
1) Agroup oflineswithsomenameiscalled afunction
2) Agroupoffunctionssavedtoafile,iscalled Module
3) AgroupofModulesisnothingbutLibrary

Library Function
-----------------
Module 1 Module2
-----------------
-----------------
Function1 Function1
-----------------
-----------------
Function2 Function2 -----------------
-----------------
Function3 Function3 -----------------
-----------------

AVERIIK TECHNOLOGY
149
AVERIIK TECHNOLOGY

TypesofVariables
Python supports2typesof variables.

1) Global Variables
2) Local Variables

1) Global Variables
 Thevariableswhicharedeclaredoutsideoffunctionarecalledglobalvariables.
 Thesevariablescanbeaccessedinallfunctionsofthatmodule.

1)a=10#globalvariable
2)deff1():
3)print(a)
5)deff2():
4)

7)
6)print(a)
9)f2()
8)f1()

Output
10
10

2) LocalVariables:
 Thevariableswhicharedeclaredinsideafunctionarecalledlocalvariables.
 Localvariablesareavailableonlyforthe [Link]
outside of function we cannot access.

1)deff1():
2)a=10
3)print(a)#valid

5)deff2():
4)
7)
9)f2()
6)print(a)#invalid

8)f1()

NameError:name'a'isnot defined

AVERIIK TECHNOLOGY
150
AVERIIK TECHNOLOGY

globalKeyword:
Wecanuseglobalkeywordforthefollowing2 purposes:
1) Todeclareglobalvariableinsidefunction
2) Tomakeglobalvariableavailabletothefunctionsothatwecanperformrequired
modifications

1)a=10
2)deff1():
3)a=777
4)print(a)
5)
6)deff2():
7)print(a)
8)
9)f1()
11)
10)f2()

Output
777
10

1)a=10
2)deff1():
3) globala
4)a=777
5) print(a)
6) deff2():
7)print(a)
8)
9)f1()
10)f2()

Output
777
777

1)deff1():
2)a=10
3)print(a)

5)deff2():
4)

7)
6)print(a)

AVERIIK TECHNOLOGY
151
AVERIIK TECHNOLOGY

8)f1()
9)f2()

Output:NameError:name'a'isnotdefined

1)deff1():
2) globala
3) a=10
4) print(a)
5)
6)deff2():
7) print(a)
8)
9)f1()
10)f2()

Output
10
10

Note:Ifglobalvariableandlocalvariablehavingthesamenamethenwecanaccess global
variable inside a function as follows

1)a=10GlobalVariable
2)deff1():
3) a=777LocalVariable
4) print(a)
5) print(globals()['a'])
6)f1()

Output
777
10

RecursiveFunctions
AfunctionthatcallsitselfisknownasRecursiveFunction.

Eg:
factorial(3)= 3*factorial(2)
=3*2*factorial(1)
=3*2*1*factorial(0)
=3*2*1*1
=6
factorial(n)=n*factorial(n-1)

AVERIIK TECHNOLOGY
152
AVERIIK TECHNOLOGY

Themainadvantagesofrecursivefunctions are:
1) Wecanreducelengthofthecodeandimproves readability.
2) Wecansolvecomplexproblemsvery easily.

Q) WriteaPythonFunctiontofindFactorialofgivenNu
mber with Recursion
1) deffactorial(n):
2) ifn==0:
3) result=1
4) else:
5) result=n*factorial(n-1)
6) returnresult
7)print("Factorial of4is:",factorial(4))
8)print("Factorial of5is:",factorial(5))

Output
Factorialof4is:24
Factorialof5is:120

AnonymousFunctions:
 Sometimeswecandeclareafunctionwithoutanyname,suchtypeofnameless
functions are called anonymous functions or lambda functions.
 Themainpurposeofanonymousfunctionisjustforinstantuse([Link] usage)

NormalFunction:
Wecandefinebyusingdef keyword.
defsquareIt(n):r
eturn n*n

LambdaFunction:
Wecandefinebyusinglambda keyword lambdan:n*n

SyntaxoflambdaFunction:lambdaargument_list:expression

Note:ByusingLambdaFunctionswecanwriteveryconcise codesothatreadabilityof the


program will be improved.

AVERIIK TECHNOLOGY
153
AVERIIK TECHNOLOGY

Q)WriteaProgramtocreateaLambdaFunctiontofindSquareofgiven
Number?
1)s=lambdan:n*n
2)print("TheSquareof4 is:",s(4))
3)print("TheSquareof5 is:",s(5))

Output
TheSquareof4is:16
TheSquareof5is: 25

Q)LambdaFunctiontofindSumof2givenNumbers
1)s=lambdaa,b:a+b
2)print("TheSum of10,20is:",s(10,20))
3)print("TheSum of100,200 is:",s(100,200))

Output
TheSumof 10,20is: 30
TheSumof100,200is:300

Q) LambdaFunctiontofindbiggestofgiven Values
1) s=lambdaa,b:aifa>belseb
2)print("TheBiggestof10,20 is:",s(10,20))
3)print("TheBiggestof100,200 is:",s(100,200))

Output
TheBiggest of10,20is:20
TheBiggest of100,200is: 200

Note:LambdaFunctioninternallyreturnsexpressionvalueandwearenotrequiredto write
return statement explicitly.

Note:[Link] lambda
functions are best choice.

Wecanuselambdafunctionsverycommonlywithfilter(), map()andreduce()functions,
because these functions expect function as argument.

AVERIIK TECHNOLOGY
154
AVERIIK TECHNOLOGY

filter() Function:
Wecanusefilter()functiontofiltervaluesfromthegivensequencebasedonsome condition.

filter(function,sequence)
WhereFunctionArgumentisresponsibletoperformconditionalcheck Sequencecanbe List OR
Tuple OR String.

Q)ProgramtofilteronlyEvenNumbersfromtheListbyusingfilter()
Function?

WithoutLambdaFunction:
1)defisEven(x):
2) ifx%2==0:
3) returnTrue
4) else:
5) returnFalse
6)l=[0,5,10,15,20,25,30]
7)l1=list(filter(isEven,l))
8)print(l1)#[0,10,20,30]

WithLambdaFunction:
1)l=[0,5,10,15,20,25,30]
2)l1=list(filter(lambdax:x%2==0,l))
3)print(l1)#[0,10,20,30]
4)l2=list(filter(lambdax:x%2!=0,l))
5)print(l2)#[5,15,25]

map() Function:
 For every element present in the given sequence,apply some functionality and
[Link]
should go for map() function.

 Eg:Foreveryelementpresentinthelistperformdoubleandgeneratenewlistof
doubles.

 Syntax:map(function,sequence)

 Thefunctioncanbeappliedoneachelementofsequenceandgeneratesnew
sequence.

AVERIIK TECHNOLOGY
155
AVERIIK TECHNOLOGY

WithoutLambda
1) l=[1,2,3,4,5]
2)defdoubleIt(x):
3) return2*x
4)l1=list(map(doubleIt,l))
5)print(l1)#[2,4,6,8,10]

WithLambda
1)l=[1,2,3,4,5]
2)l1=list(map(lambdax:2*x,l))
3)print(l1) #[2,4,6,8,10]

-------------------------------------------------------------
Eg2:Tofindsquareofgiven numbers

1)l=[1,2,3,4,5]
2)l1=list(map(lambdax:x*x,l))
3)print(l1) #[1,4,9,16,25]

Wecanapplymap()[Link] length.

Syntax:map(lambdax,y:x*y,l1,l2))
xisfroml1and yisfrom l2

1)l1=[1,2,3,4]
2)l2=[2,3,4,5]
3)l3=list(map(lambdax,y:x*y,l1,l2))
4)print(l3)#[2,6,12,20]

reduce()Function:
 reduce()functionreducessequenceofelementsintoasingleelementbyapplyingthe
specified function.
 reduce(function,sequence)
 reduce()functionpresentinfunctoolsmoduleandhenceweshouldwrite import
statement.

1)fromfunctoolsimport*
2)l=[10,20,30,40,50]
3)result=reduce(lambdax,y:x+y,l)
4)print(result)#150

AVERIIK TECHNOLOGY
156
AVERIIK TECHNOLOGY

Eg:

1)result=reduce(lambdax,y:x*y,l)
2)print(result)#12000000

Eg:

1)fromfunctoolsimport*
2)result=reduce(lambdax,y:x+y,range(1,101))
3)print(result)#5050

EverythingisanObject:
 InPythoneverythingistreatedasobject.
 Evenfunctionsalsointernallytreatedasobjectsonly.

1)deff1():
2)print("Hello")
3)print(f1)
4)print(id(f1))

Output:
<functionf1at0x00419618>429
8264

FunctionAliasing:
Fortheexistingfunctionwecangiveanothername,whichisnothingbutfunctionaliasing.

1)defwish(name):
2)print("GoodMorning:",name)
3)
4)greeting=wish
5)print(id(wish))
6)print(id(greeting))
7)
8)greeting('Durga')
9)wish('Durga')

Output:
4429336
4429336
GoodMorning:Durga
GoodMorning:Durga

AVERIIK TECHNOLOGY
157
AVERIIK TECHNOLOGY

Note:
 Intheaboveexampleonlyonefunctionisavailablebutwecancallthatfunctionby using
either wish name or greeting name.
 Ifwedeleteonenamestillwecan accessthatfunctionbyusingaliasname.

1)defwish(name):
2)print("GoodMorning:",name)
3)

5)
4)greeting=wish

7)wish('Durga')
6)greeting('Durga')
9)delwish
11)greeting('Pavan')
8)

10)#wish('Durga')NameError:name'wish'isnot defined

Output:
GoodMorning:Durga
GoodMorning:Durga
GoodMorning:Pavan

NestedFunctions:
Wecandeclareafunctioninsideanotherfunction,suchtypeoffunctionsarecalledNested
functions.

1)defouter():
2) print("outerfunctionstarted")
3) definner():
4) print("innerfunctionexecution")
5) print("outerfunctioncallinginnerfunction")
6) inner()
7)outer()
8)#inner()NameError:name'inner' isnotdefined

Output:
outerfunctionstarted
outerfunctioncallinginnerfunction
inner function execution

Intheaboveexampleinner()functionislocaltoouter()functionandhenceitisnot possible to
call directly from outside of outer() function.

Note:Afunctioncanreturnanotherfunction.

AVERIIK TECHNOLOGY
158
AVERIIK TECHNOLOGY

1) defouter():
2) print("outerfunctionstarted")
3) definner():
4) print("innerfunctionexecution")
5) print("outerfunctionreturninginnerfunction")
6) returninner
7)f1=outer()
8)f1()
9)f1()
10)f1()

Output:
outerfunctionstarted
outerfunctionreturninginnerfunction
inner function execution
innerfunctionexecution
innerfunctionexecution

Q) Whatisthedifferenecebetweenthefollowinglines?
f1 = outer
f1=outer()

 Inthefirstcasefortheouter()functionweareprovidinganothernamef1
(function aliasing).
 Butinthesecondcasewecallingouter()function,[Link] that
inner function() we are providing another name f1

Note:Wecanpassfunctionasargumentto another function


Eg:filter(function,sequence)
map(function,sequence)
reduce(function,sequence)

AVERIIK TECHNOLOGY
159
AVERIIK TECHNOLOGY

MODULE
S

AVERIIK TECHNOLOGY
160
AVERIIK TECHNOLOGY

 Agroupoffunctions, variablesandclassessavedtoafile,whichisnothingbut
module.
 EveryPython file(.py)actsasamodule.

[Link]

1)x=888
2)
3)defadd(a,b):
4)print("TheSum:",a+b)
5)
7)print("TheProduct:",a*b)
6)defproduct(a,b):

 durgamathmodulecontainsonevariableand2 functions.
 Ifwewanttousemembersofmoduleinourprogramthenweshould importthat
module.
import modulename

 Wecanaccessmembersbyusingmodulename.
[Link]
[Link]()

[Link]:

1)importdurgamath
2)print(durgamath.x)
3)[Link](10,20)
4)[Link](10,20)

Output
888
The Sum:30
TheProduct:200

Note:Wheneverweareusing amoduleinourprogram,forthatmodulecompiledfile will be


generated and stored in the hard disk permanently.

AVERIIK TECHNOLOGY
161
AVERIIK TECHNOLOGY

RenamingaModuleatthetimeofimport(Module
Aliasing):
 Eg:importdurgamathasm
 Heredurgamath isoriginalmodulenameandmisalias name.
 Wecanaccessmembersbyusingaliasnamem

[Link]:

1)importdurgamathasm
2)print(m.x)
3)[Link](10,20)
4)[Link](10,20)

from... import:
Wecanimportparticularmembersofmodulebyusingfrom...import.
Themainadvantageofthisiswecanaccessmembersdirectlywithoutusingmodule name.

1)from durgamathimportx,add
2)print(x)
3)add(10,20)
4)product(10,20)NameError:name'product'isnotdefined

Wecanimportallmembersofamoduleasfollowsfromdurgamath import*

[Link]:

1)from durgamathimport*
2)print(x)
3)add(10,20)
4)product(10,20)

VariousPossibiltiesofimport:
1) import modulename
2) import module1,module2,module3
3) importmodule1asm
4) importmodule1as m1,module2asm2,module3
5) frommoduleimportmember
6) frommoduleimportmember1,member2,memebr3
7) frommoduleimportmemeber1asx
8) frommoduleimport*

AVERIIK TECHNOLOGY
162
AVERIIK TECHNOLOGY

MemberAliasing:
1)fromdurgamathimportxas y,addassum
2)print(y)
3)sum(10,20)

Oncewedefinedas aliasname,weshouldusealiasnameonlyandweshouldnotuse original name

1)from durgamathimportx asy


2)print(x)NameError:name'x'is notdefined

Reloadinga Module:
Bydefaultmodulewillbeloadedonlyonceeventhoughweareimportingmultiple multiple times.

[Link]:
print("Thisisfrom module1")

[Link]

1)importmodule1
2)importmodule1
3)importmodule1
4)importmodule1
5)print("Thisistest module")

Output
Thisisfrommodule1 This is
test module

 Intheaboveprogramtestmodule willbeloadedonlyonceeventhoughweare
importing multiple times.

 Theprobleminthisapproachisafterloadingamoduleifitisupdatedoutsidethen
updated version of module1 is not available to our program.

 Wecan solvethisproblembyreloadingmoduleexplicitlybasedonour requirement.


 Wecan reloadbyusingreload()functionofimp module.

1)importimp
2)[Link](module1)

AVERIIK TECHNOLOGY
163
AVERIIK TECHNOLOGY

[Link]:

1)importmodule1
2)importmodule1
3)fromimpimportreload
4)reload(module1)
5)reload(module1)
6)reload(module1)
7)print("Thisistest module")

Intheaboveprogrammodule1willbeloaded4timesinthat1timebydefaultand3times
explicitly. In this case output is

1)Thisisfrom module1
2)Thisisfrom module1
3)Thisisfrom module1
4)Thisisfrom module1
5)Thisistestmodule

Themainadvantageofexplicitmodulereloadingiswecanensurethatupdatedversionis always
available to our program.

FindingMembersofModulebyusingdir()Function:
Pythonprovidesinbuiltfunctiondir()tolistoutallmembersofcurrentmoduleora specified
module.

dir() To list out all members of current module


dir(moduleName)Tolistoutallmembersofspecifiedmodule

Eg1:[Link]

1)x=10
2)y=20
3)deff1():
4)print("Hello")
5)print(dir()) #Toprintallmembersofcurrent module

Output
['annotations', 'builtins', 'cached','doc', 'file', 'loader', 'nam e', 'package', 'spec', 'f1', 'x', 'y']

AVERIIK TECHNOLOGY
164
AVERIIK TECHNOLOGY

Eg2:Todisplaymembersofparticularmodule

[Link]:

1)x=888
2)
3)defadd(a,b):
5)
4)print("TheSum:",a+b)
7)print("TheProduct:",a*b)
6)defproduct(a,b):

[Link]:

1)importdurgamath
2)print(dir(durgamath))

Output
['builtins','cached','doc','file','loader','name',
'package','spec', 'add', 'product', 'x']

Note:Foreverymoduleatthetimeofexecution Pythoninterpreterwilladdsomespecial
properties automatically for internal use.

Eg: builtins, cached,'doc, file, loader,name, package,


spec

Basedonourrequirementwecanaccessthesepropertiesalsoinour program.

Eg:[Link]

1)print(builtins )
2)print(cached )
3)print(doc)
4)print(file)
5)print(loader)
6)print(name)
7)print(package)
8)print(spec)

Output
<module'builtins'(built-
in)>None
None

AVERIIK TECHNOLOGY
165
AVERIIK TECHNOLOGY

[Link]

1)<_frozen_importlib_external.SourceFileLoaderobjectat0x00572170>
2)main
3)None
4)None

TheSpecialVariable name :
 ForeveryPythonprogram, aspecialvariablename willbeadded internally.
 Thisvariablestoresinformationregardingwhethertheprogramisexecutedasan
individual program or as a module.

 Iftheprogramexecutedasanindividualprogramthenthevalueofthisvariableis
main

 Iftheprogramexecutedasamodulefromsomeotherprogramthenthevalueofthis
variable is the name of module where it is defined.

 Hence by using this name variablewecanidentifywhethertheprogramexecuted


directly or as a module.

Demoprogram:

[Link]:

1) deff1():
2) ifname=='main':
3) print("Thecodeexecutedasaprogram")
4) else:
5) print("Thecodeexecutedasamodulefromsomeotherprogram")
6)f1()

[Link]:

1)importmodule1
2)module1.f1()

D:\Python_classes>[Link]
The code executed as a program

D:\Python_classes>[Link]
Thecodeexecutedasamodulefromsomeotherprogram
Thecodeexecuted as amodulefromsomeotherprogram

AVERIIK TECHNOLOGY
166
AVERIIK TECHNOLOGY

WorkingwithmathModule:
 Pythonprovidesinbuiltmodulemath.
 Thismoduledefinesseveralfunctionswhichcanbeusedformathematicaloperations.
 Themainimportantfunctionsare
1) sqrt(x)
2) ceil(x)
3) floor(x)
4) fabs(x)
5) log(x)
6) sin(x)
7) tan(x)
8) ....

1)from mathimport*
2)print(sqrt(4))
3)print(ceil(10.1))
4)print(floor(10.1))
5)print(fabs(-10.6))
6)print(fabs(10.6))

Output
2.0
11
10
10.6
10.6

Note:Wecanfindhelpforanymodulebyusinghelp() function

Eg:
importmath
help(math)

WorkingwithrandomModule:
 Thismoduledefinesseveralfunctionstogeneraterandomnumbers.
 Wecanusethesefunctionswhiledevelopinggames,incryptographyandtogenerate
random numbers on fly for authentication.

1) random() Function:
Thisfunctionalwaysgeneratesomefloatvaluebetween0and1(notinclusive)
0<x<1

AVERIIK TECHNOLOGY
167
AVERIIK TECHNOLOGY

1) fromrandomimport *
2)for iinrange(10):
3) print(random())

Output
0.4572685609302056
0.6584325233197768
0.15444034016553587
0.18351427005232201
0.1330257265904884
0.9291139798071045
0.6586741197891783
0.8901649834019002
0.25540891083913053
0.7290504335962871

2) randint()Function:
Togeneraterandomintegerbeweentwogiven numbers(inclusive)

1) fromrandomimport *
2)for iinrange(10):
3) print(randint(1,100))#generaterandomintvaluebetween1and100(inclusive)

Output
51
44
39
70
49
74
52
10
40
8

3) uniform() Function:
Itreturnsrandomfloatvaluesbetween2givennumbers(notinclusive)

1) fromrandomimport *
2)for iinrange(10):
3) print(uniform(1,10))

AVERIIK TECHNOLOGY
168
AVERIIK TECHNOLOGY

Output
9.787695398230332
6.81102218793548
8.068672144377329
8.567976357239834
6.363511674803802
2.176137584071641
4.822867939432386
6.0801725149678445
7.508457735544763
1.9982221862917555

random() in between 0 and 1 (not inclusive)


randint(x,y) in between x and y ( inclusive)
uniform(x,y)inbetweenxandy(notinclusive)

4) randrange([start],stop,[step])
 Returnsarandomnumberfromrange
 start<= x<stop
 startargumentisoptionalanddefaultvalueis0
 stepargumentisoptionalanddefaultvalueis1

 randrange(10)generatesanumberfrom0to9
 randrange(1,11)generatesanumberfrom1to 10
 randrange(1,11,2)generatesanumberfrom1,3,5,7,9

1) fromrandomimport *
2)for iinrange(10):
3) print(randrange(10))

Output:9
4
0
2
9
4
8
9
5
9

1)fromrandomimport*
2)for iinrange(10):
3) print(randrange(1,11))

AVERIIK TECHNOLOGY
169
AVERIIK TECHNOLOGY

Output:2
2
8
10
3
5
9
1
6
3

1)fromrandomimport*
2)for iinrange(10):
3) print(randrange(1,11,2))

Output:1
3
9
5
7
1
1
1
7
3

5) choice()Function:
 Itwon’treturnrandom number.
 Itwillreturn arandomobjectfromthegivenlistortuple.

1)fromrandomimport*
2)list=["Sunny","Bunny","Chinny","Vinny","pinny"]
3)for iinrange(10):
4) print(choice(list))
Output
Bunny
pinny
Bunny
Sunny
Bunny
pinny
pinny
Vinny
Bunny
Sunny
AVERIIK TECHNOLOGY
170
AVERIIK TECHNOLOGY

AVERIIK TECHNOLOGY
171
AVERIIK TECHNOLOGY

AVERIIK TECHNOLOGY
172
AVERIIK TECHNOLOGY

You might also like