Python Notes For BCA
Python Notes For BCA
1INTRODUTIONTOPYTHON
1.1 Introduction:
General-purposeObjectOrientedProgramming language.
High-levellanguage
Developedinlate1980byGuidovanRossumatNationalResearchInstituteforMathematics
andComputerScience intheNetherlands.
ItisderivedfromprogramminglanguagessuchasABC,Modula3,smalltalk,Algol-68.
ItisOpenSourceScriptinglanguage.
ItisCase-sensitivelanguage(Differencebetweenuppercaseandlowercaseletters).
OneoftheofficiallanguagesatGoogle.
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.
as elif if or yield
Rulesforidentifiers:
3. Literal:Literalsaretheconstantvalue.Literalscanbedefinedasadatathatisgiveninavariable
or constant.
Literal
String LiteralColl
Numeric Boolean Special
ections
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.
E. LiteralCollections: Collectionssuchastuples,listsandDictionaryareusedinPython.
Bitwisecomplementnot
Logicalnegation
B. BinaryOperator:Performsoperationontwooperands.
2.3 MantissaandExponentForm:
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.
2.5 Variable/LabelinPython:
Definition:Namedlocationthat
referstoavalueandwhosevaluecanbeusedandprocessedduringprogramexecution.
Variablesinpythondonothavefixedlocations.Thelocationtheyrefertochangeseverytimetheirvalue
schange.
Creatingavariable:
Avariableiscreatedthemomentyoufirstassign avaluetoit.Example:
x=5
y= “hello”
Variablesdonotneedtobedeclaredwithanyparticulartypeandcanevenchangetypeaftertheyhavebeen
set.Itisknownasdynamic Typing.
RulesforPythonvariables:
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.
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
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'
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
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
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(floor) x//y 3
% Modulus x%y 2
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.
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.
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
| BitwiseOR x|y
~ BitwiseNOT ~x
^ BitwiseXOR x^y
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
.
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.
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
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
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
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")
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.
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):
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:
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.
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))
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
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.
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.)
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’
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
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")
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)
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”
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"]
7.2.1 Creatingalistusinglist()Constructor:
7.2.2 NestedLists:
>>>L=[23,'w',78.2,[2,4,7],[8,16]]
>>> L
[23,'w',78.2, [2,4,7],[8,16]]
>>>List=list(input("entertheelements:"))ent
ertheelements: hellopython
>>>List
>>> L1
Toovercometheaboveproblem,wecanuseeval()method,whichidentifiesthedatatype
andevaluate themautomatically.
>>>L1=eval(input("entertheelements:"))en
>>> L1
>>>L2=eval(input("entertheelements:"))
entertheelements:[6,7,8,5,4,3] #forlist,you must enterthe[]bracket
>>> L2
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
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]
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]
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:
ForNon-equalcomparison:
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
>>>company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
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:
indexdellist-name[start:end] #toremove
elementsinlistslice
Example:
>>>L=[10,20,30,40,50]
>>>L
[10,20,40,50]
>>>L=[10,20,30,40,50]
>>>L
[10,40,50]
>>>del L #deletesallelementsandthelistobjecttoo.
>>>L
NameError:name'L'isnotdefined
Differencebetweendel,remove(),pop(),clear():
S.
del remove() pop( ) clear()
No.
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.
print("Thesecondlargestnumberinthelistis:",second)
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:
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:
>>>
T3
>>>
T(3,)
>>> T1=3, #Italsocreatesatuplewithsingleelement
>>>
T1(3,)
8.2.2 Creatingatupleusingtuple()constructor:
>>>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))
>>> T
('h','e','l','l','o',' ','p', 'y','t','h','o','n')
>>>T1=tuple(input("entertheelements:"))en
terthe elements:45678
>>> T1
Toovercometheaboveproblem,wecanuseeval()method,whichidentifiesthedatatype
andevaluate themautomatically.
>>>T1=eval(input("entertheelements:"))en
terthe elements:56789
>>> T1
>>>type(T1)
<class'int'>
>>>T2=eval(input("entertheelements:"))
>>> T2
(1,2, 3,4, 5)
>>>T3=eval(input("entertheelements:"))
>>> T3
(6,7,3,23,[45,11])
8.3 AccessingTuples:
Tuplesareverymuchsimilartolists.Likelists,tupleelementsarealsoindexed.Forwardindexin
gas0,1,2,3,4………andbackwardindexingas-1,-2,-3,-4,………
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:
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)
(25,50,75,34)
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]
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.
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}
>>> D
{}
{'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}
>>>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.
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["Maths"]
81
KeyError:'English'
godict_keys(['physics','Chemistry','Maths','CS'])
inonegodict_values([75,78,81,78])
Lookup:Adictionaryoperationthattakesakeyandfindsthecorrespondingvalue,iscalled
lookup.
9.4 TRAVERSINGADICTIONARY:
Syntax:
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':84}
>>>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:
False.
Example:
>>> 'Chemistry' in
marksTrue
>>>'CS'notinmarksFa
lse
>>>78 in marks # in and not in only checks the existence of keys not
valuesFalse
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.
dumps()functionfromjsonmodule.
Example:
>>>print(json.dumps(marks,indent=2))
OUTPUT:
"physics":75,
"Chemistry":78,
"Maths":81,
"CS":78
dumps()functionprintskey:valuepairinseparatelineswiththenumberofspaceswhich
isthevalueofindent argument.
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])
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