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

Python Notes For BCA

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Python Notes For BCA

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 118

CHAPTER-

1INTRODUTIONTOPYTHON
1.1 Introduction:
 General-purposeObjectOrientedProgramming language.
 High-levellanguage
 Developedinlate1980byGuidovanRossumatNationalResearchInstituteforMathematics
andComputerScience intheNetherlands.
 ItisderivedfromprogramminglanguagessuchasABC,Modula3,smalltalk,Algol-68.
 ItisOpenSourceScriptinglanguage.
 ItisCase-sensitivelanguage(Differencebetweenuppercaseandlowercaseletters).
 OneoftheofficiallanguagesatGoogle.

1.2 Characteristics of Python:


 Interpreted:Pythonsourcecodeiscompiledtobytecodeasa.pycfile,andthisbytecodecanbein
terpretedbytheinterpreter.
 Interactive
 ObjectOrientedProgrammingLanguage
 Easy&Simple
 Portable
 Scalable:Providesimprovedstructureforsupportinglargeprograms.
 Integrated
 ExpressiveLanguage
1.3 PythonInterpreter:
NamesofsomePythoninterpretersare:
 PyCharm
 PythonIDLE
 ThePythonBundle
 pyGUI
 SublimeText etc.

Therearetwomodestousethepythoninterpreter:
i. InteractiveMode
ii. ScriptMode
i. InteractiveMode:

Withoutpassingpythonscriptfiletotheinterpreter,directlyexecutecodetoPython(Comma
ndline).

Example:
>>>6+3

Output:9

Fig:InteractiveMode

Note: >>>is a command the python interpreter uses to indicate that it is ready.
Theinteractivemodeisbetterwhen aprogrammerdealswithsmall piecesofcode.
To runa python fileoncommandline:
exec(open(“C:\Python33\pythonprograms\program1.py”).read())

ii. Script Mode: In this mode source code is stored in a file with the .py
extensionand use the interpreter to execute the contents of the file. To execute the
script by theinterpreter,youhavetotelltheinterpreterthe nameof thefile.

Example:
ifyouhaveafilenameDemo.py,torunthescriptyouhavetofollowthefollowingsteps:

Step-1:Openthetexteditori.e.Notepad
Step-2: Write the python code and save the file with .py file extension.
(DefaultdirectoryisC:\Python33/Demo.py)
Step-3:OpenIDLE(PythonGUI)pythonshell
Step-4:Clickon filemenu andselecttheopenoption
Step-5:Selecttheexistingpythonfile
Step-6:Nowawindowofpythonfilewillbeopened
Step-7:Clickon Runmenu andtheoptionRun Module.
Step-8:Outputwillbedisplayedonpythonshellwindow.

Fig.:IDLE(PythonGUI)

Fig:PythonShell
CHAPTER-
2PYTHONFUNDAMENTAL
S

2.1 PythonCharacterSet:
Itisasetofvalidcharactersthatalanguagerecognize.
Letters: A-Z, a-
zDigits : 0-
9Special
SymbolsWhites
pace

2.2 TOKENS
Token:Smallestindividualunitinaprogramisknownastoken.There
are five typesof tokeninpython:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators

1. Keyword:Reservedwordsinthelibraryofalanguage.Thereare33keywords
inpython.

False class finally is return break

None continue for lambda try except

True def from nonlocal while in

and del global not with raise

as elif if or yield

assert else import pass


Allthekeywords areinlowercaseexcept03keywords(True,False,None).
2. Identifier:Thenamegivenbytheusertotheentitieslikevariablename,class-name,function-
nameetc.

Rulesforidentifiers:

 Itcan beacombinationofletters inlowercase(ato z)oruppercase(Ato Z)ordigits


(0to9)or anunderscore.
 Itcannotstartwithadigit.
 Keywordscannotbeused as anidentifier.
 Wecannot usespecialsymbolslike!,@,#,$,%,+etc.inidentifier.
 _(underscore)can beusedinidentifier.
 Commasorblankspacesarenotallowedwithinanidentifier.

3. Literal:Literalsaretheconstantvalue.Literalscanbedefinedasadatathatisgiveninavariable
or constant.

Literal

String LiteralColl
Numeric Boolean Special
ections

int float complex

True False None

A. Numericliterals:NumericLiteralsareimmutable.

Eg.

5, 6.7, 6+9j
B. Stringliterals:

Stringliteralscanbeformedbyenclosingatextinthequotes.Wecanusebothsingleaswell
asdoublequotesfor a String.

Eg:

"Aman",'12345'

Escape sequencecharacters:
\\ Backslash
\’ Singlequote
\” Doublequote
\a ASCIIBell
\b Backspace
\f ASCIIFormfeed
\n Newlinecharater
\t Horizontaltab

C. Booleanliteral:ABoolean literalcanhaveanyofthetwovalues:TrueorFalse.

D. Specialliterals:Pythoncontainsonespecialliterali.e. None.

Noneisusedtospecifytothatfieldthat isnotcreated.Itisalsoused forendoflists inPython.

E. LiteralCollections: Collectionssuchastuples,listsandDictionaryareusedinPython.

4. Operators: An operator performs the operation on operands. Basically there are


twotypes ofoperatorsinpython accordingto number ofoperands:
A. UnaryOperator
B. BinaryOperator

A. Unary Operator:Performstheoperationonone operand.


Example:
+ Unaryplus
- Unaryminus
~

Bitwisecomplementnot
Logicalnegation

B. BinaryOperator:Performsoperationontwooperands.

5. Separatoror punctuator:,;,(),{ },[ ]

2.3 MantissaandExponentForm:

Arealnumberin exponent formhastwo parts:


 mantissa
 exponent
Mantissa: Itmustbeeitheran integeroraproperreal constant.
Exponent: It mustbe aninteger.Representedbyaletter Eor efollowedbyintegervalue.

ValidExponentform InvalidExponentform
123E05 2.3E(Nodigitspecified forexponent)
1.23E07
0.24E3.2(Exponentcannothavefractionalpart)23,4
0.123E08
55E03 (No comma allowed)
123.0E08
123E+8
1230E04
-0.123E-3
163.E4
.34E-2
4.E3
2.4 BasictermsofaPythonPrograms:
A. BlocksandIndentation
B. Statements
C. Expressions
D. Comments

A. BlocksandIndentation:
 Python provides no braces to indicate blocks of code for class and function definition
orflowcontrol.
 Maximumlinelengthshould bemaximum79 characters.
 Blocksofcodearedenotedbylineindentation,whichisrigidlyenforced.
 Thenumberofspacesintheindentationisvariable,butallstatementswithintheblockmust be
indentedthesame amount.
for example –
ifTrue:
print(“True”)
else:
print(“False”)

B. Statements
Alinewhichhastheinstructionsorexpressions.

C. Expressions:
Alegalcombinationofsymbolsandvaluesthatproducearesult.Generallyitproducesavalue.

D. Comments:Commentsarenotexecuted.Commentsexplainaprogramandmakeaprogram
understandable and readable. All characters after the # and up to the end of
thephysicallinearepartofthecomment andthePython interpreterignores them.
Therearetwotypes ofcommentsinpython:
i. Singlelinecomment
ii. Multi-linecomment

i. Single line comment: This type of comments start in a line and when a line ends, it
isautomaticallyends. Singleline commentstarts with#symbol.
Example:ifa>b: #Relationaloperatorcomparetwovalues

ii. Multi-Line comment: Multiline comments can be written in more than one lines.
Triplequoted ‘ ’ ’ or “ ””) multi-line commentsmay be used in python.It is also
knownasdocstring.
Example:
‘’’Thisprogramwillcalculatetheaverageof10values.

Firstfind thesumof10 values


and divide thesumbynumber ofvalues
‘’’
MultipleStatementsonaSingleLine:
Thesemicolon(;)allowsmultiplestatementsonthesinglelinegiventhatneitherstatementstarts anewcode
block.
Example:-
x=5;print(“Value=”x)

2.5 Variable/LabelinPython:
Definition:Namedlocationthat
referstoavalueandwhosevaluecanbeusedandprocessedduringprogramexecution.
Variablesinpythondonothavefixedlocations.Thelocationtheyrefertochangeseverytimetheirvalue
schange.

Creatingavariable:

Avariableiscreatedthemomentyoufirstassign avaluetoit.Example:

x=5

y= “hello”

Variablesdonotneedtobedeclaredwithanyparticulartypeandcanevenchangetypeaftertheyhavebeen
set.Itisknownasdynamic Typing.

x =4# xisof typeint


x = "python" # x is now of type
strprint(x)

RulesforPythonvariables:

 Avariablename muststart withaletterortheunderscorecharacter


 Avariablenamecannotstartwithanumber
 A variable name can only contain alpha-numeric characters and underscore (A-z, 0-
9,and_ )
 Variablenamesarecase-sensitive(age,AgeandAGEarethreedifferentvariables)
Pythonallowsassignasinglevaluetomultiplevariables.Exa

mple: x =y=z =5

Youcanalsoassignmultiplevaluestomultiplevariables.Forexample−

x ,y,z =4,5,“python”
4isassignedtox,5isassignedtoyandstring“python”assignedtovariablezrespectively.x=12
y=14
x,y=y,xp
rint(x,y)
Nowtheresultwillbe14
12

LvalueandRvalue:
Anexpressionhastwovalues.LvalueandRvalue.Lva
lue: theLHSpartoftheexpression
Rvalue:theRHSpartoftheexpression
PythonfirstevaluatestheRHSexpressionandthenassignstoLHS.Example:
p,q, r= 5,10,7
q, r, p = p+1, q+2, r-
1print (p,q,r)
Nowtheresult willbe:
6 6 12

Note:Expressionsseparatedwithcommas areevaluatedfromlefttorightandassignedinsameorder.

 Ifyou wanttoknowthetypeofvariable,you canusetype()function:


Syntax:
type(variable-name)
Example:
x=6typ
e(x)
Theresultwillbe:
<class‘int’>
 Ifyou wanttoknowthe memoryaddress orlocationof theobject,you canuseid()
function.
Example:
>>>id(5)15
61184448
>>>b=5
>>>id(b)15
61184448
You can delete single or multiple variables by using del statement.
Example:delx
dely,z

2.6 Inputfroma user:


input()method isusedto takeinput
fromtheuser.Example:
print("Enteryourname:")x
=input( )
print("Hello," +x)

 input()functionalwaysreturnsavalueofstringtype.

2.7 TypeCasting:
Toconvertonedatatypeintoanotherdatatype.

Castinginpythonisthereforedoneusingconstructorfunctions:
 int()-constructsanintegernumberfromanintegerliteral,afloatliteral
orastringliteral.

Example:

x = int(1) # x will be
1y = int(2.8) # y will be
2z=int("3")# zwillbe3

 float()-constructs afloatnumberfromanintegerliteral,afloatliteral orastringliteral.

Example:

x = float(1) # x will be
1.0y = float(2.8)# y will be
2.8z=float("3")# zwillbe 3.0
w=float("4.2")#wwillbe4.2

 str()-constructsastringfromawidevarietyofdatatypes,includingstrings,integerliterals
andfloatliterals.

Example:

x = str("s1") # x will be
's1'y=str(2)

#ywillbe'2'z=str(3.0)#
zwill be '3.0'

Readinganumber froma user:


x=int(input(“Enteranintegernumber”))

2.8 OUTPUTusingprint()statement:S
yntax:
print(object,sep=<separatorstring>,end=<end-string>)
object: Itcanbeoneormultipleobjects separatedbycomma.
sep:separgumentspecifiestheseparatorcharacterorstring.Itseparatetheobjects/items.Bydefault
separgument addsspaceinbetween the items whenprinting.
end:Itdeterminestheendcharacterthatwillbeprintedattheendofprintline.Bydefaultithasnewline
character( ‘\n’).
Example:
x=10
y=20
z=30
print(x,y,z,sep=’@’,end=‘‘)Ou
tput:
10@20@30
CHAPTER-
3DATAHANDLING
3.1 DataTypesinPython:
Pythonhas Twodatatypes –

1. PrimitiveDataType(Numbers,String)
2. CollectionDataType(List,Tuple,Set,Dictionary)

DataTypes

Primitive Collection
DataType Data Type

Number String

List Tuple Set Dictionary


int float complex

1. PrimitiveDataTypes:
a. Numbers:Numberdatatypesstorenumericvalues.

Therearethreenumerictypesin Python:

 int
 float
 complex

Example:
w=1 #int
y=2.8 # float
z =1j #complex
 integer:Therearetwotypesofintegersinpython:
 int
 Boolean

 int:intorinteger,isawholenumber,positiveornegative,without decimals.
Example:

x=1
y=35656222554887711
z=-3255522
 Boolean: It has two values: True and False. True has the value 1 and False has
thevalue0.
Example:

>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘‘)
False
>>>bool(-34)
True
>>>bool(34)
True

 float : float or "floating point number" is a number, positive or negative, containing


oneor more decimals. Float can also be scientific numbers with an "e" to indicate the
powerof 10.
Example:

x =1.10
y=1.0
z=-35.59
a=
35e3b=1
2E4
c=-87.7e100
 complex: Complex numbers arewritten witha"j"astheimaginarypart.
Example:

>>>x=3+5j
>>>y=2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>z.real
5.0
>>>z.imag
9.0
Realandimaginarypartofanumbercanbeaccessedthroughtheattributesrealandimag.

b. String:Sequenceofcharactersrepresentedinthequotationmarks.
 Pythonallowsforeitherpairsofsingleordoublequotes.Example:'hello'isthesameas"hello" .
 Pythondoesnothaveacharacterdatatype,asinglecharacterissimplyastringwithalengthof1.
 ThepythonstringstoreUnicodecharacters.
 Eachcharacterin astringhasits ownindex.
 Stringisimmutabledatatypemeans itcan neverchangeits valueinplace.

2. CollectionDataType:
 List
 Tuple
 Set
 Dictionary
3.2 MUTABLE&IMMUTABLEDataType:
 MutableData Type:
Thesearechangeable.Inthesame memoryaddress,newvaluecan bestored.Example:
List,Set,Dictionary
 ImmutableDataType:
These are unchangeable. In the same memory address new value cannot be
stored.Example: integer,float, Boolean,stringand tuple.

3.3 BasicOperatorsinPython:
i. ArithmeticOperators
ii. RelationalOperator
iii. LogicalOperators
iv. Bitwiseoperators
v. AssignmentOperators
vi. OtherSpecialOperators
o IdentityOperators
o Membershipoperators

i. ArithmeticOperators:Toperformmathematicaloperations.

RESULT(
OPERATOR NAME SYNTAX
X=14,Y=4)

+ Addition x+y 18

_ Subtraction x–y 10

* Multiplication x*y 56

/ Division(float) x/y 3.5

// Division(floor) x//y 3

% Modulus x%y 2

** Exponent x**y 38416


Example:
>>>x= -5
>>>x**2
>>>-25

ii. Relational Operators: Relational operators compare the values. It


eitherreturns TrueorFalseaccordingtothecondition.

RESULT(IF
OPERATOR NAME SYNTAX
X=16,Y=42)

False
> Greaterthan x>y
True
< Lessthan x<y
False
== Equalto x== y
True
!= Notequalto x!=y
False
>= Greaterthanorequalto x>= y
True
<= Lessthanorequalto x<= y

iii. Logical operators: Logical operators perform Logical AND, Logical OR and
LogicalNOToperations.

OPERATOR DESCRIPTION SYNTAX


and LogicalAND:Trueifboththeoperands aretrue x andy
or LogicalOR: Trueifeitheroftheoperandsistrue xor y
not LogicalNOT:Trueifoperandis false not x

ExamplesofLogicalOperator:

Theandoperator:Theandoperatorworksin twoways:
a. Relationalexpressionsasoperands
b. numbersorstringsorlists asoperands
a. Relationalexpressionsasoperands:

X Y XandY
False False False
False True False
True False False
True True True

>>>5>8and7>3
False
>>>(4==4)and (7==7)
True

b. numbersorstringsorlistsasoperands:
In an expression X and Y, if first operand has false value, then return first operand X as
aresult,otherwise returnsY.

>>>0 and 0 X Y XandY


0 false false X
>>>0 and 6 false true X
0 true false Y
>>>‘a’ and
true true Y
‘n’’n’
>>>6>9and‘c’+9>5 #and operatorwilltestthesecondoperandonlyifthefirstoperandFalse
#is true,otherwiseignores it,even ifthesecondoperandiswrong

Theoroperator:Theoroperatorworksintwoways:
a. Relationalexpressionsasoperands
b. numbersorstringsorlistsasoperands

a. Relationalexpressionsasoperands:

X Y Xor Y
False False False
False True True
True False True
True True True

>>>5>8or7>3
True
>>>(4==4)or(7==7)
True
b. numbersorstringsorlistsasoperands:
In an expression X or Y, if first operand has true value, then return first operand X as
aresult,otherwise returnsY.

X Y Xor Y
false false Y
false true Y
true false X
true true X

>>>0or0
0
>>>0or6
6
>>>‘a’or‘n’’
a’
>>>6<9or ‘c’+9>5 # or operator will test the second operand only if the first
operandTrue #isfalse,otherwiseignoresit,evenifthesecondoperand iswrong

Thenotoperator:
>>>not
6False
>>>not
0True
>>>not -
7False

ChainedComparisonOperators:
>>>4<5>3 is equivalentto >>> 4<5 and
5>3True True

iv. Bitwiseoperators:Bitwiseoperatorsactsonbitsandperforms bitbybitoperation.

OPERATOR DESCRIPTION SYNTAX

& BitwiseAND x&y

| BitwiseOR x|y
~ BitwiseNOT ~x

^ BitwiseXOR x^y

>> Bitwiserightshift x>>

<< Bitwiseleftshift x<<

Examples:
Let Outpu
a =10
t:0
b=4print(a
14
& b)print(a
-11
| 14
2
b)print(~a)
40
print(a ^
b)print(a>>2)

print(a<<2)

v. Assignmentoperators:Assignmentoperatorsareusedtoassignvaluestothevariables.

OPERA
TOR DESCRIPTION SYNTAX

= Assignvalueofrightsideofexpressiontoleftsideoperand x=y+z
AddAND:Addrightsideoperandwithleftsideoperandandthen a+=ba
+=
assigntoleftoperand =a+b
Subtract AND: Subtract right operand from left operand and a-=ba=a-b
-=
thenassigntoleftoperand
MultiplyAND:Multiplyrightoperandwithleftoperandandthenassignt a*=ba
*=
oleftoperand =a*b
DivideAND:Divideleftoperandwithrightoperandandthenassignto a/
/=
leftoperand =ba=
a/b
ModulusAND:Takesmodulususingleftandrightoperandsandassign a
%=
resulttoleftoperand %=ba
=a%b
Divide(floor)AND:Divideleftoperandwithrightoperandandthen a//
//=
assignthevalue(floor)toleftoperand =ba=a
//b
ExponentAND:Calculateexponent(raisepower)valueusingoperands a**=ba
**=
andassignvaluetoleft operand =a**b
PerformsBitwiseANDonoperandsandassignvaluetoleftoper a&=ba
&=
and =a&b
Performs Bitwise OR on operands and assign value to a|
|=
leftoperand =ba=
a|b
PerformsBitwisexORonoperandsandassignvaluetoleftopera a^=ba
^=
nd =a^b
PerformsBitwiserightshiftonoperandsandassignvaluetoleftoperand a>>=ba
>>=
=a>>b
Performs Bitwise left shift on operands and assign value to a <<=b
<<=
leftoperand a=a <<b
vi. OtherSpecialoperators:Therearesomespecialtypeofoperatorslike-

a. Identity operators- is and is not are the identity operators both are used to check
iftwo values are located on the same part of the memory. Two variables that are
equaldoesnotimplythattheyareidentical.
is True if the operands are identicalTrueiftheoperandsarenotidentical
isnot

Example:
Leta1
=3
b1=3
a2 =
'PythonProgramming'b2 =
'PythonProgramming'a3
=[1,2,3]
b3=[1,2,3]

print(a1isnotb1)
print(a2isb2) # Output is False, since lists are
mutable.print(a3 isb3)

Output:
FalseTrue
FalseExa
mple:
>>>str1=“Hello”
>>>str2=input(“Enter a
String :”)EnteraString :Hello
>>>str1==str2

#comparesvaluesofstringTrue
>>>str1is str2 # checks iftwoaddress refertothesame
memoryaddressFalse

b. Membershipoperators- inand
notinarethemembershipoperators;usedtotestwhetheravalueorvariableisinasequence
.

in Trueifvalueis found inthesequence


not in Trueifvalueis not foundinthesequence

Example:
Let
x = 'Digital
India'y={3:'a',4:'b
'}

print('D'inx)print('digi

tal' not in

x)print('Digital' not in

x)print(3iny)

print('b'iny)
Output:
True
True
False
True
False

3.4 OperatorPrecedenceandAssociativity:
OperatorPrecedence:Itdescribestheorderinwhichoperationsareperformedwhenanexpressionis
evaluated.Operators withhigherprecedenceperformtheoperation first.
OperatorAssociativity:whenevertwoormoreoperatorshavethesameprecedence,thenassociativitydef
inesthe order ofoperations.

Operator Description Associativity Precedence


( ),{ } Parentheses(grouping) Leftto Right
f(args…) Functioncall Leftto Right
x[index:index] Slicing Leftto Right
x[index] Subscription Leftto Right
** Exponent RighttoLeft
~x Bitwisenot Leftto Right
+x,-x Positive,negative Leftto Right
*,/, % Product,division,remainder Leftto Right
+,– Addition,subtraction Leftto Right
<<,>> Shiftsleft/right Leftto Right
& BitwiseAND Leftto Right
^ BitwiseXOR Leftto Right
| BitwiseOR Leftto Right
<=,<, >, >= Comparisons Leftto Right
=,%=,/=, += Assignment
is,isnot Identity
in,notin Membership
not BooleanNOT Leftto Right
and BooleanAND Leftto Right
or BooleanOR Leftto Right
lambda Lambdaexpression Leftto Right
CHAPTER-
4FLOWOFCONTROL

1. DecisionMakingandbranching (ConditionalStatement)

2. LoopingorIteration

3. Jumpingstatements

4.1 DECISIONMAKING&BRANCHING
Decision making is about deciding the order of execution of statements based on
certainconditions. Decision structures evaluate multiple expressions which produce TRUE or
FALSEas outcome.
Therearethreetypesofconditionsinpython:
1. ifstatement
2. if-elsestatement
3. elifstatement

1. ifstatement:Itisasimpleifstatement.Whenconditionistrue,thencodewhichisassociate
d withifstatement willexecute.
Example:
a=40
b=20
ifa>b:
print(“ais greater thanb”)

2. if-
elsestatement:Whentheconditionistrue,thencodeassociatedwithifstatementwillexecute,othe
rwisecodeassociatedwith elsestatementwill execute.
Example:
a=10
b=20
ifa>b:
print(“aisgreater”)
else:
print(“bisgreater”)

3. elif statement: It is short form of else-if statement. If the previous conditions were not
true,thendothis condition".Itis alsoknown asnestedifstatement.
Example:
a=input(“Enter first
number”)b=input("Enter Second
Number:")if a>b:
print("a is
greater")elifa==b:
print("bothnumbersareequal")
else:

print("bisgreater")

4.2 LOOPSinPYTHON
Loop:Executeasetofstatementsrepeatedlyuntil aparticularconditionissatisfied.

Therearetwotypes ofloopsinpython:
1. whileloop
2. forloop

whileloop
Loops inPython

for loop
1. while loop: With thewhileloop we can execute a set of statements as long as a condition
istrue.Itrequirestodefineanindexingvariable.
Example:Toprinttableofnumber2i=2
whilei<=20:
print(i)
i+=2

2. forloop:Theforloop iterateoveragivensequence(it maybelist,tupleorstring).

Note:Theforloopdoesnotrequireanindexingvariabletosetbeforehand,astheforcommanditselfallowsfo
r this.

primes = [2, 3, 5,
7]forxinprimes:
print(x)

Therange()function:

itgeneratesalistofnumbers,whichisgenerallyusedtoiterateoverwithforloop.range()functionu
sesthreetypesofparameters,whichare:

 start:Startingnumberofthesequence.
 stop:Generatenumbersupto,butnotincludinglastnumber.
 step:Difference

betweeneachnumberinthesequence.Pythonuserange()functionint

hreeways:

a. range(stop)

b. range(start,stop)

c. range(start,stop,step)

Note:

 Allparametersmustbeintegers.
 Allparameterscanbepositiveornegative.
a. range(stop):Bydefault,Itstartsfrom0andincrementsby1andendsuptostop,butnotincludin
gstopvalue.

Example:

forxinrange(4):
print(x)

Output:

0
1
2
3

b. range(start,stop):Itstartsfromthestartvalueanduptostop,butnotincludingstopvalue.

Example:

forxin range(2,6):
print(x)

Output:

2
3
4
5

c. range(start, stop, step): Third parameter specifies to increment or decrement the value
byaddingorsubtractingthevalue.

Example:

forxinrange(3,8,2):pri

nt(x)

Output:

3
5
7
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3
andincrease it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1
valuethat is8here.So,theoutputis3,5,8.

Differencebetweenrange( )andxrange():

S.
No. range( ) xrange()

returnsthe
1 returnsthelistofnumbers
generatorobjectthatcanbeusedtodisplaynumbe
rsonlybylooping
The variable storing the rangetakes
2 variablestoringtherangetakeslessmemory
morememory
alltheoperationsthatcanbeappliedonthelistc operations associated to list cannot
3
anbeusedon it beapplied onit
4 slowimplementation fasterimplementation

4.3 JUMPSTATEMENTS:
Therearetwojumpstatementsinpython:
1. break
2. continue

1. breakstatement:With the breakstatement wecanstop theloopevenifitis true.


Example:
inwhileloop in forloop
i=1 languages = ["java", "python",
while i "c++"]forx in languages:
<6:print( if x ==
i)ifi==3: "python":brea
break k
i+= 1 print(x)
Output: Output:
1 java
2
3

Note: If the break statement appears in a nested loop, then it will terminate the very loop it
isin i.e. if the break statement is inside the inner loop then it will terminate the inner loop
onlyand the outer loopwill continue asitis.
2. continuestatement:Withthe
continuestatementwecanstopthecurrentiteration,andcontinuewiththe nextiteration.
Example:
inwhileloop in forloop
i=0 languages = ["java", "python",
while i "c++"]forx in languages:
<6:i+= 1 if x ==
if i == "python":cont
3:conti inue
nue print(x)
print(i)

Output: Output
1 :javac+
2 +
4
5
6

4.4 Loopelsestatement:
Theelsestatementofapythonloopexecuteswhentheloopterminatesnormally.Theelsestatementoftheloo
pwillnot executewhen thebreakstatementterminatestheloop.
Theelseclauseofaloopappearsatthesameindentationasthatoftheloopkeywordwhileor
for.

Syntax:
forloop whileloop

for <variable> in while <test


<sequence>:statement-1 condition>:state
statement-2 ment-
. 1statement-2
. .
else: .
statement(s) else:
statement(s)

4.5 NestedLoop:
Aloopinsideanotherloopisknown asnestedloop.
Syntax:
for<variable-name>in<sequence>:
for <variable-name> in
<sequence>:statement(s)
statement(s)

Example:

foriin range(1,4):
forjin range(1,i):
print("*", end="
")print("")

ProgramsrelatedtoConditional,loopingandjumpingstatements
1. Writea programtochecka numberwhetheritisevenorodd.
num=int(input("Enterthenumber:"))if
num%2==0:
print(num, " is even
number")else:
print(num,"isoddnumber")

2. Writeaprograminpythonto checkanumberwhetheritis primeornot.


num=int(input("Enterthenumber:"))f
oriinrange(2,num):
ifnum%i==0:
print(num, "is not prime
number")break;
else:
print(num,"isprimenumber")
3. Writea programtochecka yearwhether itisleap yearornot.
year=int(input("Entertheyear:"))ify
ear%100==0andyear%400==0:
print("It is a leap
year")elifyear%4==0:
print("It is a leap
year")else:
print("Itisnot leapyear")

4. Writeaprograminpythontoconvert°Cto °Fandvice versa.


a=int(input("Press 1 for C to F \n Press 2 for F to C \
n"))if a==1:
c=float(input("Enter the temperature in degree
celcius:"))f=(9/5)*c+32
print(c, "Celcius = ",f,"
Fahrenheit")elifa==2:
f=float(input("Enter the temperature in
Fahrenheit:"))c=(f-32)*5/9
print(f,"Fahrenheit=",c,"Celcius")
else:
print("Youenteredwrongchoice")

5. Writeaprogramto checkanumber whetheritis palindromeornot.


num=int(input("Enter a number :
"))n=num
res=0
while
num>0:rem=n
um%10
res=rem+res*10
num=num//10
ifres==n:
print("NumberisPalindrome")e
lse:
print("NumberisnotPalindrome")

6. A number is Armstrong number or


not.num=input("Enter a number :
")length=len(num)
n=int(num)
num=nsum
=0whilen>
0:
rem=n
%10sum=sum+rem**le
ngthn=n//10
ifnum==sum:
print(num, "is armstrong
number")else:
print(num,"isnotarmstrongnumber")

7. Tocheckwhetherthenumberisperfect number or not


num=int(input("Enter a number :
"))sum=0
foriinrange(1,num):if
(num%i==0):
sum=sum+i
ifnum==sum:
print(num, "is perfect
number")else:
print(num,"isnotperfectnumber")

8. WriteaprogramtoprintFibonacciseries.n=i
nt(input("How many numbers :
"))first=0
second=1
i=3
print(first, second, end="
")whilei<=n:
third=first+secondp
rint(third, end="
")first=secondsecon
d=third
i=i+1
9. To printa patternusing nestedloops
foriin range(1,5): 1
for j in 1 2
range(1,i+1):print(j 1 2 3
,"",end="") 1 2 3 4
print('\n')
CHAPTER-
5FUNCTIONSINPYTHO
N
5.1 Definition:Functionsarethesubprogramsthatperformspecifictask.Functionsarethe
smallmodules.

5.2 TypesofFunctions:
Therearetwotypesoffunctionsinpython:
1. LibraryFunctions(Builtinfunctions)
2. Functionsdefinedinmodules
3. UserDefinedFunctions

Builtinfunctions

Functionsdefinedinmodules
Typesoffunctions

Userdefinedfunctions

1. LibraryFunctions:Thesefunctionsarealreadybuiltinthepythonlibrary.

2. Functions defined in modules: These functions defined in particular modules.


Whenyouwanttousethesefunctionsinprogram,youhavetoimportthecorrespondingmoduleoftha
tfunction.

3. User Defined Functions: The functions those are defined by the user are called
userdefined functions.

1. LibraryFunctionsinPython:
Thesefunctions arealreadybuiltin thelibraryofpython.
Forexample:type(),len(),input()etc.
2. Functionsdefinedinmodules:
a. Functionsofmathmodule:
Toworkwiththefunctionsofmathmodule,wemustimportmathmoduleinprogram.
importmath
S.No. Function Description Example
1 sqrt() Returnsthe squareroot ofanumber >>>math.sqrt(49)
7.0
2 ceil() Returnstheupperinteger >>>math.ceil(81.3)
82
3 floor() Returnsthelowerinteger >>>math.floor(81.3)
81
4 pow() Calculatethepower ofanumber >>>math.pow(2,3)
8.0
5 fabs() Returnsthe absolute valueof anumber >>>math.fabs(-5.6)
5.6
6 exp( ) Returnsthe eraised tothepoweri.e.e3 >>>math.exp(3)
20.085536923187668

b. Functioninrandommodule:
randommodulehas afunction randint().
 randint()functiongeneratestherandomintegervaluesincludingstartandendvalues.
 Syntax:randint(start,end)
 Ithastwoparameters.Bothparametersmusthaveintegervalues.

Example:
import
randomn=random.ran
dint(3,7)

*Thevalueofnwillbe 3to7.

3. USERDEFINED FUNCTIONS:
Thesyntaxtodefineafunctionis:
def function-name ( parameters)
:#statement(s)
Where:

 Keyworddefmarksthestartoffunctionheader.
 Afunctionnametouniquelyidentifyit.Functionnamingfollowsthesamerulesofwriting
identifiersinPython.
 Parameters(arguments)throughwhichwepassvaluestoafunction.Theyareoptional.
 Acolon (:)to marktheendoffunction header.
 Oneormorevalidpythonstatementsthatmakeupthefunctionbody.Statementsmusthavesame
indentationlevel.
 Anoptionalreturnstatementtoreturnavaluefromthefunction.

Example:

defdisplay(name):

print("Hello" + name +"Howareyou?")

5.3 FunctionParameters:
Afunctionshas twotypes ofparameters:
1. Formal Parameter: Formal parameters are written in the function prototype and
functionheader of the definition. Formal parameters are local variables which are assigned
values fromtheargumentswhenthe functionis called.
2. Actual Parameter: When a function is called, the values that are passed in the call
arecalled actual parameters. At the time of the call each actual parameter is assigned to
thecorresponding formalparameterinthe function definition.
Example:
defADD(x,y): #Defining afunction andxand yareformal
parametersz=x+y
print("Sum=",z)a=float(input("Enter
first number:
" ))b=float(input("Entersecondnumber:")
)
ADD(a,b) #Callingthefunctionbypassingactualparameters
Intheaboveexample, xandyareformalparameters.aandbareactualparameters.
5.4 Callingthefunction:
Once we have defined a function, we can call it from another function, program or even
thePythonprompt.Tocallafunctionwesimplytypethefunctionnamewithappropriateparameters.

Syntax:
function-name(parameter)
Example:
ADD(10,20)

OUTPUT:
Sum= 30.0

Howfunctionworks?

deffunctionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)

… .. …
… .. …

Thereturnstatement:
Thereturnstatementisusedtoexitafunctionandgobacktotheplacefromwhereitwascalled.
Therearetwotypesoffunctions accordingtoreturnstatement:
a. Functionreturningsomevalue(non-voidfunction)
b. Functionnotreturninganyvalue(voidfunction)
a. Function returning some value (non-void
function) :Syntax:
returnexpression/value
Example-1:Functionreturning onevalue
defmy_function(x):
return5*x

Example-2Functionreturningmultiplevalues:
defsum(a,b,c):
returna+5,b+4,c+7
S=sum(2,3,4)

#Swillstorethereturnedvaluesasatupleprint(S)

OUTPUT:
(7, 7,11)

Example-3:Storingthereturnedvaluesseparately:
defsum(a,b,c):
returna+5,b+4,c+7
s1,s2, s3=sum(2, 3, 4) # storing the values
separatelyprint(s1, s2, s3)

OUTPUT:
7711

b. Functionnotreturninganyvalue(voidfunction):Thefunctionthatperformssomeoperationsbu
t doesnot returnanyvalue,calledvoidfunction.
def
message():pri
nt("Hello")
m=message()
print(m)
OUTPUT:
Hello
None

5.5 ScopeandLifetimeofvariables:

Scopeofavariableistheportionofaprogramwherethevariableisrecognized.Parametersand
variables defined inside a function is not visible from outside. Hence, they have a localscope.

Therearetwotypes ofscopeforvariables:

1. LocalScope

2. GlobalScope

1. Local Scope: Variable used inside the function. It can not be accessed outside the
function.In this scope, The lifetime of variables inside a function is as long as the function
executes.They are destroyed once we return from the function. Hence, a function does not
remember thevalueofavariable fromitspreviouscalls.

2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of
avariableisthe periodthroughout whichthevariableexitsin thememory.

Example:

defmy_func():
x =10
print("Valueinsidefunction:",x)

x =20
my_func()
print("Valueoutsidefunction:",x)

OUTPUT:

Value inside function:

10Valueoutsidefunction:2
0
Here, we can see that the value of x is 20 initially. Even though the function
my_func()changedthevalue ofx to10,itdidnotaffectthe valueoutsidethe function.

Thisisbecausethevariablexinsidethefunctionisdifferent(localtothefunction)fromtheone outside.
Although they have same names, they are two different variables with differentscope.

Ontheotherhand,variables outsideof thefunctionarevisiblefrominside.Theyhave aglobal


scope.

We can read these values from inside the function but cannot change (write) them. In order
tomodify the value of variables outside the function, they must be declared as global
variablesusingthekeywordglobal.

5.6 RECURSION:
Definition:Afunctioncallsitself,iscalledrecursion.
5.6.1 Pythonprogramtofindthefactorialofanumberusingrecursion:
Program:
def
factorial(n):if
n == 1:
return
nelse:
returnn*factorial(n-1)

num=int(input("enterthenumber:"))if
num<0:
print("Sorry,factorialdoesnotexistfornegativenumbers")elif
num== 0:
print("The factorial of 0 is
1")else:
print("Thefactorialof",num,"is",factorial(num))
OUTPUT:
enterthenumber:5
Thefactorial of 5 is 120

5.6.2 PythonprogramtoprinttheFibonacciseriesusingrecursion:Pro
gram:
def
fibonacci(n):i
f n<=1:
return
nelse:
return(fibonacci(n-1)+fibonacci(n-2))

num=int(input("How many terms you want to display:


"))foriinrange(num):
print(fibonacci(i),"",end="")

OUTPUT:
How manytermsyouwanttodisplay:80
1 1 2 3 5 8 13

5.6.3 BinarySearchusingrecursion:
Note:Thegivenarrayorsequencemustbesortedto performbinarysearch.
Program:
def Binary_Search(sequence, item, LB,
UB):ifLB>UB:
return-5 # return any negative
valuemid=int((LB+UB)/2)
ifitem==sequence[mid]:
return mid
elifitem<sequence[mid]:
UB=mid-1
return Binary_Search(sequence, item, LB,
UB)else:
LB=mid+1
returnBinary_Search(sequence,item,LB,UB)

L=eval(input("Entertheelementsinsortedorder:"))n=len(L)
element=int(input("Entertheelementthatyouwanttosearch:"))foun
d=Binary_Search(L,element,0,n-1)
iffound>=0:
print(element,"Foundattheindex:",found)else:
print("Elementnotpresentinthelist")

5.7 lambdaFunction:

lambdakeyword,isusedtocreateanonymousfunctionwhichdoesn’thaveanyname.

Whilenormalfunctionsaredefinedusingthedefkeyword,inPythonanonymousfunctionsaredefinedusin
gthe lambdakeyword.

Syntax:

lambdaarguments:expression
Lambda functions can have any number of arguments but only one expression. The
expressionisevaluatedandreturned.Lambdafunctionscanbeusedwhereverfunctionobjectsarerequi
red.

Example:

value=lambdax:x*4pri
nt(value(6))Output:
24
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x
*4isthe expression thatgetsevaluated andreturned.

ProgramsrelatedtoFunctionsinPythontopic:
1. Write a python program to sum the sequence given below. Take the input n from
theuser.
1 1 1 1
1+ + + +⋯
1! +3! 𝑛!
Solution: 2!
def
fact(x):j
=1res=1
while
j<=x:res
=res*jj=j
+1returnr
es
n=int(input("enter the number :
"))i=1
sum=1whil
ei<=n:
f=fact(i)sum=
sum+1/fi+=1
print(sum)

2. WriteaprogramtocomputeGCDand LCMoftwonumbers
defgcd(x,y):
while(y):
x, y = y, x %
yreturnx
deflcm(x,y):
lcm =
(x*y)//gcd(x,y)return
lcm

num1 = int(input("Enter first number:


"))num2=int(input("Entersecondnumber:"))

print("TheL.C.M.of",num1,"and",num2,"is",lcm(num1,num2))
print("TheG.C.D.of",num1,"and",num2,"is",gcd(num1,num2))
CHAPTER-
6STRINGINPYTHO
N

6.1 Introduction:
Definition:Sequenceofcharactersenclosedinsingle,doubleortriplequotationmarks.
BasicsofString:
 Stringsareimmutableinpython.Itmeansitisunchangeable.Atthesamememoryaddress,thene
wvalue cannotbe stored.

 Eachcharacterhas itsindex orcanbeaccessedusing itsindex.

 Stringinpythonhastwo-wayindexforeachlocation.(0,1,2,…….Intheforwarddirectionand -
1,-2,-3,.....................................inthe backwarddirection.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1

 The index of string in forward direction starts from 0 and in backward direction
startsfrom-1.
 The size of string is total number of characters present in the string. (If there are
ncharacters in the string, then last index in forward direction would be n-1 and last
indexinbackwarddirectionwouldbe–n.)

 Stringarestored eachcharacterin contiguouslocation.


 Thecharacterassignmentisnotsupportedinstringbecausestringsareimmutable.Exam
ple:
str=“kendriya”
str[2]=‘y’ #itisinvalid.Individualletterassignmentnotallowedinpython

6.2 TraversingaString:
Access the elements of string, one character at a
time.str=“kendriya”
forch instr:
print(ch,end=‘‘)
Output:
kendriya

6.3 StringOperators:
a. BasicOperators (+,*)
b. MembershipOperators(in,notin)
c. Comparison Operators(==,!=,<,<=,>,>=)

a. BasicOperators:Therearetwobasicoperatorsofstrings:
i. StringconcatenationOperator(+)
ii. StringrepetitionOperator(*)

i. StringconcatenationOperator:The+operatorcreates anewstring
byjoiningthetwooperandstrings.
Example:
>>>”Hello”+”Python”‘Hello
Python’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’

Note:Youcannotconcatenumbersandstringsasoperandswith+operator.Exampl
e:
>>>7+’4’ #unsupportedoperandtype(s)for+:'int'and'str'It
isinvalidand generatesan error.
ii. StringrepetitionOperator:Itisalsoknownas Stringreplicationoperator.Itrequirestwo
typesofoperands-a stringandan integernumber.
Example:
>>>”you” *
3‘youyouyou

>>>3*”you”
‘youyouyou’

Note:You cannot have strings as n=both the operands with *


operator.Example:
>>>”you”* “you” # can't multiply sequence by non-int of type
'str'It isinvalidandgenerates an error.

b. MembershipOperators:
in– ReturnsTrueif acharacterorasubstringexistsinthegivenstring;otherwiseFalse
notin -Returns Trueif acharacterorasubstringdoes notexist inthegiven string;otherwiseFalse

Example:
>>> "ken" in "Kendriya
Vidyalaya"False
>>>"Ken" in
"KendriyaVidyalaya"True
>>>"yaV"in"KendriyaVidyalaya"Tr
ue
>>>"8765"notin"9876543"
False

c. ComparisonOperators:Theseoperatorscomparetwostringscharacterbycharacteraccording
totheir ASCII value.
Characters ASCII(Ordinal)Value

‘0’to ‘9’ 48to57

‘A’to ‘Z’ 65to90

‘a’to ‘z’ 97to122

Example:
>>>
'abc'>'abcD'Fals
e
>>>'ABC'<'abc'
True
>>>
'abcd'>'aBcD'True
>>>'aBcD'<='abCd'
True

6.4 FindingtheOrdinalorUnicodevalueofacharacter:
Function Description
ord(<character>) Returnsordinalvalueofacharacter

chr(<value>) Returnsthecorrespondingcharacter

Example:
>>>
ord('b')98
>>>
chr(65)'A'
Program: Write a program to display ASCII code of a character and vice
versa.var=True
whilevar:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\
n"))if choice==1:

ch=input("Enter a character :
")print(ord(ch))
elifchoice==2:
val=int(input("Enteranintegervalue:"))print(chr(val))
else:
print("Youenteredwrongchoice")

print("Do you want to continue?


Y/N")option=input()
if option=='y' or
option=='Y':var=True
else:
var=False

6.5 SliceoperatorwithStrings:
Thesliceoperatorslicesastringusingarangeofindices.
Syntax:
string-name[start:end]
wherestartandendareintegerindices.Itreturns astring fromtheindexstarttoend-1.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
d a t a s t r u c t u r e
-14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
>>>str="datastructure"
>>>str[0:14]
'datastructure'
>>>str[0:6]
'data s'
>>>str[2:7]
'tast'
>>>str[-13:-6]
'atastr'
>>>str[-5:-11]
'' #returnsemptystring
>>>str[:14] # Missing index before colon is considered as
0.'datastructure'
>>>str[0:] # Missing index after colon is considered as 14. (length of
string)'datastructure'
>>>
str[7:]'ruct
ure'
>>>
str[4:]+str[:4]'stru
cturedata'
>>>str[:4]+str[4:] #for any index str[:n]+str[n:] returns original
string'datastructure'
>>>
str[8:]+str[:8]'uctu
redatastr'
>>>str[8:],str[:8]
('ucture','datastr')
Sliceoperatorwith stepindex:
Sliceoperatorwithstringsmayhavethird index.Whichisknownasstep.Itisoptional.
Syntax:
string-name[start:end:step]
Example:
>>>str="datastructure"
>>>str[2:9:2]
't tu'
>>>str[-11:-3:3]
'atc'
>>>str[::-1] # reverses a
string'erutcurts atad'

InterestingFact:Indexoutofboundscauseserrorwithstringsbutslicingastringoutsidetheindex
doesnotcauseanerror.
Example:
>>>str[14]
IndexError:stringindexoutofrange
>>>str[14:20] # both indices are outside the
bounds' ' # returnsemptystring
>>>str[10:16]
'ture'

Reason:Whenyouuseanindex,youareaccessingaparticularcharacterofastring,thustheindex
must be valid and out of bounds index causes an error as there is no character to
returnfromthe givenindex.
Butslicingalwaysreturnsasubstringoremptystring,whichisvalidsequence.

6.6 Built-
infunctionsofstring:Example:
str=”datastructure”
s1=
“hello365”s2=
“python”s3=
‘4567’
s4= ‘‘
s5=‘comp34%@’
S.No. Function Description Example
1 len() Returnsthe length of astring >>>print(len(str))
14
2 capitalize() Returns a string with its first character >>>str.capitalize()
capitalized. 'Datastructure'
3 find(sub,start,end) Returnsthelowestindexinthestringwherethesubstrin >>>str.find("ruct",5,13)
gsubis found withinthe slicerange. 7
Returns-1ifsub isnotfound. >>>str.find("ruct",8,13)
-1
4 isalnum() ReturnsTrueifthecharactersinthestringarealphabetso >>>s1.isalnum()
r numbers.Falseotherwise True
>>>s2.isalnum()
True
>>>s3.isalnum()
True
>>>s4.isalnum()
False
>>>s5.isalnum()
False
5 isalpha() ReturnsTrueifallcharactersinthestringarealphabetic. >>>s1.isalpha( )
Falseotherwise. False
>>>s2.isalpha( )
True
>>>s3.isalpha()
False
>>>s4.isalpha()
False
>>>s5.isalpha()
False
6 isdigit() ReturnsTrueifallthecharactersinthestringaredigits. >>>s1.isdigit( )
Falseotherwise. False
>>>s2.isdigit( )
False
>>>s3.isdigit( )
True
>>>s4.isdigit( )
False
>>>s5.isdigit( )
False
7 islower() ReturnsTrueifallthecharactersinthestringarelowerc >>>s1.islower()
ase.Falseotherwise. True
>>>s2.islower()
True
>>>s3.islower()
False
>>>s4.islower()
False
>>>s5.islower()
True
8 isupper() ReturnsTrueifallthecharactersinthestringareupperc >>>s1.isupper()
ase.Falseotherwise. False
>>>s2.isupper()
False
>>>s3.isupper()
False
>>>s4.isupper()
False
>>>s5.isupper()
False
9 isspace() Returns True if there are only >>>"".isspace()Tr
whitespacecharactersin ue
thestring.Falseotherwise. >>>"".isspace()
False
10 lower() Convertsastringinlowercase characters. >>>"HeLlo".lower()
'hello'
11 upper() Convertsastringinuppercase characters. >>>"hello".upper()
'HELLO'
12 lstrip() Returns a string after removing the >>>str="datastructure"
leadingcharacters.(Left side). >>>
ifusedwithoutanyargument,itremovestheleadingwhit str.lstrip('dat')'stru
espaces. cture'
>>>str.lstrip('data')'
structure'
>>>
str.lstrip('at')'data
structure'
>>>
str.lstrip('adt')'stru
cture'
>>>
str.lstrip('tad')'stru
cture'
13 rstrip() Returns a string after removing the >>>str.rstrip('eur')'
trailingcharacters.(Right side). datastruct'
ifusedwithoutanyargument,itremovesthetrailingwhit >>>str.rstrip('rut')'
espaces. datastructure'
>>>str.rstrip('tucers')'
data '
14 split() breaksastringintowords andcreates alistout ofit >>>str="DataStructure"
>>> str.split( )
['Data','Structure']
ProgramsrelatedtoStrings:
1. Writeaprogramthattakesastringwithmultiplewordsandthencapitalizethefirstletterof
eachwordandformsa new stringoutof it.
Solution:
s1=input("Enter a string :
")length=len(s1)
a=0end=le
ngth
s2="" #empty
stringwhilea<length:
if a==0:
s2=s2+s1[0].upper()
a+=1
elif (s1[a]==' 'and s1[a+1]!
=''):s2=s2+s1[a]s2=s2+s1[a
+1].upper()a+=2
else:
s2=s2+s1[a]
a+=1
print("Original string : ",
s1)print("Capitalizedwrdsstring:",s2)

2. Writeaprogramthatreads astringandchecks whetheritisa palindromestringornot.


str=input("Enter a string :
")n=len(str)
mid=n//
2rev=-1
for i in
range(mid):ifstr[i
]==str[rev]:
i=i+1rev
=rev-1
else:
print("Stringisnotpalindrome")b
reak
else:
print("Stringispalindrome")

3. Write a program to convert lowercase alphabet into uppercase and vice


versa.choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in
uppercase\n"))str=input("Enterastring:")
if
choice==1:s1
=str.lower()pr
int(s1)
elif
choice==2:s1
=str.upper()pr
int(s1)
else:
print("Invalidchoiceentered")
CHAPTER-
7LISTINPYTHON

7.1 Introduction:

 Listisacollectionofelementswhichisorderedandchangeable(mutable).
 Allowsduplicatevalues.
 Alistcontainsitemsseparatedbycommasandenclosedwithinsquarebrackets([]).
 Allitemsbelongingtoalistcanbeofdifferentdatatype.
 Thevaluesstoredinalistcanbeaccessedusingthesliceoperator([]and[:])withindexes
startingat0 inthe beginningofthe list.

Differencebetweenlistandstring:

List String
Mutable Immutable
Elementcanbeassignedatspecified Element/character cannot be
index assignedatspecifiedindex.
Example: Example:

>>>L=[7,4,8,9] >>>str=“python”

>>>L[2]=6 #valid >>>str[2]=‘p’ #error

7.2 Creatingalist:

To create a list enclose the elements of the list within square brackets and separate
theelementsbycommas.

Syntax:

list-name=[item-1,item-2,.............,item-n]

Example:

mylist=["apple","banana","cherry"]

#alistwiththreeitemsL=[ ] #an emptylist

7.2.1 Creatingalistusinglist()Constructor:

oItis alsopossibletousethelist()constructorto makealist.


mylist=list(("apple","banana","cherry")) #note the double round-
bracketsprint(mylist)

L=list() #creating emptylist

7.2.2 NestedLists:

>>>L=[23,'w',78.2,[2,4,7],[8,16]]

>>> L

[23,'w',78.2, [2,4,7],[8,16]]

7.2.3 Creating alistby taking input fromtheuser:

>>>List=list(input("entertheelements:"))ent

ertheelements: hellopython

>>>List

['h','e','l','l','o',' ','p', 'y','t','h','o','n']

>>> L1=list(input("enter the elements:

"))enterthe elements: 678546

>>> L1

['6','7','8','5','4','6'] #ittreats elementsasthe characters thoughweentereddigits

Toovercometheaboveproblem,wecanuseeval()method,whichidentifiesthedatatype
andevaluate themautomatically.

>>>L1=eval(input("entertheelements:"))en

terthe elements: 654786

>>> L1

654786 # itis aninteger,not alist

>>>L2=eval(input("entertheelements:"))
entertheelements:[6,7,8,5,4,3] #forlist,you must enterthe[]bracket

>>> L2

[6,7, 8,5, 4,3]

Note:Witheval()method,Ifyouenterelementswithoutsquarebracket[],itwillbeconsidered as
atuple.

>>>L1=eval(input("entertheelements:"))en

tertheelements: 7,65,89,6,3,4

>>> L1

(7,65,89,6,3,4) #tuple

7.3 Accessinglists:

 Thevaluesstoredinalistcanbeaccessedusingthesliceoperator([]and[:])withindexes.
 List-name[start:end]willgiveyouelementsbetweenindicesstarttoend-1.
 Thefirstiteminthelisthasthe indexzero(0).

Example:
>>>number=[12,56,87,45,23,97,56,27]

Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
BackwardIndex

>>>
number[2]87
>>> number[-
1]27
>>> number[-
8]12
>>>number[8]
IndexError:listindexoutofrange
>>>number[5]=55 #Assigningavalueatthespecifiedindex
>>>number
[12,56,87,45,23,55, 56,27]

7.4 TraversingaLIST:

Traversingmeansaccessingandprocessingeachelement.

Method-1:

>>> day=list(input("Enter
elements :"))Enterelements:sunday
>>>fordin day:
print(d)

Output:
s
u
n
d
a
y

Method-2
>>> day=list(input("Enter
elements :"))Enterelements:wednesday
>>> for i in
range(len(day)):print(
day[i])

Output:
w
e
d
n
e
s
d
a
y

7.5 ListOperators:

 Joiningoperator +
 Repetitionoperator *
 Sliceoperator [:]
 ComparisonOperator <, <=, >, >=, ==,!=
 Joining Operator: It joins two or more

lists.Example:

>>>L1=['a',56,7.8]

>>>L2=['b','&',6]

>>>L3=[67,'f','p']

>>>L1+L2+L3

['a',56,7.8,'b','&',6, 67, 'f','p']

 Repetition Operator: It replicates a list specified number of

times.Example:

>>>L1*3

['a',56,7.8,'a',56,7.8, 'a',56,7.8]

>>>3*L1

['a',56,7.8,'a',56,7.8, 'a',56,7.8]

 SliceOperator:

List-name[start:end]willgiveyouelementsbetweenindicesstarttoend-1.

>>>number=[12,56,87,45,23,97,56,27]

>>> number[2:-2]

[87,45,23,97]

>>> number[4:20]

[23,97,56,27]

>>> number[-1:-6]

[]

>>> number[-6:-1]

[87,45,23,97,56]
>>> number[0:len(number)]

[12,56,87,45,23,97, 56,27]

List-name[start:end:step]willgiveyouelementsbetweenindicesstarttoend-1withskipping
elementsasper thevalueofstep.

>>> number[1:6:2]

[56,45,97]

>>> number[: :-1]

[27,56,97,23,45,87, 56,12] #reversesthelist

Listmodificationusingsliceoperator:

>>>number=[12,56,87,45,23,97,56,27]

>>>number[2:4]=["hello","python"]

>>>number

[12,56,'hello','python',23,97,56,27]

>>>number[2:4]=["computer"]

>>>number

[12,56,'computer',23,97,56,27]

Note:Thevaluesbeingassignedmustbeasequence(list,tupleorstring)

Example:

>>>number=[12,56,87,45,23,97,56,27]

>>>number=[12,56,87,45,23,97,56,27]

>>>number[2:3]=78 # 78 is a number, not a

sequenceTypeError: canonlyassignaniterable
 ComparisonOperators:

o Comparestwolists
o Pythoninternallycomparesindividualelementsoflistsinlexicographicalorder.
o It compares the each corresponding element must compare equal and
twosequences mustbe ofthesame type.
o For non-equal comparison as soon as it gets a result in terms of
True/False,fromcorrespondingelements’comparison.IfCorrespondingelementsa
reequal,itgoestothenextelement andsoon,until it finds elementsthatdiffer.

Example:

>>>L1,L2=[7,6,9],[7, 6, 9]

>>>L3 =[7,[6,9]]

ForEqualComparison:

Comparison Result Reason


>>>L1==L2 True Correspondingelementshavesamevalueandsame
type
>>>L1==L3 False Correspondingvaluesarenotsame

ForNon-equalcomparison:

Comparison Result Reason


>>>L1>L2 False Allelementsareequal
>>>L2>L3 TypeError:'>'notsuppo in L2, element at the index 1 is int
rtedbetweeninstanceso typeand in L3 element at the index 1 is
f'int'and'list'
listtype

>>>[3,4,7,8]<[5,1] True 3<5 is True


>>>[3,4,7,8]<[3,4,9,2] True Firsttwoelementsaresamesomovetonex
telement and7<9 isTrue

>>>[3,4,7,8]<[3,4,9,11] True 7<9 is True


>>>[3,4,7,8]<[3,4,7,5] False 8<5is False
ListMethods:

Consideralist:

company=["IBM","HCL","Wipro"]

S. Function
Description Example
No. Name
1 append() Toaddelementtothelistatt >>>company.append("Google")
he end. >>> company
Syntax: ['IBM','HCL','Wipro','Google']
list-name.append(element)
Error:
>>>company.append("infosys","microsoft")

#takesexactlyoneelementTypeError:append()takesexactlyone argument (2
given)
2 extend() Addalist,totheendofthecur >>>company=["IBM","HCL","Wipro"]
rentlist. >>>desktop=["dell","HP"]
Syntax: >>>company.extend(desktop)
list-name.extend(list) >>> company
['IBM','HCL','Wipro','dell','HP']
Error:
>>>company.extend("dell","HP")

#takesonlyalistasargumentTypeError:extend()takes
exactlyoneargument(2given)
3. len() Findthelengthofthelist. >>>company=["IBM","HCL","Wipro"]
Syntax: >>>len(company)
len(list-name) 3
>>>L=[3,6,[5,4]]
>>>len(L)
3

4 index() Returns the index of >>>company=["IBM","HCL","Wipro","HC


thefirstelementwiththespe L","Wipro"]
cified value. >>>company.index("Wipro")
Syntax: 2
list-name.index(element)
Error:
>>>company.index("WIPRO") # Python is case-sensitive
languageValueError: 'WIPRO' isnotin list
>>>company.index(2) # Writetheelement,notindex
ValueError:2isnotinlist
5 insert() Addsanelementatthespecif >>>company=["IBM","HCL","Wipro"]
ied position. >>>company.insert(2,"Apple")
>>> company
Syntax: ['IBM','HCL','Apple','Wipro']
list.insert(index,element)
>>>company.insert(16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']

>>>company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']

6 count() Return the number >>> company = ["IBM", "HCL",


oftimes "Wipro","HCL","Wipro"]
thevalueappears. >>>company.count("HCL")
Syntax: 2
list-name.count(element) >>>company.count("TCS")
0

7 remove() To remove an >>> company = ["IBM", "HCL",


elementfromthe list. "Wipro","HCL","Wipro"]
Syntax: >>>company.remove("Wipro")
list-name.remove(element) >>> company
['IBM','HCL','HCL', 'Wipro']
Error:
>>>
company.remove("Yahoo")ValueError
:list.remove(x):xnotinlist
8 clear( ) Removesalltheelementsfr >>>company=["IBM","HCL","Wipro"]
omlist.
Syntax: >>>company.clear()
list-name.clear()
>>>

company[]
9 pop() Removestheelementatthe >>>company=["IBM","HCL","Wipro"]
specified position >>>
andreturnsthedeletedelem company.pop(1)'HC
ent. L'
Syntax: >>>
list-name.pop(index) company['IBM'
,'Wipro']
Theindexargumentisoptional.I
fnoindexisspecified, pop( )
removes andreturnsthe
>>>
lastitem inthelist. company.pop( )'Wip
ro'
Error:
>>>L=[ ]
>>>L.pop( )
IndexError:pop fromemptylist
10 copy() Returnsacopyof thelist. >>>company=["IBM","HCL","Wipro"]
>>>L=company.copy()
Syntax: >>> L
list-name.copy() ['IBM','HCL','Wipro']
11 reverse( ) Reverses the order of >>>company=["IBM","HCL","Wipro"]
thelist. >>>company.reverse()
Syntax: >>>company['Wipro','
list-name.reverse() HCL','IBM']

Takes no
argument,returnsno
list.
12. sort() Sorts the list. By >>>company=["IBM","HCL","Wipro"]
defaultin ascending >>>company.sort()
order. >>> company
['HCL','IBM','Wipro']
Syntax:
list-name.sort() To sorta listindescending order:

>>>company=["IBM","HCL","Wipro"]
>>>company.sort(reverse=True)
>>>company['Wipro','
IBM','HCL']
Deletingtheelementsfromthelistusingdelstatement:Synt

ax:

dellist-name[index] # to remove element at specified

indexdellist-name[start:end] #toremove

elementsinlistslice

Example:

>>>L=[10,20,30,40,50]

>>>del L[2] #deletetheelementattheindex2

>>>L

[10,20,40,50]

>>>L=[10,20,30,40,50]

>>>delL[1:3] # deleteselementsoflistfromindex 1to 2.

>>>L

[10,40,50]

>>>del L #deletesallelementsandthelistobjecttoo.

>>>L

NameError:name'L'isnotdefined
Differencebetweendel,remove(),pop(),clear():

S.
del remove() pop( ) clear()
No.

1 Statement Function Function Function

Deletes a single Removesthefirst Removes


Removes all
2 elementor a list slice or matching anindividualiteman
theelementsfromli
completelist. itemfromthe list. dreturns it.
st.
Removesallelementsa Removes
3 nddeleteslistobject allelementsbutlist
too. objectstillexists.

Differencebetweenappend(),extend( )andinsert( ):

S.
append( ) extend( ) insert( )
No.
Addsanelementatthe
Addssingleelementintheendoft Add alistinthe specified position.
1
helist. endoftheanotherlist
(Anywhereinthelist)
Takes one list Takes two
2 Takesoneelement asargument
asargument arguments,positionan
delement.
The length of the
The length of the list The length of the
3 listwill increase by
willincreaseby1. listwillincreaseby1.
thelengthofinsertedlis
t.

ACCESSINGELEMENTS OFNESTEDLISTS:
Example:
>>>L=["Python","is","a",["modern","programming"],"language","that","we","use"]
>>> L[0]
[0]'P'
>>>L[3][0][2]
'd'
>>>L[3:4][0]
['modern','programming']
>>>L[3:4][0][1]
'programming'
>>>L[3:4][0][1][3]
'g'
>>>L[0:9][0]
'Python'
>>>L[0:9][0][3]
'h'
>>>L[3:4][1]
IndexError:listindexoutofrange

Programsrelatedtolistsinpython:
Program-1Writeaprogramto findtheminimumand maximumnumberin alist.

L=eval(input("Enter the elements:


"))n=len(L)
min=L[0]
max=L[0]
for i in
range(n):ifmi
n>L[i]:
min=L[i]i
fmax<L[i]:
max=L[i]

print("The minimum number in the list is : ",


min)print("Themaximumnumberinthelistis:",max)
Program-2 Find the second largest number in a
list.L=eval(input("Enterthe elements: "))
n=len(L)max=sec
ond=L[0]foriin
range(n):
if
max<L[i]>second
:max=L[i]seond=
max

print("Thesecondlargestnumberinthelistis:",second)

Program-3:Programtosearchan element in alist.(LinearSearch).

L=eval(input("Enter the elements:


"))n=len(L)
item=eval(input("Entertheelementthatyouwanttosearch:"))foriin
range(n):
ifL[i]==item:
print("Element found at the position :",
i+1)break
else:
print("ElementnotFound")

Output:
Entertheelements:56,78,98,23,11,77,44,23,65Enter
the element that you want to search : 23Element
foundattheposition:4
CHAPTER-
8TUPLEINPYTHO
N

8.1 INTRODUCTION:

 Tuple is a collection of elements which is ordered and unchangeable


(Immutable).Immutablemeansyou cannotchangeelementsofatupleinplace.
 Allowsduplicatemembers.
 Consiststhevaluesofanytype,separatedbycomma.
 Tuplesareenclosedwithinparentheses().
 Cannotremovetheelementfromatuple.

8.2 CreatingTuple:

Syntax:

tuple-name=() #emptytuple

tuple-name=(value-1,value-2,..............., value-n)

Example:

>>>T=(23,7.8,64.6,'h','say')

>>> T

(23,7.8,64.6,'h','say')

8.2.1 Creatingatuplewithsingleelement:

>>> T=(3) #Withasingleelementwithoutcomma,itisavalueonly,notatuple

>>>

T3

>>>T= (3,) # toconstructatuple,addacomma afterthesingleelement

>>>
T(3,)
>>> T1=3, #Italsocreatesatuplewithsingleelement

>>>

T1(3,)

8.2.2 Creatingatupleusingtuple()constructor:

oItis alsopossibletousethetuple()constructorto createatuple.

>>>T=tuple() #emptytuple

>>>T=tuple((45,3.9,'k',22)) #notethedoubleround-brackets
>>> T
(45,3.9, 'k',22)

>>>T2=tuple('hello')#forsingleround-bracket,theargument mustbeofsequencetype
>>> T2
('h','e','l','l','o')

>>>T3=('hello','python')
>>> T3
('hello','python')

8.2.3 NestedTuples:

>>>T=(5,10,(4,8))

>>> T

(5,10, (4,8))

8.2.4 Creating a tupleby taking inputfromtheuser:

>>> T=tuple(input("enter the elements:

"))entertheelements: hello python

>>> T
('h','e','l','l','o',' ','p', 'y','t','h','o','n')

>>>T1=tuple(input("entertheelements:"))en

terthe elements:45678

>>> T1

('4','5','6','7','8') #ittreatselementsasthecharactersthough weentereddigits

Toovercometheaboveproblem,wecanuseeval()method,whichidentifiesthedatatype
andevaluate themautomatically.

>>>T1=eval(input("entertheelements:"))en

terthe elements:56789

>>> T1

56789 # it isnota list,itis an integervalue

>>>type(T1)

<class'int'>

>>>T2=eval(input("entertheelements:"))

entertheelements: (1,2,3,4,5) #Parenthesisisoptional

>>> T2

(1,2, 3,4, 5)

>>>T3=eval(input("entertheelements:"))

entertheelements: 6,7,3,23,[45,11] # listasan elementoftuple

>>> T3

(6,7,3,23,[45,11])
8.3 AccessingTuples:

Tuplesareverymuchsimilartolists.Likelists,tupleelementsarealsoindexed.Forwardindexin
gas0,1,2,3,4………andbackwardindexingas-1,-2,-3,-4,………

 Thevaluesstored ina tuplecanbeaccessed usingthesliceoperator([]and[:])withindexes.


 tuple-name[start:end]willgiveyouelementsbetweenindices starttoend-1.
 Thefirstitemin thetuplehastheindexzero (0).

Example:

>>>alpha=('q','w','e','r','t','y')

Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
BackwardIndex

>>>
alpha[5]'y'
>>> alpha[-
4]'e'
>>>alpha[46]
IndexError:tupleindexoutofrange
>>>alpha[2]='b'

#can’tchangevalueintuple,thevaluewillremainunchangedTypeError:
'tuple'objectdoesnot supportitemassignment

8.3.1DifferencebetweenListandTuple:

S.No. List Tuple

1 Orderedandchangeable(Mutable) Orderedbutunchangeable(Immutable)

2 Listsareenclosedinbrackets. [] Tuplesareenclosedinparentheses.()
3 Elementcanberemoved. Elementcan’tberemoved.
8.4 TraversingaTuple:

Syntax:

for<variable>intuple-

name:statement

Example:

Method-1

>>>alpha=('q','w','e','r','t','y')
>>>foriinalpha:
print(i)

Output:
q
w
e
rt
y

Method-2
>>>fori in range(0,len(alpha)):
print(alpha[i])

Output:
q
w
e
rt
y

8.5 TupleOperations:

 Joiningoperator +
 Repetitionoperator *
 Sliceoperator [:]
 ComparisonOperator <, <=, >, >=, ==,!=
 Joining Operator: It joins two or more

tuples.Example:

>>>T1=(25,50,75)
>>>T2=(5,10,15)
>>>T1+T2
(25,50,75,5,10, 15)

>>> T1+ (34)


TypeError:canonlyconcatenatetuple(not "int")totuple

>>> T1+ (34,)

(25,50,75,34)

 Repetition Operator: It replicates a tuple, specified number of

times.Example:

>>>T1*2

(25,50,75,25,50,75)

>>>T2=(10,20,30,40)

>>>T2[2:4]*3

(30,40,30,40,30,40)

 SliceOperator:

tuple-name[start:end]willgiveyouelementsbetweenindicesstarttoend-1.

>>>alpha=('q','w','e','r','t','y')

>>> alpha[1:-3]

('w','e')

>>> alpha[3:65]

('r','t','y')

>>>alpha[-1:-5]
()

>>> alpha[-5:-1]

('w','e','r','t')

List-name[start:end:step]willgiveyouelementsbetweenindicesstarttoend-1withskipping
elementsasper thevalueofstep.

>>> alpha[1:5:2]

('w','r')

>>>alpha[ : :-1]

('y', 't','r','e','w','q') #reversesthetuple

 ComparisonOperators:

o Comparetwotuples
o Python internally compares individual elements of tuples in
lexicographicalorder.
o It compares the each corresponding element must compare equal and
twosequences mustbe ofthesame type.
o For non-equal comparison as soon as it gets a result in terms of
True/False,fromcorrespondingelements’comparison.IfCorrespondingelementsa
reequal,itgoestothenextelement andsoon,until it finds elementsthatdiffer.

Example:

>>>T1=(9,16,7)
>>>T2=(9,16,7)
>>>T3=('9','16','7')
>>>T1 ==T2
True
>>>T1==T3
False
>>> T4 =(9.0, 16.0,7.0)
>>>T1==T4
True
>>>T1<T2
https://pythonschoolkvs.wordpress.com/ Page
101
False
>>>T1<=T2
True

8.6 TupleMethods:

Consideratuple:

subject=("Hindi","English","Maths","Physics")

S. Function
No.
Description Example
Name
1 len() Findthelength ofatuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>>
len(tuple-name) len(subject)4
2 max() Returnsthelargestvaluefro >>>
matuple. max(subject)'Phy
Syntax: sics'
max(tuple-name)
Error:

Ifthetuplecontainsvaluesofdifferentdatatypes,thenitwillgiveanerrorbecausemixeddatatype
comparisonisnot possible.

>>>subject=(15,"English","Maths","Physics",48.2)
>>>max(subject)
TypeError:'>'notsupportedbetweeninstancesof 'str'and'int'
3. min() Returns the >>>subject=("Hindi","English","Maths","Physics")

smallestvalue >>>
fromatuple.
Syntax: min(subject)'Eng
min(tuple-name)
lish'
Error:

Ifthetuplecontainsvaluesofdifferentdatatypes,thenitwillgiveanerrorbecausemixeddatatype
comparisonisnotpossible.

>>>subject=(15,"English","Maths","Physics",48.2)
>>>min(subject)
TypeError:'>'notsupportedbetweeninstancesof 'str'and'int'

Page
102
4 index() Returns the index of >>>subject=("Hindi","English","Maths","Physics")

thefirstelementwiththespe
cified value.
Syntax:

Page
103
tuple- >>>subject.index("Maths")
name.index(element)
2
5 count() Return the number >>>
oftimes
thevalueappears. subject.count("English")1
Syntax:
tuple-
name.count(element)

8.7 TuplePackingandUnpacking:

TuplePacking:Creatingatuplefromset ofvalues.

Example:

>>>T=(45,78,22)
>>> T
(45,78,22)

TupleUnpacking:Creatingindividualvaluesfromtheelementsoftuple.

Example:

>>> a, b,c=T
>>>
a45
>>>
b78
>>>
c22

Note:Tupleunpackingrequiresthatthenumberofvariableontheleftsidemustbeequaltothe
lengthofthe tuple.

8.8 Deletea tuple:

Thedelstatementisusedtodeleteelementsandobjectsbutasyouknowthattuplesareimmutable,whicha
lso means thatindividual element ofatuplecannot bedeleted.

Page
104
Example:

>>T=(2,4,6,8,10,12,14)

>>> delT[3]

TypeError:'tuple'objectdoesn'tsupportitemdeletion

Butyoucandeleteacompletetuplewithdelstatementas:

Example:

>>>T=(2,4,6,8,10,12,14)

>>> delT

>>> T

NameError:name'T'isnotdefined

Page
105
CHAPTER-
9DICTIONARYINPYTHO
N

9.1 INTRODUCTION:

 Dictionaryisacollectionofelements whichisunordered,changeableandindexed.
 Dictionaryhas keys andvalues.
 Doesn’thaveindexforvalues. Keysworkasindexes.
 Dictionarydoesn’thaveduplicatemembermeansnoduplicatekey.
 Dictionariesareenclosedbycurlybraces{}
 Thekey-valuepairsareseparated bycommas (,)
 AdictionarykeycanbealmostanyPythontype,butareusuallynumbersorstrings.

 Valuescanbeassignedandaccessedusingsquarebrackets[].

9.2 CREATINGADICTIONARY:

Syntax:

dictionary-name={key1:value,key2:value,key3:value,keyn:value}

Example:

>>>marks ={"physics": 75,"Chemistry" : 78,"Maths": 81,"CS":78 }

>>>marks

{'physics':75,'Chemistry':78,'Maths':81,'CS':78}

>>> D= {} #Empty dictionary

>>> D

{}

>>>marks ={"physics": 75,"Chemistry" : 78,"Maths": 81,"CS":78 }

{'Maths':81,'Chemistry':78,'Physics':75,'CS':78}

Page
106
#thereisnoguaranteethat#elements indictionarycanbeaccessed

asperspecificorder.

Page
107
Note: Keys of a dictionary must be of immutable types, such as string, number,

tuple.Example:

>>>D1={[2,3]:"hello"}

TypeError:unhashabletype:'list'

Creatingadictionary usingdict()Constructor:

A. usethedict()constructorwithsingleparentheses:

>>>marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

 In the above case the keys are not enclosed in quotes and equal sign is
usedforassignment rather than colon.

B. dict()constructorusingparenthesesandcurly braces:

>>>marks=dict({"Physics":75,"Chemistry":78,"Maths":81,"CS":78})

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

C. dict()constructorusing keys andvalues separately:

>>>marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

Page
108
In this case the keys and values are enclosed separately in parentheses and are given
asargumenttothezip()function.zip()function clubsfirstkeywithfirst valueandsoon.

D. dict( ) constructor using key-value pairs

separately:Example-a

>>>marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
#listasargumentpassedtodict()constructorcontainslisttypeelements.

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

Example-b

>>>marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))

#tupleasargumentpassedtodict()constructorcontainslisttypeelements

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

Example-c

>>>marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))

#tupleasargumenttodict()constructorandcontainstupletypeelements

>>>marks

{'Physics':75,'Chemistry': 78,'Maths':81,'CS':78}

Page
109
9.3 ACCESSINGELEMENTSOFADICTIONARY:

Syntax:

dictionary-name[key]

Example:

>>>marks ={"physics": 75,"Chemistry":78,"Maths": 81,"CS":78 }

>>>marks["Maths"]

81

>>>marks["English"] #Access akeythat doesn’texist causes anerror

KeyError:'English'

>>>marks.keys() #To access all keys in one

godict_keys(['physics','Chemistry','Maths','CS'])

>>>marks.values() # To accessall values

inonegodict_values([75,78,81,78])

Lookup:Adictionaryoperationthattakesakeyandfindsthecorrespondingvalue,iscalled

lookup.

9.4 TRAVERSINGADICTIONARY:

Syntax:

for <variable-name> in <dictionary-

name>:statement

Page
110
Example:

>>>foriin marks:

print(i,":",marks[i])

OUTPUT:

physics :75

Chemistry: 78

Maths: 81

CS:78

9.5 CHANGEANDADDTHEVALUEINADICTIONARY:Syn

tax:

dictionary-name[key]=value

Example:

>>>marks ={"physics": 75,"Chemistry" : 78,"Maths": 81,"CS":78 }

>>>marks

{'physics':75,'Chemistry': 78,'Maths':81,'CS':78}

>>>marks['CS']=84 #Changing avalue

>>>marks

{'physics':75,'Chemistry': 78,'Maths':81,'CS':84}

>>>marks['English']=89 #Adding avalue

>>>marks

{'physics':75,'Chemistry':78,'Maths':81,'CS':84,'English':89}

Page
111
9.6 DELETEELEMENTSFROMADICTIONARY:

Therearetwomethodstodeleteelementsfromadictionary:

(i) usingdelstatement

(ii) usingpop()method

(i) Usingdelstatement:

Syntax:

deldictionary-name[key]

Example:

>>>marks

{'physics':75,'Chemistry':78,'Maths':81,'CS':84,'English':89}

>>>delmarks['English']

>>>marks

{'physics':75,'Chemistry': 78,'Maths':81,'CS':84}

(ii) Usingpop()method:Itdeletesthekey-valuepairandreturnsthevalueofdeletedelement.

Syntax:

dictionary-

name.pop( )Example:

>>>marks

{'physics':75,'Chemistry': 78,'Maths':81,'CS':84}

>>>

marks.pop('Maths')81

Page
112
9.7 CHECKTHEEXISTANCEOFAKEYINADICTIONARY:

Tochecktheexistenceofakeyin dictionary,twooperators areused:

(i) in:it returns Trueifthegiven keyispresentinthedictionary,otherwiseFalse.

(ii) notin:it returnsTrueifthegivenkeyisnotpresentin thedictionary,otherwise

False.

Example:

>>>marks ={"physics": 75,"Chemistry" : 78,"Maths": 81,"CS":78 }

>>> 'Chemistry' in

marksTrue

>>>'CS'notinmarksFa

lse

>>>78 in marks # in and not in only checks the existence of keys not

valuesFalse

However,ifyouneedtosearchforavalueindictionary,thenyoucan useinoperatorwith the


followingsyntax:

Syntax:

valueindictionary-name.values()

Example:

>>>marks ={"physics":75,"Chemistry":78,"Maths":81,"CS":78 }

>>> 78 in

marks.values( )True

9.8 PRETTYPRINTINGADICTIONARY:

WhatisPrettyPrinting?

Page
113
Toprintadictionaryinmorereadableandpresentableform.

Forprettyprinting adictionaryyou needtoimportjsonmoduleandthenyou canuse

dumps()functionfromjsonmodule.

Example:

>>>print(json.dumps(marks,indent=2))

OUTPUT:

"physics":75,

"Chemistry":78,

"Maths":81,

"CS":78

dumps()functionprintskey:valuepairinseparatelineswiththenumberofspaceswhich

isthevalueofindent argument.

9.9 COUNTINGFREQUENCYOFELEMENTSIN ALISTUSINGDICTIONARY

Steps:

1. importthejsonmoduleforprettyprinting
2. Takeastring fromuser
3. Createalistusingsplit()function
4. Createanemptydictionarytoholdwordsandfrequency
5. Nowmake thewordas akeyonebyonefromthe list
6. Ifthekeynotpresentinthedictionarythen addthekeyin dictionaryand count
7. Printthedictionarywithfrequencyofelementsusingdumps()function.

Page
114
Program:

import

jsonsentence=input("Enter a

string: ")L=sentence.split()

d={}

for word in

L:key=wor

if key not in

d:count=L.count(ke

y)d[key]=count

print("Thefrequqencyofelementsinthelistisasfollows:")print(json.dumps(d,indent=2))

9.10 DICTIONARYFUNCTIONS:

Consideradictionarymarksasfollows:

>>>marks ={"physics":75,"Chemistry":78,"Maths":81,"CS":78 }

S. Function
No.
Description Example
Name
1 len() Find the length of >>>
adictionary.
Syntax: len(marks)4
len(dictionary-name)
2 clear( ) removes all >>>marks.clear()
elementsfrom
the dictionarySyntax: >>>marks
dictionary-name.clear()
{}

Page
115
3. get( ) Returnsvalueofakey. >>>
Syntax:
dictionary-name.get(key) marks.get("physics")75

Note:Whenkeydoesnot existitreturnsnovaluewithoutanyerror.

>>>marks.get('Hindi')

>>>
4 items() returns all elements as >>>marks.items()
asequenceof(key,value)tu
plesinanyorder. dict_items([('physics',75),('Chemistry',
Syntax: 78),('Maths',81),('CS',78)])
dictionary-name.items()
Note:Youcanwritealoophavingtwovariablestoaccesskey:valuepairs.
>>>seq=marks.items()
>>> fori, jinseq:
print(j,i)
OUTPUT:
75physics
78Chemistry
81Maths
78CS
5 keys() Returnsallkeysintheformof >>>marks.keys()
a list.
Syntax: dict_keys (['physics',
dictionary-name.keys() 'Chemistry','Maths','CS'])
6 values() Returnsallvaluesinthefor >>>
mof a list.
Syntax: marks.values()dict_values([
dictionary-name.values()
75,78,81,78])

7 update() Merges two


dictionaries.Already
present
elementsareoverride.
Syntax:
dictionary1.update(dictionary2)

Page
116
Example:
>>>marks1 ={"physics": 75,"Chemistry": 78,"Maths":81,"CS":78}
>>>marks2 ={"Hindi":80,"Chemistry": 88,"English":92 }
>>>marks1.update(marks2)
>>>marks1
{'physics':75,'Chemistry':88,'Maths':81,'CS':78,'Hindi':80,'English':92}

Page
117
Page
118

You might also like