Python Notes
Python Notes
Python Notes
SYELABUS
follow By-P4thon-world-1n
Lnaduction
rexe Quisite3_o LeaxninqJala
Necessity o Pzogrammin9-
hatis java ?
h a t is plattom Ladependeace
Whexe jaa Stands Ioday
mpartaat eatures
History o Java
Editions of laA
TDkJRE and JVM
Compilina And Ezecuting The Cade
An Taoductian to TAVA
rerequisties ofLearning Java
Necessity ok Psag1amming
tha is TAVA
WhaE is Platfoym adependenCe
Xlhexe JavaStandsloday
PLATFORM Independence
Plattorm.
A. plattoxm is the ênvixanment in shich a
Dx090m XuAS
2 n Simple termsit is Cambinatian o
OperatingSyetemond pLoCeS&ox
examnle Wndauas +lalel Ci5), Ubunto +AMD
Pthon woTld-in
(Platform= apexating+(Pxatesial
System
QRou many Phy3ical Machines ase thereio
he gure ? Ans 12 physical machines,
Laindous Mat int LDindoo
l32 bit)| S C32 bit)
Python- lulorld-in
Wlheye Java Stanels Today
Ploundex3tand hoLo aya has dominated
he naaxket romlast 25 yea3,
please
Seethis ideo htps nun.belE-rksUa S
3 Billao devicesxun aya as_ pex OxaCe.
LC1 eilioo =loo Cyoxes)
1 Billion Jaya daunlo ads pe Eheax
Automatic nt
MemoryManage.ment
T languages like c and C+ any_dunamie
memoxy hich the proqrammeyallocate s
ox_ne ba.s to be deallocated_
USingmalloc O
by himself Osingree ) oy delete
But oVO USe3 xuotime outamatic gaxbage
Callecdionleatuze hexe he JVM itel
LAeallocates any unomic memaxry hich Our
Program ollocated.
pyHhan-lalosld-lo
> Sefure
Whenit Come 8 to SecuxityJava is
alumays the fixst_chaice, Tt enableS us to
develo p vixus- aeetempex xee Sustem
JAVA_i3_amoxe Securelanguage aS
Caapaxed to clct+be Cause
1 I t doesnot allou a DOqammex to
Robust
has Vexy Stsict Kules which evexy
Java
Program muSE Compulsaxilyfollouo and if
theseXules are Violated en JVM kills/
teminaBes theCode b 9enexatingException
asli=it1
lanpredictable, a-fter iis 5
Puthon-Jlorld-in
The Previas Code might shouo Uncextain
Simple=
Java
avabaxxau.S mostof it's Suntaz -om
c/c++lanauageS
Moxe Ovexit has inbexiked best points ham
heselanguages and droppedothexs.
ike i t has_xemaved pointerS, multiple
iahexitanCe etc as developexS of Jova languagsk
found the&e teatuxes to be Secaity thàea
found
Ond Canusin9-
Thus i e have aasi onderstanding of
clc languages t isVery eaSy to learn
Java
object Oxiented-
ava Suppaits all impoxtant Concepts_of
OOPslike
@ Pythan.-Wosld-in.
S Encap.Sulation
> Iaheri tance
Polmar phism.
Abstxaction
*Mulhthreaded -
Mulithxe.ading mean ConCurreat exeofion
* I Simple excm&it neans that ean.
execute moxe thanOne paxt othe Some
proqram paxalle ly LSimultaneausu
clscx
lactosial(5);_
Prime la)_
evenedd (D;_
Pathan- world in
Ealitions/Elavours of Jaua
O Wlhen ova wa_OxLginally eleased in
l96itudas just Javaand ioSuch thing-
s"edikions"_wasthexe
O But as ose of Jova inCreased, then in
aaaSuN Cadegaxized it iato 3 edition&
Called JSE,Je£ And J, ME
0 atex An in 2 o06 they changed the
Namingand
namin9- Called them aS JSE,JEE L JME
o oTheseedition.s LOexe named based on the
the
Kind afopplication obhich Caa he developed
y leaxning that edition.
TAVA Editions
lauou3 ot JAVA
TRE(ls) JVM
o OndexstandingH dlference between DK,
TRE and JVM" is Vezy Very inepartant in
Java ox intex vieuss
0 Thesetexmsstand fo
JDk JAVA Developmeat k i t
k JREJva Runtimne nvixonment
JVML Java ViTHha MachioAe
What 1SJVM
VM is an abstract Machine that Can
execute Precorapiled Java praqrams
T Simple texms i is the Code-
eyecution Component aFJAVA.
*IHis designed fox each platfoxm(os+Cpu)
Suppaxted bujava ond his mean that
Eeryplatloxmill hove a diilexeat VerSian
VM_
QUIZ
hy VM i3 Called Virtual Machine
JVM is Called istual nackine because it
s a Sotuoaxe layer but it behave aS i
Pthon- nloxld-in
it is a Complet machineplatform)..
KThat is all Hhe tasks shich axe done
o O machine okile Yunning proqram
i in othex longuage3ike Coare o.ctually d
by TM in Java
Foxzample-
Stoxting Theyecutian By Calling maial
Allacaling memory t h e Pya9
cleanio9 up Memox Cleaaup et
What VM Cantains?
JVM_Contoinsallousing J impostant Campanents
Lntexpxetex
naxbage Callector
QUIZ
Ae ioaya Campiler Ond intexpretex Same
Aa, lot _ot oall_
The iova Canmpilex anuexts Saurce Cade to
oyte Cade and 1s not apaat of TVM, xather
Comnes uithNDK-
heintepre ter livesinside the JVM ond
ConVexts lautecode to Machine (Ondastandable
ro m
What isTRE
RE is an aCronymtoxava Runtime
nvixooDaeat.
I Contain JM olongwith jaua
classes/ package3ond Set Lntime
Python- World-inn
ibaasieS.
Sothe Java
JVM, while zuaoing adava
ogramram USees he classe S and athex libraxies
Supplied by JRE
Ae do not want to LOxite adava
rogram, andwe j u s t W a n t t o xun it then
We Only aeed o JRE.
What is JDK-
JDkStands o dava Develapment kit
and is a buadle a Sotwaxe that we Can
USe develop Jova based application
H includes the JRE, Set o libraxy class,
tnals needed
Java Campilex Jax and additional
shiledeveloping o Java appli.cation.
AUIz
Con Compile a iava appi.cation if I
have a JRE
.YeS
No
Coxrect anSses N o
JRE Can Only beUsed o xun a lnva
opplicatioo I doesot Cantain the javac
avac
DoLnloading JDk
1. Goto
https://www.oracle.Carojava/technalagiesdasnnads/
Tnstallinq JDk
1.The dosalaadill begio
2.wlheA the doanload Camplete 3, yau aill get
an eye ile Called Jdk -11.0.02-wlindous-xhu
bin.eyLe
_and
3. Nous,xight elick an this exeile
"Run dminis ha toa"_
4An installexwindoa AiLp0p up
5. TE evesythin90e3 pafecly you will_
eCeiveameSaqeSaying- thadinstallatian
is ScCesEul.
o Puthonlelorldin-
Vexifying Installation
e aa o the Specified path dhease yau install
Gous Java.
B deiault Java gets iostalled io
C:\Pogxamile3 foldex
lhele you wil 3ee a Java foldex.
nside the Java oldex yau will See
jdk-1a2 o ldea-
Cto to Stast type Comd andopea it by
Clickingon it Ond type the follaudin9
Command highlighted in ed: Cend i l )
Pthon-woadn
But fomlava lo ohich lSaS TeleoSed
ia maxch 2018, Oracle changed the oew
YeleaSepalicy Ond decided to launch a
Nex3iao Savaevexy6 months
*Nlausit be Came, Nery dihcli ox
Sattuoaxe Developes tKeep theixapplicatians
Sevexal hudxed CHhausa.nd 2) SeuexSup
o date t a the neusest Java seleage.
That is wlh a CanCept san TS hlas
cstablsud
henext LTS VexiAD is Jova l,which-
Koas elea Sed in 20 8 and wilCantinue to
eceue pdate 3 until 202, wH a
Possibility a _ d a t eytenSion.
The nezt y eleasesa Javaaftex
Nava va 11,jshich axe Sava 12Java13, Java 14
aad ava 15 are al_STS Shost Texm SupDAst.
JDKL Jahich haseleased in Sep 2021
is helatest LIS_release and uoilll he
Suppoxted os long asSep 2029 h
a
Strong pa3sikility _date exBensian
python-wlorld
Deve lapinq JAVA Pragxams
Java pxagramDevelopment
DevelopitNolepad.
DevelopingJavaprograms Usin4
Developing andd unnin9 a ava proga.m
se quires °three main Steps
1.oriting heSouxceCade
2. Compilinq he Code-
3.ecutidg the Cade
C Lthon-wlorld-in
witin the Sauxce Cade
Select notepad.exe hom the list
Shoan io pep up menu o Xun Cammands
Right click and chooSe u n as odminis
txato option.
Nous
No tupe Hhe Cade given innezi slide.
classTest
Public staticVoid mainlStiaq Llargs)
Sustem.Out.Priatla (" Hella USex)
Puthan- world-in
class Tes
Sincejava is an object osiented koangu
age and it 3trictly Suppaxts En Capsulation
Sa every iouapmamm mus t always Can-
tain otlea.st One classand lhateyer
we Loxi te_mustappeos within the opening-
and cloSing bace a the cla
The 3econd3tatement is
Public Static Naid main skinq L1ar9)
n java also (like c/ct+)the èntYy_point_
o eecution ot Oux program s the me thed
main ) Shich is Calledh the VM.
Te norde3 sho on in blue ere Keyuords
The
Land each has a diHerent_meaning a
and
ad
AUIZ_
)Doe3 evexymethod has tnbe public
Statieand veid 9
Yes No
Noit n o t Campsionhis is
onlyith the din noe thodthat e haVe
t o make it public gkatic and Vaid. AU
othey methods_ bave declaxatians are decided
he ProgramaeK
(Pthon-ulorld-in.
Savinq the Souxce Code
Qnce e havew1ttea he Cade
Hhe next gtep_is to Save ond Campile
heolausing
*opea- the Co.mma.ndprompt by sight
cltckingand Selecing xun a3 ddmiais -
ato option.
Miqrate to the dks bio foldea
Pe he Cemmand to Campile the
Cade
hegenexa Suntax o Compilation is
Ejavac/iullna.me oE iava ile >
Jayacig the name of jova's Compiler
th tokes he nane o Ous Source.
Code o as asqument and 9enera tes t the
he
bytecade
or exampe:
javaclest jova
*Recnembeythis Commaad has to be
Lbivea
Loivea om jdk's "bin Jolder ae we
ha veSa vedthe le here onlyl
Class PB
clo3sC
Ansioey 3.
Closs B-
@Python-arld-in
classC
but
tInsuoe ALhough eCan give any
i t i s pãciexed to give the Same na.me
AS the class ohichContaln& maa)
Methad.
Sustem.out.
A Piiatla I n ladaxe");_
class Bhapal
Pustatic Vaid maiaLshing Llara)
Suetea.Out. Priat lal" Ia Bhapal)_
Hnswes
Can be_either BhopalLjava" or Indaxe java
3
*Nouo when we lailll xua it
laya Tes
The Output Laill be
Hello OSeY_
elcoaetoJava_
Data TypeS
Ge nerallydata tupeSAre used to Greate_.
axiables wlexe Vasiables ill hold Values as
deined in the rangeoE Values a a
data ype
JavaSupparts tuo Categories o data
peS
o Pxicaitive dota fype_and
Nan psimitve Data Iypes
Pythan-wloxld-in
Data tpe Categaxies
Dataype
primitive Non-Psimitive
Data TyPe Data Iype
bcclean
byte float
Shoxb double
int
o Douhle
Chaxaceys
oChax
Cenditisna _
Obaalean
LO Iaeeex Tupes
une Size Co Butes Ran9e
Be -128 to 21
Shor 324& to 3216
in -21414R 3448 to 2]4142364%
9223,3-2, 034,854115o8&
223,312, 036,85411580t,
o Ratienal Numbess
uDe Kize Range
4 -3.4* l t 2. 133
double 3
o Chazacters
TH pe Size Ranae
chox 2 ata5535
Pytann-alorle-In_
hJava Uses2 hytes a charactexs?
* LnJaua almost G1indexoationallanguages
Ore Supparted._
No he chara.clesand Sumbols o he sSe **
Condi tional
ype Size Range
Baalean- IVM- tue ox falke
depandent
( Puon-hlorld-in_
TYPe ConvexSion
lha _is bype Canversion
henevex
nevetheCompiler enCountezg a
eiatement here the value an iaht Side
assignmentisi s diHexeat thanheVariable
on Letthen the Compilex ties to Canve
R.HS LH.S Dndhis adamaticConvexsion.
dane hy Campilex is Called as ype Caaueraion.
Fox example
CanSide the sllaii.ngStatemeat
X=Y;
In this Case twa thing5 Miakt happen
data type o both Vaiable&a
Samethen Value o y aill be_assianed to-
Hhe Voriable X
Rut idatatype al bath Vaxiabe& are
differeat then h e Value of Y needs to be_
CanVexted as per the datatypes oE Vaxiable y_
And his_i3 Called ups anyesSion
o Putnon-lald-In
Acceptinq lnput
Ja Jova here are3 oays to actept
input homUSex
houg Command line arauments
USinq Scanoer cla3ses
> OstAg GUL Caoponents
I i s ecture e Cavey Commandline axgu
meatsand the ethex too methedswill be
Cavexedin futue lectures.
Osina Command lineArquments
UsingCammand line Arqunaerds use Can-
accept_ioput
acCept shen wedxe abaut to execute.
bin>lovalestSachia
Case llL
claSs esE
3
bin > lava TesE Sachin
CASE-V
class Test
3
b i ava Add alaslo 20
Why as the output lo20 ?
Becouse anutking Ohich ime pass from
Carapaa.nd pxamptis hy deiault zeated as
aShing byAava
No SinceJava isConsidesinq the values
LLo _and 20 0 Lo ond_20" So he Ope ratoy
Cancahecaded them iostead sadding then
mathenmatically
T_Salve his problem ae hove to Caniext
he voalues o " and 20"xom Stxin9 toiat
and kis is daae Usta9Specialclasses io
Java Calledalxapper classes
wliapper Classes_
n iaa Canc3panding to& paimitive_data-
Puthon alorldin
pes we have 3_pxedeined classes also
Called xappes casses
hese closse 3 oxeayailable in the package
java loang and their names Similar to the-
nameo data tupe
i ex lntegexchaxactex, oat, Baalean et.
Notice that He s t lettex in wlappex
elass nameis in_ uppexCase shile in Case
data
dataype- it i io lousexCase.
oo ex bute and byte long and long and Soon
int a,b, c_
ae lnteges. Paxselnt Carg3 [o])
b= lategex. Parselnt largs 1]):
Ceatb
9(tes 'Canditioa
ue false
else
ielge
3
Pthon-woald-io_
Every else statement Should have one if
Statement
ielse i
I n Caseot ChecKingmultiple Canditians
thexeare oo
10seOnly ik statemeat to check ever
Candiion.
a Ose elee i statement alte he first
shatement o check_all he other
e maining Conditions
me Hhad hald dauuback.
Caa you tellohat ?2
Z IKe dinusback in usiog only if statement
to chek all the CanditionS , h a t even
altex 9etting the sight Skatement and
eyecuting i the Campilex 3tll Continues
Checkin9alll he emaining 3ate.me.ats
ShichiaCrease3 xun timeof the progmm.
So it Canuenient and Sug9e 3ted
Ose else it gBatement to _check multiple-
Conditions.
i else
ECtes-Candition)
true
else ittest-canditian)_
re-
else 4
@Python-orld-in
Nested if
Any Condikional state.ment whin oith in
heobher Canditianal statement make
itnested in natuxe
iLtestCanditian
tCtest Caaditiand
else
ly this.
Accep n inteaer am Use yiaCommaad
ine araumea and check ahether
Lodd ox e veno nature
Salufion.
claes 2eo add
3 Pthon-wadd-in
I this
ompany ONideS inSurance to i}s
emplay.eesocCoding to the Lollouain
Ctexia
TEthe emploj.ee Ls Masied
o T Bhe_employee is nmaxriedMaleaod-
abave35 Yeoxi ofge
0 Ti the eaployee 1sunmaxxied dlale and
abave 30 Yeax& _oage
n alL_othe Case 3 inluTanCeis nat 9iven
WAP to accepb tnder
gcader and maritalL&tatus
om he Usex Using Caamand line_axguments_
ond check uohether- the 1Sexi3 eligible ox
insusaoce n o t
The Swi teh Statement_
eTe Suitdhstateraeat is imilar to it
tatementositit i3alsa adecisiaa Cantral
statenent
T alloos laxiable a be testeda4anist
tst fyalues 3here eoch Value is Called
a Case
Suntax
SL ehlloxiable-name or expiessiond
Case value l / statemeals
break
Case Nalue Igtatecmends
break
detault l/skademeats
Pthon- wlould-in
TheSwiteh statement Can_Use different
Voaiables to check the Canditions.,ohich ort
byte shor charint
h eUSe ol Stxing3 Ond eoumeaated types
QYe also Sup poxted
Example
iat month =&
SLitch Loa.math)
ase 1:Sustem.aut.Printlo (anuarL
break
Case Suckem-aut Println("februaru"
break
Ond So on
deault: System.out.PintHnInvalid oaath
brea k
Cose Value 4 Case Value 5 case_Value 6:
break
Ldefault
Any number_a Cases Can be clubbeJ
ogethe. 0spex Candition
Pathon_Wanld.in
Exercise- numberom the
WAP o ackept a month
User Via Command ine arqument anc cispla1
the nameoF the SeaSonin which the
month falls accoxcing to he table ive
oelo
Month Numer Season Name
l12, 19 inter
3, 5 Summex
Raiot
Any ather Value oxonioput
n -
Output-EaBex a ao 5
Fockaxai l2o
Do-WhileloopP
Suntax
do
shiletest
Conditian)
Since, the Candition is tested at exit,So_
ance
he loop bodyilll eyecute at_least
ixespecHve _of the Condition.
Exercise -2
WAPta altept too inteqer om he Usex
Land display theix Sum Nos aSk the Use
Lshethexhelshe ant Continue or nat
the anSex i3 Yes thea Daain aepeat
He proce SR Atheiwiseferminade ep am
(aPtho-Word-in
1
3
Can oe replate nexEO with nextline()12_
Buffer
Bufer is aa reqon ok a physical mecmar
L
Storoge used to tempoxaxilyStoxe data shille
U
KE is being moved äonm one placeto aaather.
EkSoin dhove Case the keyboard's bulle is
letLoithanENTER kEy"shile we pYessed
ater ioputioq the econd inteqer, hich
neytne) aCCepts os an input.
Pthon_World- in
Rouo Can we Solve this 2 2
B4 Calling
nextline O betore accepting
actualinput. mput since, his Call auld
clean the buffer.
Solution Ex:2
class Adddas
Public Static Noid mainlstsing Llargs
3
Pthon-World-in
Theiaitializatlon and sodementpart
Can be left blank.
break_ and Continue
Toterminate Hhe loop ond exit i
DadyPnviding a Candition betaxe itio
Such Cases_oe Use e gtatement
Stuatlon3 Lahexewe ant to skip
SKip-
urtheYSteps in a loep and mave direct
back ts the test Candition, Hhexe we Use-
the &Batemeat
LetS nderstand these hxoughan Sraanple
*WAPto_accept an iategey bam USex_and
Check_she thex i t is pxime s naty
impax javautil. *_
Class CheckPrime
lai=o)
break
LiH Ca==)
Sustem-out Pintlo "nlo is_pioe"
Lelae
SystemoutPiatln"Na s nat a_prime");_
Pgthen_Wovld- in
trercisse
wsite a progaam to_acceptan inteqe
om
h a m the Use Calculade and_print the
Seum o t's_digtts. Fo example i f ioput is
5 hea Output_shauld be 12.
Wrtte a pxagmm to accept an. indegeSum
om the usea Calcauate and pint the
'sfixsand last_digtonly. Eaz example
i input i s 21 15 then butput Shauld e E
Wite a proqyam to aCCept an inte qex
hom the usesand pxint it's
eYexsefar
example iaput is 451 the output should
be 154.
aite a pxogxam acceptan integex
am he se aadcheckshe thex it is
pime Ox not
t ea paaqaam aCCe pt an indeqe
am he Usex and paiat it's table up to
Aa texM.
Nested Loop
Suntax =
Cinit; Canditioo stmt)
Eercise
WAP accept an int on uses Ond
pint Sum a t t s digits ?_
WAP to accep_ar intram Oser and
check Lohether i t i OXmsrong oY not
>WAP ta acceptaa int bam USer and
priatts xeverse
>WAPtoto accept anintegex om USes
and Check Lohe therit is egual to its
reverSe Os not
WiBe o meno dsivenproqram in dhich
you will provide y_choices ta the USex
1Facdoxial 2.Aime 3 Even /odd 4, Qui
Pthon Jwlanldin -
Atxays
AAaay is a Calection o data ot
SimilaxalatatypeS be i t Pemitive a Non=
PximitiveExample, an axray o integexs i l
will be onsist a Collecdian ainteger
pe daia aa oaaay ol name ill be a
Calleckion of skings ond So an
Aoay in da va is txeadedas an object
So, to Cxeate aa- oxroay e se the Keuooxd
new
Suntax -Thexe ae 2Step3 involved in
1Creating axray e fere nce
Ldata pe L1Lamay xe fexence na me > on
Ldata type Laixay zefexence name>LL
Example-int 1 a r
Here axr i s a efexeoce a0 0ro yo inteseas
Double tap +o add tle
a. Cxeainq artual anay
Lama xelexence>eneuwidata tpe >Size]_
Erample
intLani
a y ene intLl01_ intf Jaxy ene uoint o l
2 S
7
oolooloooloo o
looo
looo
aTY
Pthon.wWorld-in
Patializing e is Same as that in-
Clc++ £ämple
arxLal=la
Oy i =20
int[1ax =lo,20,30,40, 563/can be initialized.
PSze ok onay Can be _sSe b Vasiable ohich_
as not allosed either io C and Ctt Ezample
int n=loi
in tIJaax sneo întlo.
He Size i given negative hen Negative
Anay Sze Exception_acCurs
ExercisSe_ WAP o Ceate on anay af n-
indeqex s Where n is qiven by the 0ses Then
a.Sk the Usea t a input Values inthat axray
and inally display the Sum and ovexage
allte praqxoas of Numbers /Sum and
averags af alL the _numberS eatered by the US
Salution
impaxt javauHL*_
class AxayDemo
loooB 6o 7o o1 loo
2
ox int izojiLn;itt)
Sum =Sum +inteqer. pax Se lntCargs Li]
System.out.pxintlo C"Sum is "Sum)i
tem.out.pxintlnld
Python-World-in
Creating auay bject
aayreferen object
Teterence = neuudatatee[Sze][Sizel)
ample -a Ene int[311
"a"is_a Yeference toan Arrayo Reteren=-
oooo
looo
2000
looo 3000
o00
o l ool
oill be theoutput_Lor this
shat
iot L]L ay enew 033 L33LY
1.System.out.println lan-length):
2.Sgstem.aut PriotlaLarn IoJ.length)y_
Eno1_
3.System.out. Priatlalan LoCoJ.kngth)
Erercise=
WAP to Create a xectanqular 2D aray oE
| He oLo andCalumn Size eatianed byhe
Oser.Nouo, ask the ysex to input value3
in
these values
hat auray and finallydisplay
rom 03 welas_theix Sam and
in maix
Laverage
RthanWauld in
Salutionimporjava.ul. Scaaner
class TooD Demo
Yow+Ci+D.
|System.out: Printlo ("Enter numbess in
Hoxintjso,jLaufol anqta ijt+)
O i l L 1 =kb.nextlnO
Sum= Sumtam CiJLj]z
HorCint izojiLan.lanaHhiit)
farCintjEoijLaxloi.langthi j )
System.out.PriatCan li]LJ+");
2o0o
looo 3o00
oco
2 o0o 2
Solooolo
Initializing jaggedanay
int aix sneu int L2] H
azlo]=nes int23
osY Eneo intf 31
ayx LoILo1=lo
a CoJLJ =20
arY C11loJ =3o /and So c
2 intLIUo) Enew int [2IUL
axlolenes intltlo,20,30,a
o Enew int SO, 60,1ok
3.IntLillar ell0,28,3ai,fD6oi,2o,20,a3
Erercise
A e to Cxeate a jaagedaxo Y wheye KOla
and Columa Size axeo be acceped ao.m
Hhe Ses. Nouo psint al the yalues atjogged
Pthon-orld-in
OTa along with oO w3e Sum.
Solution Lmpostiava util,Scannex
classjaggedDecmo
Public Static Vaid manstaing C.lars)
SConnex kb=ne ud Scanaer(Sqstem.in)i
SCanner
int(ILlan
Sstem.out.paintln"Eater _aumer of Rouss)j
daY=ne uo int ] f U
oxCint i=oii on,lanqthjitt)
Sustem.out.Pxintla("Eales numbey of Columns io
int c kb.nextInt _
oxl =neuo intLcl
Sqstenm.out.pxintln("Eates Values ");_
oxlint jeaijcanfillength ijtt
a i] =kb.nextintO
dlass
/CAR
MethadsAthib1 Pthon
-
Pillarso OOP
world
in.
etadd bady
(Pthon-Word-in
yaople
class3tudent
int xall
char gadei
loatpex
3
closs s e 3tudent
{
Pblicstatic voidmainlshing Llarga
Students
S=nem student
3
AccesS Madi-iers
There axe accegs adikers provided by
java hich axe
public
Psivate
otected
default
pubic and Pxivate_are o impartance to
o3 nleseB we leaxoPackage"in Java
@Ptoonlerld-in.
Caeatin9 raethads in a class
heoajoxmajosprinciplee o obiect_onienked pyogxa
eminaie nCapulotion implemeated tusing
raethods in o clasS
InJava We s t deline o method in class
no declastian is equixed.
Y
Cla3s studeat
L
Psivate int all
Rivate char qade
Pivate te loaPeapea
Public Void SetDatal)
TollEla
9radeA '
Pex =b4.5t
Student S=neu3tudeat O
S.SetDatal i
S.shaua Dadal)i
Phon-lorldn
s Racher'Signature. ********************
Initializins Data Membes at RUNTIME
Public Void ShousData C)_
classUsestudent
2 dota rmembey
/initializex block
lintializx bady
lo Pthon-Narld-in
PaSsin Amay Reference
class Demo
Employ ee
Pthon-world-io
The object" class
I n Java every class by default inheids o
claSsnamed Obi
h i s inhexitance i_done by and Connotbe
avoided by enypoqrammex.
Jovaa
* Obiect cla.ss is te SupeyLaxeat
enteas3 Ot every
cla 3s. IA is Supes doddy clars.
i sispxe Sent in e packaqeJava slaa9
Gbiectclass has 8 methods ia it.Hence, evey
J
classhos at least 8 mehods
Finalizel) method is One of them and we Oueide
this method
USin "skatie"Methods
H methad shauld be made static in looing
thaeeSituationS.
|1.when it is only aCceeing Stati data o class
a.ohen it is only acceSSing its oxqumente -and
i Ca
Xetuxn a j
else
setusa b
Phen -ovld in
3 Teacher's Signature.....
classTesE
EactaxyMethads
here
here ae Situations here Cxeating an ohiect
miakt be depeodent on Same Canditions.
Fox ex ample,it Sooeone eatess O xneqatiye age
In Such situotions ehave to checkhe Canditions
beioxe the obiect_Con be m a d e
for Such Situations factoxymethadsCan beUsed
claaes_ ase
Can3tauetorsotSuch- Piva te and
the factos y method is Stoticin nattire
factox aethods Usually Ceate and return object
Lets See on eomplesa.
Class Pexson
Oe o Pthon- tdovld-in
name = S; Teacher's Signature..
Publlc void sha)
S.o.PCaqe +"name)
3
shatic PersonCxeate fexsan iotoshing. s
iCaE0
Ke tuxo DullU.
else
class Test
Puthon-larld_io
Yroperties_ a f statie methad.
They -ax allauned doocess anly_ statizdata
t h e cla 8simplicity
Ihey da not have thisyefescoce" built in them
e
Iheq_Cannot Use the Keyoard Super
1hey are Called dixectly Óstng Clags name
withaut Usingobjerleeobiect re-fexeoce
AlAlL methads a moath classaxeStatie
Static" Blacks
Consider theollataingprogrammin Stuation.
SuppoSe e have oCxeate o cla3 Called_
Accaunt ar a Banking application,hich 3haos accid.
0 afintefegt aCustomer
namebalance and Tae
The challengeis hatGur Code should accept
Tate -oP-intexe3t at Juntime and only cnce Ho
Can we ackhieve hia?
The Calutioa liesin OsingSatic_ blacks.
Static blocks ase iadependeat blocks kichare
leaded in RAMand executed as Saon p3 the
Px.0qIm eyecutes
Ezample
impoitjana otil. Scannex;
clo33 Accaua
Psivate int 0cid
Paivate Stxing name QPathan-darld-in
PiNatedouble baloncei
aivateetatic doublexate-a -iotiest
Static
Scanner Sc aneo Scanner Sustemio)
System.out.priatln " Entex xate af iotere.st ");
ateak-intexe 3= ScnertDauble()
P i c Account ()
3
Lnberitance
Lahexitanceis one o he mainpillarao
Pthon-orld-in
ypesof Taheaitance
* Single
#Mulfilevel
Hierarchical_
Jaya daes nat Suppas Multiple Tahexitance JalHv22|
2Becauseiava daes nat Suppxt ambiquity Assumin
i t thee axe classes A and B bovinga
a cnettad
metbod
namedshaw.IL both axe inhexited a closs C
hen tse ill be an ambiquit ak hieh Bhauwl)
naethodis to be Called
Usinq keqord "Supes
The Vequoexd Supe Us.ed by the derive.d
Lelas3 progammexto eplici H xetex he mem beX3
baee class
>Usion9 Superbe Come 3 (ampulsoxy in 2 ragamminq
Situations
1.cblio-
1.cblliog bage upey
class
class ConstzutoszAm desived
class bextends A
Public BO
Closs est
The term
Bindingg-
binding neans a MechoniSm lLaed
bthe Compilex langua qe to mak e
tunction/method Calls
*Just like objec aya _also
Oxiented Lanquagesava
N
two type of binding
1 faxly/Compil time Lstatid Bindina
2. e Dunamic. /Randime Biodiog
In Bindinq it the method beins Calledpein
s a elatic nne thad thealava determine s the esion
o methedo be Calle.d bu looking at the obiect
heingpaintedand not the eterence
A Rrogram to achieve Dunamie MeHhad DispalM
class Shape
etuio O.0
retuxnOaknoa
Publicdouble axea)
Class UseShape
ipublic 3tatio Void main(shinq L1args)
Shape Si
S=new Rectangle (5,lo2_ oPuthan-lsarld-io-
LS.o. PC"Shope is" +S.noame O)
S.o.P ( Its oxea is"+S. area
()
S:neuo siangle C15, 20)D
S.O. P C Shape is+S. name )
S.O P Hs axea i3" +s.asea)
3
Abstract closses and Methads.
defined
class Cannot be
Soae aethods a a
Sanme
as heix unctionalities depends on dexived classe3,
ike he ve yiou s example methads aseaC) and namel)
*So to avold oriliag their bady
body and just declaxe_
hem
he in baseclas s that thcCaa be Ovexxioder
in
n dexived class as pex Pnctianality
theix Hnctionality,wee
USethe KeyOOrd
Bydeclanins OmeHhadabstract e Canovaid
detning themethad but with toa Cacopulsian.S.
Jetinio
heclass ghauld also be Pae iix.ed LAith the
|ke y0xd
the class i3made obshact ten its obiec
Lannot be Creared but Ye FerenCe Can be_Lreated
SamPreviaus Example
absract class shope
Psivatete int dimi
Priyate int_dim 2
L--= Same OS pre yious - - - / _
abshactpublic
abstract PLblicdauble
Sbingname C
areal)
Pthan Larld.in
Rest bath dexived closses and DIive class
emaios
SameBrogra m LOl 8haa Some Output.
Methods shich Canna be made Abstact
EStati methnd 2 Sinceabstract isused wbhea
hereis no unctianalt deiaed yet"and shatic.
iEse l MeanS there ig unctionality eveo iE you-
do not have obiect So3totic and abstracet ore
Campletely pposite to- ech othex
CanstructnS Since, Constxuctor3 are neyes
inhexited henCe daat requireto be ovexidden
Psivate methods_ The3e are natacce3sible ina
not.
_dexiyed closs
Classee ohichiahexits abstsact_ methads must
CompulSoxily OvexYide heabsraet methad
(Ptaon-dorld-io
T's Value will yemainOnchangad Kemembex
he data member Math. PI_ t s declaredthe
Samehay Ihey behave Like Constants
ETheinifializatisno inal data member Can
eithey be done explicits_ hile_decloaxing o through
Consxuctors at Yu timeAnl onCe. But i n all the
Canstructoxs defined in acloss.
Once expticiH initializedot eclaration hen it
Cannot be iaitiallzed Osing Canshuctors
* LscalVaxiahles Can be madle ina
inalaS Lela
Java ShonglyreCammends that whea an data
members inal and 3tatic in natuYe_ Heo
i t should be named in uppey Case Srample, Yiivate
inal State dauble PI=3.lul59. THs nat a ule
but a Protessiana Coding Canvention
Example
class Data
tina int oi
PublicDatalint )
3 3
class Data
inASEatic_int a
State Ptha
thon-iorld-ioo
a-lo
Teacher's Sienature
Public_shatic Vnid mainL_shing LIags
SystemOut. Priatla CA. a )
final Methods
dinais_used sith methadsLahase unctionality
xemains Same thoughoutie base as laell
a s desived classeS
Methads shich Oxe declaxed inalsCannot be Over
iddenio dexived closseSBut they sda qet inhevita
classA
closs B etends A
Super. display ()
33
class C
P S V mainCStsinq arq)
Bobienew BC
ohjdisplay(
Absbhac ae thods Cannot be mada inal asd
Vise ersa Sincea me thadis madde abstact beCau
Se ofits Dnknowa {unction.alitSa they Can he
acCording.ly madified in- theix deived cla&se3.bkere as
a method is m a d e inaS0 that t's unctianality
Should nevexy Chan9e thxaugbQu he hiexarchs
Abs tract methods Con
be CalledUsingdeaived
b u t Cannot be Ovexxiddeo
esiyed
clas3obiect
ven methedaainlCon bemade inal
ina classes
*Those classes bick Oe Prefixed sith Keqiuaard
ina Cannot be inhexiteol in ava.
|*For example class sing 3 a Sina olass_and
no other class Can inhexit i t
Classe aremadeÅinal in Gse wshere dhe data
membex ox method3 oye Sensitive enough hat the
@ Pyton-uorld-in
shauld not be altexed at_any Cost
Ts thexe an other a thxaugb whichw e
Lao prevea tt cla ss e
o m being inheyited 22 9
CTustf kneisledge)
B making Censtdetoe Kivate
ina cla&sA
3
cla3s B extends A X
3
Thoughaa cloaSseS Cannet be inhexited but
lasses Can inhesitother closses.
Fox eXampleevexy class doe3 inher t_ he closs
obiect and henCe Tina class also dac3 inheit
the class obiect
Iaterfacce
An iatesface i s aaalternate to Puxe absbacE
classiet o Suppostua time Polumorphiam
An iateriaceis also a Kind oJava cloas& but
An
with Some pre.defined restiction3which oxe a ollous
1Ao Interface Co Containdata members but he
b yby_deiaulE be publiLshat ard na by natuxe
2.Eveiwe danta3ignan Vi&ibilit modeo
the members of aninteiface tll_their visibikty
Puthon- donld-io-
always xemaias public and o pyoqramme i3
no a llauoed to ate it.
An intexface Can Contain na.ethadsbut the
uaill be Public and abshacE in- nature
Suntax
intextace 2inter face name >
Puthon-world-io
classCircle implements Paint ,Shape
dauble OseaC)
StainqaetName
closs Rectangle imple.nents Shape
ivate double b
Public Rectangle Cdouble double b).
his. J =li
his.bb
Pabli c doubleareal
retum b
dauble Qrea
3 (RtLon-LJorld-io.
intesface Eraure
Strinqname O
Packages
ackaq.es are nothing hut a anc nameter a
Plodex ie, a. oicial Professiona name for a
aldey by dava
Packages are a Callection oE elaed closes and
indeafaces
i.eclasses and interfaces withSanae
Similar related unctionalities.
ava saronglyndvicea us to groupall ou elasses|
andinte tace3 inSide a packaae dee o sllosing reosans-
Beniits of Packages
Bymaking Use of Packaqes Loe Can easily
yeSolue namee Conflicts_ i.e tusa classe s Can hay e
Same bame iL the
T and onl i
hey clasa_isapast
are in_diflereat Packagess.
oAE fackage
Lae Can impaxtitio othepragramS, othexiie e
3
JavaxeComnends to name packase.s in lauoer Case.
for examplesjava. lan9java.uiletrPackoge names
ave also Case (Senattiue) Seasitive.
Packages
Creating packages Creating Packages outside
inside bin bin ond. SettingPATH
and. CLAsSPATH
C Pteon-orld-in
Creatinq packages in bin"
Package myiava Codes
class Test
Piuate int a
Bivateint b
Private int c
Void Set (int iintj)_
a i
|bzi
void add)
Catb
aPython-ovld-in
N.aidshoo)
3
OseNum.iava
Yackage mjavaCodes
Lelass USe Num
PublicstaticVoid main shing (laras)
Num obje NedNam)
obi.SeECo,20)
Ohadd (O
obj. shewC)
Compilin Proasam
I e Compile Use Nurnjava, hen automaticallG
Numjava also aets Campiled and you uill See tuoa
cla ss tles aill be eated e Num.clage_and
LOseNum.class This3 because ae Useon obiect
_oPclas3 Num_in class Usenlum..
But E you CampileNamiava then- only a Single
Num.classilewill be orme d
*Tava alo Ruppos wild Card Compilatiaa akich
i3 javacmuiavaCodes \* java (Pthon-orld-in
I t i l Campile alL the java les preSentE
in the Package myiavacode s.
Erecution Java muaaCade s,Use Num
Creatin Proqrams outside hin"
class Greetigss
Create
Sust tch
a dikctoay
On Cusvent location
Oxiainall ibxaxy
oe eCall Dxeviaug example,he class
Ose Num Creates an obiect ofclass Num ia it.
Since Nam is Createdby US ag o programmei
have
i t ontbe eaauahto iust iompoxt it.we
and then LOe Can impoxt
a Set its classpath
i t inothex programa
2 loSet classpoath oe again have 2choices
U
.lemparax4 Setin
Set Classpathe C clas&path Z
2Pexmanent Setin9
Right_Clickon my Canaputex Lopexies-
AAvänced- SystemSettings £niranment Vaiia bes
ne
neu
Nasiable name Classpath
Vayiable Value /locatian z closspath%;
click Ok
Puthansorled-io
Access ModiieYS O Visibilit Modes
Acess PsivatePublic defaultPo tected
Modiliet1
Sameclagg Yes Yes Yes Yes
Non Sub c las s No yeS Yes yes
Same fackage
Sub cloSS Same No- yes Yes Yes
Package
Non Sub closs No- yes No No
dPfexent Packaqe
Sub class and No yes No Yes
Diffesent Pockagel
Rthan-Norld-in.
Exception Handling
KExcLpioninpxagra.mming lonquages IiKe ava
mean3 Kuntime eLI í e enors hich appe.a-
_during ezecutioo o Pragram
*TE aiakt be due to uses xon9 inpu ox an
logicalalla.cy e progxam.
cepion handliog is the be haviað of a Pzogram
atey an exLeption ocCurs
Butbe foxe handling hdestonding hoLd to ezception
i s let US Ondex s tándd Lohat_ java does shen.
on eNCeptioa OcCux3
B leiaultjovo takes actian& ohenevexon
eLCeption-OcCurs
Puthon-warld-io
Exception Hieraxchy-
Jhiouwable
Lxos- Ezception-
TEiepresents those This closs xepreSeatss
exCeptions shich are thoseexceptio ohich
hotmeant t o be hand- Can and Shauld be
led bpogxammeS hondled boprograomm
hey are ethex hond- e in hig po qxam
led byJVM o OS AlL Exception closses
are dexiv.ed clos3 a
xleptian class
Erception=
Runime xception LObzCeption SQL Excepto
Athmetic Ex leption .file ot found 2rteption
No Such element Extepison EoF Steptioo
Teput Misnaateh £xteptton Maioznme.d 0RL
Numbes Foxmat Exception Exceptiso
Index Out af Bounds Socket eiception
£Lception Nulll paintex Exceptton
Amoy 1adex Out of
Baunds brceptian
Shing Index Out of
Bound3 Ezceptton.
Erercise
AP to accept 2 inteqexs om the 08e_and
displaq the e &ult ofthei_division and Sum
Yaupngxam Shauldbehave in the ollooing ay
@Pathan-soxld-io.
both the inputs_Qre integeis and Are
Valid then theproqram shoald display the yeSult
of heir division and Suma
Z I denaminatox_i8thenpyogram shaulddisplay
xelevant e 3oY message but_3hould isplay the Sum
ioput Nalue 13 not an integerthen he
Pogxam Shauld display relevant mesSage Ond
neitherdiuision noxSumshould be
be dizplayed
obtaining descaiptionof an Exception.
Oheneyex an ex Ceptioon ocCarsin try block
axaCreates_an Obiect_ok pecific.£xcepion
classand3tore s Someimpoitant details in
the abiect
No Osing
USin that okje ct we Can obtain all
the pogsible details of the exCeption that
OCCumed block
in the
To dathis uae Can Dse Seveialmethods
Osingthe object e fere n Some impartrant and
Cemmon methods axe
Methods
PablicSning 9et Message (
This method s preseat ia the class Ihxamable
The method ye tuxns_eTrorme3Sage" aenex
qenexated
1
ated
by javaegording the exception.
ample Cateh(£zceptioa e).
Psivatea t oge
Pivate Staingname
Public Pexsonlint age staing name)
this ag e age-
thisna me Ename
CPuthan-world-in
Using
Thexe
the keqhord finall
axe Cextain stodeoe.cds in Oux proam
Lohosee2eccution Cucia
So that before Ous
multiple ex Ceptions
This eatuve was iotroeuced iA java rom
VeysioO
Suntax
Catch.AithmeticErceptiaa Tnvalid Numexater Lcptian_e
Sustem.cut Priatn (Ex.ge Messaae)
StrinqHandlin
lala 3classes to
pxovides3 hondle Stsings as
pe Situation, these 0xe
Sing
2ShiogBuifer
3. ShingBuilder
Shin9Builderwill be Cavesed in the Multi-
headinq- chapte.
Stxin closs
Sshing objectsin sava de immutable i.e. Cantent
oncestoredCannat be changed.
Dfor frample
Shing city = "Bhapal"
Systea.out.Paintln Ccit) BH o PAL
2000
City "Indoxe"; oo0
System.out. Println lcit) NDRE
ooo
Thatg the Outut wll chanae but
He objects aant @Puthon-lorldio
ConstructoxS of String
Shing(-Stxing Seneus sthiogO 2000
2o0o. |
>shina(shing)-Shing S=neud shinsBhopalP
looo looo
Phan-orld-in
-1 Tti s a CaS Sensitive method
Publicinindexol C3thing) Accepts aSubsBsing
as agumeat and etuwns the beqioning indez
shexe he Substi09 OCCux3.
Pablicint lengthU:Ges length ok Stsing
Pabliccha chas AHCint) z Takes index numbeei
and give s chaxact at hat index
Public eid qetchaalintint.chasfl, int)E.
Takesaultiplechasaciers
Takes and postes theix Capy
chaacers
Public boaleaa startsith sthing) Ts it tis
Sthing Stasts oith Ahe Specified Prei
Public boolean Stats Lai thCstsin9,iot) -
Test i i s Shing Startswith ie Specified
Prei beginning a Speciied index
Publi baolean endwith (sbing)_lests_A his
Shioqends ith the Specified Suffix.
Pblicint lostIndexaÈ (int) Retusns3 e index
oithinh i s sting of the l a s o CCUYDEnCe ot he
Specified Choxactex
Pthan-uosld-io
Wlhat IS A_Collection 2?
As he n a m e indicate s Collectisn is a Oup
goup
o abiects Knouon- os its èlementsExamplesof
Callections
>Listo emai ids
List o Name S
Phone oumbeys
Recaxdosudent
ReCosds boakS_eto
Hau java Supports Calleetians?722_
lo laandle Such cslleztion oobechsjao
otex3_ (s o huge - Set ot prede iined clases
and inteydaces Called o The Calleckiaog frameklark
alichs available in Hhe package java.otiL
Wh do e need_to learn Callectian 1??
The irst quesiaa shich Caone.sinmindo
Eyesy pxo9rommex is
h
*Why
hoye
shauld
an aa
ose Callection classesshen I
tnsuoe
Athouah anays are vexy Setul data stoxage
Shuctunes butthe Satla ram Sevexal impos=
tant_dawbocks which axe
1 SiZe needs to be declored nt the ime
declaratiaa, So Can only be sed ifse Kna
Kra
ae fonehoind houn _man elements Le0ould be
sta tng CPgihon-wotld-in
Remain3 Of ed Size
3. Na xeady made methadsa pesiosminapex
atians lik inaestingxemavin Seaxching0x
Sasting.
Axxoy3 Qre not based an onypapula Data
Shuctise
5 Can only hold homagene atus datae lements
Advantage.s of Collectian.ss
Can na.cai.cally graia o shxiok
Reduces P s a g r a m m i n q e l e s t
nCreoSeS pxoqxa.mSpeed ondqualit
oethacs to pextomall
POyide e de.fioed
R0 D opexations
Amays Vs_Callectians
Aey Collections
Axraqs ixed in SzeCollections
axe qaLoable a r e qroLAaLle
QPthan-Lsarld-in
Gaad Pexfox monce but Poa es formance but goad
LPanz onemayu (otilizatiao:memazu Olization
Cadioq is Camplez Coding is Eos
here
Types ok CallectianSCallections
3 maio types
aYe
sts alwayg Osdered, may Cantain duplicates
ond Can be handled the
he Sameway os usual
objsadd(rAmitb) /Loxxect
obj.add C25); ILLoson
oadd (aue) Loang
Insexting Elements in Arayist
elemeat in_he rauist a
have to
ove Call themethad add)
ismethndkas 2 Neyaions
SPretotype
Publi baaleoan add Cobject)
Pablic Vaid add Ciat, object)
>The s t method accepts an object
arqu-
M e n t and adds that object ot_the_end of H
aqlist
h e SeCond method Qccepts_an indey numbes as
LOell og Qn Obiect as Or qument_and adds the-
obiectat the Speciied index_ @Pthan-arldin
Tindex is Qut afange then it thron&
He eCeptioo ndex Outof Bauads Exceptioo
Hox x
Arzaylist2 stinq>cikies = neu axayist 2>O
CitiesaddBpal")_
cities add0, Tadare");
Retnieving Elements of Amaylist
To xetieve aA elecmeat fam the Asraqlis
Loe have to Call themethod9et).
* Prototpe
public obieck 9eECiat index)
ThisThis onethad nccepts oninder number os
arQument and retuxn3the element_at thot paSitian
I ndex 13 Out_oi ange hen 1 throas the
exceptionLadey Out of Bounds Lceptia
fox ex-
Shing S=citie3.qet(o)
Sting p=cities.getC1):
Systemout. Printlos);_/oill shoua indose_
System.aut.Psintln (p)/wil show Ehopal
Pathon-waxld-io
Creating A Custam AnayList
Housdo we add abiects in o Custom Axaylist
T add objects o class in a
Oux Costom
Array ist we OSe h e SameSuntax agbe-laxe
i e by Calling the metho.d add
tax ex
raulist Emp aplist sneu Amaylst 2>0
Empe =neuo Emp 21 "Ravi" Soooo.a)
Lmp
mp eOEmp 25,Suomit" oooo)
emplis add Ce)
RmpisE-add l4):
Paints To Rermember
o eoe areadding obiects of Ou oLon clasS in_
AxayListthen e mus almays Overxidethe lequaD
eqal3) method inhexited b.om theSuper clas&
Object beCauSe dheneNex e oillCall the2
This i3
method emove () an the sxay List obie ct, it
iatexnolly Calls theeQLale O aethodL o dur class.
intexnall Call the methads
his also happens- LAhen e
inder of)_ox Contains)
Nou ae do net OveKide_thie method in our
clos3
clo3s then he equals C)_ methad oE object class l
get CalledAnd ad uieKnaia the equals ()methad o
obec class Co mpoaxegpae mos addse s3e3
Pthon-woxld-io
even
membex Value3
abiects
Hhen
axe having Same data
also equals"() method o
object class wi_e etuxn.alse
hus the methads emoVe indeyofO and
LCantains) llfatto indQur Dbie ctin
the list
Hous To sbxt he_AraykisE 222-
heJava ava languageproVides uspredeiaed
Soxting unctian3 methods to Sotthe elements
o Colle ctions ke r a i s t .
*Thu3 oe do hat haye tO uOnite Oux ooa logic
ar 3.otiagthese Callections
This done sing o clags called collectians
i n h e packaqe javaotil_ skich Cantaing a Statiel
methed Called ext) Lskich Can Soxt arn aylist
The patatpe at themethod is
Publicstati Void Sost (List L.
methadaccepts_aliet as arqunent ond
Sosts it's elements in Natuxal ordex.
Summaxy fBenefits
*Maintains the in3eí fion Ordesof element
Can 9oui duna.mically
* Elements Can be odde o eMoVed om
Paxticulax lacation
PrOvides methods manipulate Stoxed_abiects
Pathan-warld ino
The Iee Se class_
i s classimplemeats the_Set intexiace
Te eeSet class isuseful ohen oe AeedL
to exhract elements om a Callection io a
Soxted manaer
Store selemeat io a ree and they
axe outomatically amaaged in a Sated Oxdex.
Progyam
impaxt java utL*:
publicclass Ixee Set Demo-
Public Shatic Vaid main (stsing oras C)_
lhee Se t Lststng> ts =_ne TeeSet 2>O
s.adeCu
ts,add ( A")
ts.add ( B"):
ts.add (E);_
ts.add C e");1
tSaddCe o");_
System.Out.println (ts);_
Output
CA,B_C D £, F
(Trans) raverSing a ee.set
npax t iava. uil S
Public_class Set Demo
Public Skstie Void mainlsinqIJaxas)
CPthon-world-in
heesetStsing > st = oc Tee SeE»O-
St.add (C"Gyan")
SALadd Rohit)
Stadd CAnand)
ltexatar i t stiteratosO
bk; le (Rh. hasNext )
Stringsh =(stainq) inextl
Systm.outAintlnCst)
Oukput
Bnand
an
Rahit
Addinq Custom obiects To TreeSet
SuppaSe oe uant o aeate a ree Set o Boak
Obiect Ond loe dant to 9etthe output in_asCeoa=
dng Odex_Of ice.
XNoa, we coxite
TeeSet 2Boak2 ts E nes yeeSet Boak O
Bank b1=nes Baak CLe Us Kone tkax 350)D
Book b2=neus BaakTava Cextiicatian? *Kathy",65o
Boak b3= heo Bank "Mas texin9 Ct+ Venugapal 500
B.add Lh1);
tsadd b2);_ @Rthon-waxld-in
ts. add Cbi:
hen iava sill throLo a clossCos Exception
hy Did This Happen
*This is beCause object Abich we
any
add o the ee.Set Cxeated Osing default
then 2 Candition3 mu
Constxuctos then be Cempulsoil
Satisfied
The obiects added Must be homagene.ous
heobjects musE be Cmpaxable iethe class
m u s t implemeot the_ava lanQ.Campaxabie interface
mus
Ln DurCase irstCandida is Satisied
but Since Boak has na imple.omented the Campa-
xable intexdace,a closs Cast Ezcephian asi3eds
So to Sluehe_abaye eyception, oe must imple--
meat the Campaable intextace in Ous_Baak class
hexcise -8
Madity the Librat Manage ment Sustem Cade
by odding Yealuxe
One_mOxehich i to pxint
Bksioscending ode o Paice. Also_dis
he Beak& One One Osiniterator
PyTHON-IAORLD-IN-
FREE NOTES FOR
BEGINNER
PYTHON
LECTURE 1-INTRODUCTION
Today’sAgenda
• Prerequisites Of LearningPython
• Necessity OfProgramming
• What Is Python ?
• Important Features
• Course Outline
WhatYou Should Know ?
It is inspired by another
programming language called
ABC
Why was Python created ?
It is a non-profit organization
devoted to the growth and
enhancement of Python
language
Their website is
http://www.python.org
Where Is Python used?
GUI
Web
Data Science
AI &ML
IoT
Hacking
GUI In Python
How it happens ?
How it happens ?
Machine learning is a
field of AI (Artificial
Intelligence) by using
which software
applications can
predict more accurate
outcomes based on
historical data.
Hackers generally
develop small scripts and
Python provides amazing
performance for small
programs
Why should Ilearn Python ?
Simple
DynamicallyTyped
Robust
Cross Platform
Extensible
Huge Library
Simple
Python is verysimple
INC
#include <stdio.h>
int main(){
printf("Hello Bhopal!");
return 0;
}
IN JAVA
public class HelloWorld{
public static void main( String[] args ) {
System.out.println( "Hello Bhopal!");
}
}
IN PYTHON
print('Hello Bhopal!')
Add 2 Nos
IN C
#include <stdio.h>
int main(){
int a=10,b=20;
printf(“Sum is %d”,a+b);
return 0;
}
IN JAVA
public class HelloWorld{
public static void main( String[] args ) {
int a=10,b=20;
System.out.println( “Sum is “+(a+b));
}
}
IN PYTHON
a,b=10,20
print(“Sum is”,a+b)
Swap 2 Nos
IN C
….
temp=a;
a=b;
b=temp;
IN JAVA
…
temp=a;
a=b;
b=temp;
IN PYTHON
…
a,b=b,a
Dynamically Typed
Dynamically Typed
IN C IN Python
int a;
a=10
a=10;
a=“Bhopal”; a=“Bhopal”
Robust
int arr[5];
int i;
for(i=0;i<=9;i++)
{
arr[i]=i+1;
}
Robust
In other words, we can take one code and run it on any machine,
there is no need to write different code for different
machines.
So we can code that part of our program in Cor C++ and then
use it from our Python program.
Huge Library
• Version History
• This means that a project which uses Python 2 will not run
on Python 3.
• In Python 2
print “HelloBhopal”
• In Python 3
print(“HelloBhopal”)
• In Python 2
5/2 →2
5/2.0→2.5
• In Python 3
5/2→ 2.5
• The way of accepting input has also changed and like this
there are many changes
TheTwo Versions Of Python
C/C++
Source Code
Turbo
Compiler
Machine
Code Windows Linux
Difference Between Machine Code
And ByteCode
Bytecode
Source Code
Compiler
Byte Code
PVM PVM PVM
MacOS
Windows Ubuntu
Benefits AndDrawbacks
Of ByteCode
PyPy adds JITC to PVM which makes the PVM more efficient
and fast by converting bytecode into machine code in much
more efficient way than the normal interpreter.
Downloading And
Installing Python
A. print
B. print()
C. Print()
D. Print
Correct Answer:A
QUIZ-TestYourSkills
A. print
B. print()
C. Print()
D. Print
Correct Answer:B
QUIZ-TestYourSkills
A. False
B. True
Correct Answer: B
QUIZ-TestYourSkills
A. Compiled Language
B. Interpreted Language
C. Both
D. None Of The Above
Correct Answer:C
QUIZ-TestYourSkills
A. True
B. False
Correct Answer:A
QUIZ-TestYourSkills
A. True
B. False
Correct Answer: B
QUIZ-TestYourSkills
A. Machine Code
B. Secret Code
C. Source Code
D. Byte Code
Correct Answer:D
QUIZ-TestYourSkills
8. What isCPython ?
A. APython Library
B. Name Of Python Framework
C. APython language Implementation
D. None Of The Above
Correct Answer:C
QUIZ-TestYourSkills
A. PVM
B. VM
C. JVM
D. Bytecode Converter
Correct Answer:A
QUIZ-TestYourSkills
A. True
B. False
Correct Answer:B
QUIZ-TestYourSkills
A. 31-Jan-2019
B. 1-Jan-2020
C. 31-Dec-2018
D. 31-Dec-2019
Correct Answer:B
QUIZ-TestYourSkills
A. CPython , PyPy, C
B. PyPy, C,CPython
C. CPython ,C, PyPy
D. C,PyPy,CPython
Correct Answer: D
QUIZ-TestYourSkills
A. CPython
B. PyPy
C. Jython
D. IronPython
Correct Answer:B
QUIZ-TestYourSkills
A. 2.0
B. 2.5
C. 2
D. None Of The Above
Correct Answer: B
QUIZ-TestYourSkills
A. Python Rocks
B. Python
C. Syntax Error
D. None OfThe Above
Correct Answer:C
QUIZ-TestYourSkills
A. PyCharm
B. Cutie Pie
C. Spyder
D. Visual Studio Code
Correct Answer: B
QUIZ-TestYourSkills
Correct Answer:A
QUIZ-TestYourSkills
A. True
B. False
Correct Answer:B
Today’sAgenda
• Interactive Mode
• Script Mode
Two Ways Of Interacting
With Python
• Doing this will activate the Python Shell and now we can
use it for running python statements or commands
The InteractiveMode
The InteractiveMode
• print(“HelloBhopal”)
Python Shell is great for testing small chunks of code but there
is one problem - the statements we enter in the Python shell are
not saved anywhere.
Compile it
( Generation of bytecode )
Run it
( Interpretation/Execution of the bytecode )
Open notepad and type the code as shown in the next slide in the file.
The Script Mode
print("Hello User")
print("Python Rocks")
The Script Mode
Now save this file by the name firstcode.py in the folder “My
Python Codes” in D:\ drive .
Remember the file can have any name but the extension must
compulsorily be .py
python firstcode.py
• Since we are using Cpython , so in our case the file name will
be firstcode.cpython-38.pyc
Can We See The Bytecode File ?
• Introduction TOIDLE
• Rules ForIdentifiers
• Python ReservedWords
Types Of Predefined Function
Provided By Python
• Built In Functions
But to use a module we must first import it in our code using the
syntax :
import <name of the module>
For example: import math
1.
print("Hello User",end="\t")
print("Python Rocks")
2.
print("Hello User",end="\b")
print("Python Rocks")
Introducing IDLE
The IDLE is a GUI based IDE for editing and running Python
programs
IDLE has two main window types, the Shell window and the
Editor window.
Just type the commands, hit enter and it will display the
result.
Using IDLE
Using IDLE’s EditorWindow
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Using IDLE’s EditorWindow
• Syntax Error
• Runtime Error
Syntax Error
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Rules For Identifiers
• What is an identifier?
• Identifier isthe name given to entities like class, functions,
variables, modules and any other object in Python.
Data Types
• Numeric Types
• DifferentTypes Of Integers
• Numeric Types
• Boolean Type
• Sequence Types
• Set Types
• Mapping Type
• None Type
• Given on the next slide are the names of actual data types
belonging to the above mentioned categories
Basic Data Types In Python
complex bytes
bytearray
tuple
range
SomeVery Important Points
Another important
observation we can make
is that in Python all the
data types are
implementted as classes
and all variables are
objects
SomeVery Important Points
• This initial size for int is 24 bytes and then increases as the
value is increased
a=10
b=256
c=-4
print(a)
print(b)
print(c)
Output:
10
256
-4
Numeric Types In Python
3. As octal number(base 8)
3. Example:
a=25
Numeric Types In Python
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Numeric Types In Python
Syntax : bin(a)
Some Examples:
1. Converting decimal base to binary
Some Examples:
Syntax : oct(a)
Some Examples:
1. Converting decimal base to octal
Some Examples:
Syntax : hex(a)
Some Examples:
1. Converting decimal base to hexadecimal
Some Examples:
• The boolType
• So 2.5 , 3.14 , 6.9 etc are all examples of float data type
• The real part can be specified in any int form i.e. decimal ,
binary , octal or hexadecimal but the imaginary part
should only be in decimal form
Some Important Points
About complex Data Type
• Don’t think real and imag are functions , rather they are
attributes/properties of complex data type
The bool Data Type
• For example:
NONE!
Both will give error.
Correct way is to use either triple single quotes or triple
double quotes or escape sequence character \
msg=' ' 'Let's learn "Python" ' ' '
OR
msg='Let\'s learn "Python" '
Some Important Points
About Strings
Some Important Points
About Strings
Some Important Points
About Strings
• Concatenating Strings
• Type Conversion
String Concatenation
• Example: • Example:
s1=“Good”
s1=“Good” s2=“Morning”
s2=“Morning” s3=s1+” “+s2
s3=s1+s2 print(s3)
print(s3)
• Output:
• Output: Good Morning
GoodMorning
The Slicing Operator
• Example: • Example:
s=“Industry” s=“Welcome”
print(s[2:6]) print(s[3:6])
• Output: • Output:
dust com
The Slicing Operator
• Example: • Example:
s=“Mumbai” s=“Mumbai”
print(s[0:3]) print(s[0:10])
• Output: • Output:
Mum Mumbai
The Slicing Operator
• Example: • Example:
s=“Python” s=“Python”
print(s[2:2]) print(s[6:10])
• Output: • Output:
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[1:]) print(s[:3])
• Output: • Output:
elcome wel
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[:]) print(s[])
• Output: • Output:
welcome Syntax Error
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[-4:-1]) print(s[-1:-4])
• Output: • Output:
com
Using Step Value
s[begin:end:step]
• Output:
dust
• Outp
ut: ds
• Can also be written
as :
s=“Industry”
print(s[2:6:1])
• Output:
dust
Three Very Useful
Functions/Methods
Of String Data Type
• len()
• lower()
• upper()
Three Very Useful
Functions/Methods
Of String Data Type
• Syntax: s.upper()
Comparing Strings
Now the first two characters from str1 and str2 ( I and I ) are compared.
Because they are also equal, the third two characters ( d and d ) are
compared.
Since they also are equal , the fourth pair (o and i) is compared and there
we get a mismatch .
• There are some cases , where Python will not perform type
conversion automatically and we will have to explicitly
convert one type to another.
• Syntax: int(value)
int(2.3)
Output:
2
int(False)
Output:
0 int() cannot convert
int(True) complex type to int
type
Output:
1
int(3+4j)
Output:
TypeError: Can’t convert complex to int
int( ) Examples
int(“25”)
Output: int() cannot accept
anything other than
25 digits in a string
int(“2.5”)
Output:
ValueError: Invalid literal for int()
int(“1010”)
int() cannot accept
Output: binary values as
1010 string
int(“0b1010”)
Output:
ValueError: Invalid literal for int()
SolutionTo The
Previous Problem
a=10 Solution:
b=“6” a=10
b=“6”
c=a+b
c=a+int(b)
print( c ) print( c )
Output: Output:
TypeError 16
The float( ) Function
• Syntax: float(value)
float(25)
Output:
25.0
float(False)
Output:
0.0 float() cannot
float(True) convert complex
type to float type
Output:
1.0
float(3+4j)
Output:
TypeError: Can’t convert complex to float
float( ) Examples
float(“25”) float(“twenty”)
Output: Output:
25.0 ValueError:Could not convert string
float(“2.5”) to float
Output:
2.5
float(“1010”) float() cannot
Output: accept any int value
other than base 10
1010.0 as string
float (“0b1010”)
Output:
ValueError:Could not convert string to float
The complex( ) Function
• Syntax: complex(value)
complex(25)
Output:
(25+0j)
complex(2.5)
Output:
(2.5+0j)
complex(True)
Output:
(1+0j)
complex(False)
Output:
0j
complex( ) Examples
complex(“25”) complex(“twenty”)
Output: Output:
(25+0j) ValueError: complex() arg is a
complex(“2.5”) malformed string
Output:
(2.5+0j)
complex(“1010”) complex() cannot
Output: accept any int value
(1010+0j) other than base 10 as
string
complex (“0b1010”)
Output:
ValueError: complex() arg is a malformed string
The bool ( ) Function
• Syntax: bool(value)
bool(1)
Output:
True
bool(5)
Output:
True
bool(0)
Output:
False
bool(0.0)
Output:
False
bool( ) Examples
bool(0.1)
Output:
True
bool(0b101)
Output:
True
bool(0b0000) bool() returnsTrue if
Output: any of the real or
False imaginary part is non
zero . If both are zero
bool(2+3j) it returns False
Output:
True
bool( ) Examples
bool(0+1j) bool(“twenty”)
Output: Output:
True True
bool(0+0j) bool(' ')
Output: Output:
True
False
bool('')
Output: bool() returns False
for empty Strings
False otherwise it returns
bool('A') True
Output:
True
The str( ) Function
• Syntax: str(value)
str(15)
Output:
‘15’
str(2.5)
Output:
‘2.5’
str(2+3j)
Output:
‘(2+3j)’
str(True)
Output:
‘True’
str( ) Examples
str(1)
Output:
‘1’
str(5)
Output:
‘5’
str(2.5)
Output:
‘2.5’
str(True)
Output:
‘True’
PYTHON
LECTURE 8
Today’sAgenda
• The is Operator
Understanding Python
Variables
a=10
a=20
a=30
1. Garbage Block
2. The GarbageCollection
3. Reference Counting
The Garbage Block
• In Python , if an object is not being referred by any
reference , then such objects are called Garbage Blocks.
The Garbage Block
The Garbage Collection
• Garbage collection is the process of cleaning the
computer memory which was used by a running program
when that program no longer needs that memory .
a=10
a=20
a=30
• DISADVANTAGE:
a=42
b=42
• Can you tell how many objects has Python created in the
above code ?
• Answer: Only 1
• By using is operator
The id( ) Function
• id() is a built-in function in Python 3, which returns
the identity of an object.
• For example:
#a=a+1
#b=b+5
#c=c+10
• For example:
Both the lines
a=10 get
commented
' ' ' a=a+1 out and are
a=a+1 ' ' ' not executed
print(a)
Output:
10
Why It Is Un Official ?
• They are regular multiline strings , but since they are not
getting assigned to any variable , they will get garbage
collected as soon as the code runs.
• For example:
PI=3.14
MAX_MARKS=100
• Example:
• Example:
a=“Good”
a=“Good” b=10
b=“Morning” print(a+b)
print(a+b)
• Output:
• Output:
TypeError
GoodMorning
The print( ) Function
• Example: • Example
:
a=“Good” a=“Good”
b=“Morning” b=10
print(a,b) print(a,b)
• Output:
• Output: Good 10
Good Morning
• Exampl • Example
:
e: a=10 a=“Good”
b=20 b=10
print(a,b) print(a,b)
• Output: • Output:
10 20 Good 10
The print( ) Function
• Example:
name=“Sachin”
print(“My name is“, name)
• Output:
My name is Sachin
The print( ) Function
• Example:
age=32
print(“My age is“, age)
• Output:
My age is 32
The print( ) Function
• Example:
name=“Sachin”
age=32
print(“My name is“, name,”and my age is”,age)
• So the statement :
• print(“Good”,”Morning”)
• Examp • Examp
le:
le: a=10 hh=10
b=20 mm=30
print(a,b,sep=“#”) ss=45
print(hh,mm,ss,sep=“:”)
• Output:
• Output:
10:30:45
10#20
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 10
QUIZ 2- TestYour Skills
A. 31 characters
B. 63 characters
C. 79 characters
D. none of the mentioned
Correct Answer: D
QUIZ 2- TestYour Skills
A. Class
B. List
C. Str
D. Tuple
Correct Answer: A
QUIZ 2- TestYour Skills
A. hel
B. he
C. Lo
D. olleh
Correct Answer: B
QUIZ-Test Your Skills
A. int
B. float
C. bool
D. dict
Correct Answer: A
QUIZ-Test Your Skills
Correct Answer: C
QUIZ-Test Your Skills
A. k = 2 + 3j
B. k = complex(2)
C. k = 2 + 3I
D. k = 2 + 3J
Correct Answer: C
QUIZ-Test Your Skills
A. k = 0b101
B. k= 0x4f5
C. k = 19023
D. k = 0o3964
Correct Answer: D
QUIZ-Test Your Skills
A. False
B. True
C. SyntaxError
D. 0
Correct Answer: B
QUIZ-Test Your Skills
A. List
B. Tuple
C. Both
D. None
Correct Answer: A
QUIZ-Test Your Skills
A. Yes
B. No
Correct Answer: A
QUIZ-Test Your Skills
A. Yes
B. No
Correct Answer: B
QUIZ-Test Your Skills
A. Yes
B. No
Correct Answer:B
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
QUIZ- Test Your Skills
A. include math
B. import math
C. #include<math.h>
D. using math
Correct Answer: B
QUIZ-Test Your Skills
A. chr
B. char
C. str
D. None Of The Above
Correct Answer: D
QUIZ- Test Your Skills
Correct Answer: C
Today’sAgenda
• Operators In Python
• Types Of Operators
• Arithmetic Operators
• Arithmetic Operators
• Logical Operators
• Assignment Operator
• Identity Operators
• Membership Operators
Arithmetic Operators
In Python
+
(Arithmetic Addition)
-
(Subtraction)
*
(Arithmetic Multiplication)
/
(Float Division)
%
(Modulo Division)
//
(Floor Division)
**
(Power or Exponentiation)
The 5 Basic Arithmetic
Operators
mymath.py
a=10
b=4
print("sum of",a,"and",b,"is",a+b)
print("diff of",a,"and",b,"is",a-b)
print("prod of",a,"and",b,"is",a*b)
print("div of",a,"and",b,"is",a/b)
print("rem of",a,“and",b,"is",a%b)
The 5 Basic Arithmetic
Operators
The Output:
Two Special
Operators // and **
• Means it returns the integer part and not the decimal part.
• Example: • Example:
a=10.0
a=10 b=4
b=4 print(a//b)
print(a//b)
• Output:
• Output: 2.0
2
• Example: • Example:
a=97
a=97 b=10.0
b=10 print(a//b)
print(a//b)
• Output:
• Output: 9.0
9
The Floor Division Operator
• Examp • Examp
le:
le: a=- a=19
10 b=4 b=-2
print(a//b) print(a//b)
• Output: • Output:
-3 -10
The Floor Division Operator
• Examp • Examp
le: a=-
le: a=- 19 b=-2
10 b=-4 print(a//b)
print(a//b)
• Output:
• Output: 9
2
An Important Point
• Exampl • Example:
e: a=10 a=10
b=0.0
b=0 print(a/b)
print(a/b)
• Output: Output:
ZeroDivisionError ZeroDivisionError
Division By 0
• Examp • Example:
a=10
le: b=0.0
a=10 print(a//b)
b=0
print(a//b)
• Output:
ZeroDivisionError
• Output:
ZeroDivisionError
Division By 0
• Examp • Example:
a=10
le: b=0.0
a=10 print(a%b)
b=0
print(a%b)
• Output:
ZeroDivisionError
• Output:
ZeroDivisionError
The power (**)Operator
• For example:
a=10
b=3
print(a**b)
• Output:
1000
Double Role Of The Operator +
• For
example: a=“Good”
a=10 b=“Evening”
b=5 print(a+b)
print(a+b)
Output:
Output:
15 GoodEvening
Double Role Of The Operator +
• Example: • Example:
a=“Good”
a=“Good” b=“10”
b=10 print(a+b)
print(a+b)
• Output:
• Output: Good10
TypeError
Double Role Of The Operator *
• For
example: a=“Sachin”
a=10 b=3
b=5 print(a*b)
print(a*b)
Output: Output:
50 SachinSachinSachin
The * Operator
• Examp • Example:
a=“Sachin”
le: a=5 b=3.0
b=4.0 print(a*b)
print(a*b)
• Output:
• Output: Type Error :
20.0 Can’t multiply
by non int
The * Operator
• Example: • Example:
a=“Sachin”
a=“Sachin” b=“Kapoor”
b=3 print(a*b)
print(b*a)
• Output:
• Output: Type Error :
SachinSachinSachin Can’t multiply
by non int
PYTHON
LECTURE 11
Today’s Agenda
• Operators In Python
• Relational Operators
Operator Meaning
> Greater Than
< Less Than
>= Greater Than Equal To
<= Less Than Equal To
== Equal To
!= Not Equal To
The 6 Basic Relational Operators
myrelop.py
a=10
b=4
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
The 6 Basic Relational Operators
The Output:
Relational Operators With Strings
myrelop2.py
a="Ramesh"
b="Rajesh"
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
Relational Operators With Strings
The Output:
Relational Operators With Strings
Example:
ord(‘A’)
65
ord(‘m’)
109
ord(‘j’)
106
Relational Operators With Strings
myrelop4.py
a= "BHOPAL"
b= "bhopal"
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
Relational Operators With Strings
The Output:
Will This Code Run ?
• Example: • Example:
print(5<6>7)
print(7>6>5)
• Output:
• Output:
False
True
Cascading Of Relational Operators
• Example: • Example:
print(5<6<7)
print(5>6>7)
• Output:
• Output:
True
False
Special Behavior Of
== And !=
• Example: • Example:
print(10==20)
print(10==10)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(10==True)
print(10==“10”)
• Output: • Output:
False False
Special Behavior Of
== And !=
• Example: • Example:
print(“A”==“A”)
print(1==True)
• Output:
• Output:
True
True
Special Behavior Of
== And !=
• Example: • Example:
print(“A”==65)
print(“A”==“65”)
• Output:
• Output:
False
False
Special Behavior Of
== And !=
• Example: • Example:
print(15==15.01)
print(15==15.0)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(0 != False)
print(15!=“15”)
• Output:
• Output: False
True
Special Behavior Of
== And !=
• Example: • Example:
print(False != 0.0)
print(False!=True)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(2+5j!= 2)
print(2+5j==2+5j)
• Output:
• Output:
True
True
PYTHON
LECTURE 12
Today’s Agenda
• Operators In Python
• Logical Operators
Operator Meaning
3. If the first value is False , then Logical and returns first value
, otherwise it returns the second value
• Example: • Example:
5 and 0
5 and 6
• Output:
• Output:
0
6
Logical Operators
On Non Boolean Types
• Example: • Example:
6 and 0
0 and 10
• Output:
• Output:
0
0
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Sachin’ and 0
‘Sachin’ and 10
• Output:
• Output:
0
10
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Indore’ and ‘Bhopal’ ‘Bhopal’ and ‘Indore’
• Output: • Output:
Bhopal Indore
Logical Operators
On Non Boolean Types
• Example: • Example:
0 and 10/0 10/0 and 0
• Output: • Output:
0 ZeroDivisionEror
Logical Operators
On Non Boolean Types
• Example: • Example:
5 or 0
5 or 6
• Output:
• Output:
5
5
Logical Operators
On Non Boolean Types
• Example: • Example:
6 or 0
0 or 10
• Output:
• Output:
6
10
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Sachin’ or 0
‘Sachin’ or 10
• Output:
• Output:
Sachin
Sachin
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Indore’ or ‘Bhopal’ ‘Bhopal’ or ‘Indore’
• Output: • Output:
Indore Bhopal
Logical Operators
On Non Boolean Types
• Example: • Example:
0 or 10/0 10/0 or 0
• Output: • Output:
ZeroDivisionError ZeroDivisionEror
Logical Operators
On Non Boolean Types
• Example: • Example:
not 5 not 0
• Output: • Output:
False True
Logical Operators
On Non Boolean Types
• Example: • Example:
not ‘Sachin’ not ‘’
• Output: • Output:
False True
PYTHON
LECTURE 13
Today’s Agenda
• Operators In Python
• Assignment Operators
• Compound Operators
• Identity Operators
• Membership Operators
For example:
a=10
Assignment Operators In Python
a,b,c=10,20
print(a,b,c)
Output:
ValueError : Not enough values to unpack
a,b,c=10,20,30,40
print(a,b,c)
Output:
ValueError : Too many values to unpack
Compound Assignment Operators
+= x+=5 x=x+5
-= x-=5 x=x-5
*= x*=5 x=x*5
/= x/=5 x=x/5
%= x%=5 x=x%5
//= x//=5 x=x//5
**= x**=5 x=x**5
Guess The Output
a=10
Conclusion:
print(++a) Python does not has any
increment operator like ++.
Output:
10 Rather it is solved as
+(+x) i.e +(+10) which is 10
a=10
However the expression a++
print(a++) is an error as it doesn’t make
any sense
Output:
SyntaxError : Invalid Syntax
Guess The Output
a=10
Conclusion:
print(--a) Python does not has any
decrement operator like --.
Output:
10 Rather it is solved as
-(-x) i.e -(-10) which is 10
a=10
However the expression a--
print(a--) is an error as it doesn’t make
any sense
Output:
SyntaxError : Invalid Syntax
Guess The Output
a=10
Try to figure out yourself
print(+++++a) the reason for these outputs
Output:
10
a=10
print(-----a)
Output:
-10
Identity Operators
a=2 a=2
b=3 b=2
c=a is b c=a is b
print(c) print(c)
Output: Output:
True
False
Explanation: Explanation:
Since a and b are pointing Since a and b are pointing
to 2 different objects, so to same objects, so
the operator is returns False the operator is returns True
Examples Of is Operator
a=2 a=2
b=type(a) is int b=type(a) is float
print(b) print(b)
Output: Output:
True False
Explanation: Explanation:
type(a) is int evaluates type(a) is float evaluates
to True because 2 is indeed an to False because 2 is not a float
integer number. number.
Examples Of is not Operator
a=“Delhi” a=“Delhi”
b=“Delhi” b=“delhi”
c=a is not b c=a is not b
print(c) print(c)
Output: Output:
True
False
Explanation: Explanation:
Since a and b are pointing Since a and b are pointing
to the same object, so to 2 different objects, so
the operator is not returns False the operator is not returns True
Membership Operators
in
not in
Behavior Of in and not in
not in : The ‘not in’ operator is the opposite of ‘in’ operator. So,
if a value does not exists in the sequence then it will return a
True else it will return a False.
Examples Of in Operator
a=“Welcome” a=“Welcome”
b=“om” b=“mom”
print(b in a) print(b in a)
Output: Output:
False
True
Examples Of not in Operator
primes=[2,3,5,7,11] primes=[2,3,5,7,11]
x=4 x=5
print(x not in primes)
print(x not in primes)
Output: Output:
True False
Precedence Of Operators
Operator Name
() Parentheses
** Exponent
+, - Addition, Subtraction
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR
Guess The Output
a=6/2+3**4 a=25/(2+3)**2
print(a) print(a)
Output: Output:
1.0
84.0
a=20-12//3**2
print(a)
Output:
19
Associativity Of Operators
a=5*2//3
print(a)
Output:
3
a=5*(2//3)
print(a)
Output:
0
Guess The Output
a=2**3**2
Remember , ** has
print(a)
Right to left
assoiativity
Output:
512
a=(2**3)**2
print(a)
Output:
64
PYTHON
LECTURE 14
Today’s Agenda
Syntax:
input([prompt])
Output:
Example 2
(Using input( ) With Message)
Output:
Example 3
(Using input( ) With Message)
Output:
Accepting Integer Input
a=input("enter a number\n")
b=a+1
print(b)
Output:
Accepting Integer Input
a=input("enter a number\n")
b=int(a)+1
print(b)
OR
a=int(input("enter a number\n")
b=a+1
print(b)
Accepting Float And Bool
Example:
s=input("enter your percentage\n")
per=float(s)
print(per)
OR
s=input(“Delete the file ?(yes-True,no-False)")
ans=bool(s)
print(ans)
Exercise
WAP to accept two numbers from the user and display their
sum
Code:
a=int(input("Enter first num:"))
b=int(input("Enter secnd num:"))
c=a+b
print("Nos are",a,"and",b)
print("Their sum is",c)
Exercise
Code:
import math
radius=float(input("Enter radius:"))
area=math.pi*math.pow(radius,2)
circum=math.tau*radius
print("Area is",area)
print("Circumference is",circum)
Second Way To Import
A Module
Syntax:
import modname as newname
This helps us to use short names for modules and make them
more easy to use
Using as Keyword
Code
import platform as p
print(p.system())
Second Way Of Writing Previous
Code Using math Module
Code:
import math as m
radius=float(input("Enter radius:"))
area=m.pi*m.pow(radius,2)
circum=m.tau*radius
print("Area is",area)
print("Circumference is",circum)
Third Way To Import A Module
Syntax:
from modname import name1[, name2[, ... nameN]]
In this way we will not have to prefix the module name before
the member name while accessing it
Using from Keyword
Code
from sys import getsizeof
a=10
b=“hello”
print(getsizeof(a))
print(getsizeof(b))
Third Way Of Writing Previous
Code Using math Module
Code:
from math import pi,tau,pow
radius=float(input("Enter radius:"))
area=pi*pow(radius,2)
circum=tau*radius
print("Area is",area)
print("Circumference is",circum)
Fourth Way To Import A Module
Syntax:
from modname import *
Code
from sys import *
a=10
b=“hello”
print(getsizeof(a))
print(getsizeof(b))
Fourth Way Of Writing Previous
Code Using math Module
Code:
from math import *
radius=float(input("Enter radius:"))
area=pi*pow(radius,2)
circum=tau*radius
print("Area is",area)
print("Circumference is",circum)
How To List
All Members Of A Module
Write a program that asks the user to enter his/her name and
age. Print out a message , displaying the user’s name along
with the year in which they will turn 100 years old.
Code:
s=input("Enter 2 numbers:")
a,b=s.split()
print("First number is",a);
print("Second number is",b)
c=int(a)+int(b)
print("Their sum is",c)
Accepting Multiple
Values Separated With ,
Code:
s=input("Enter 2 numbers separated with comma:")
a,b=s.split(",")
print("First number is",a);
print("Second number is",b)
c=int(a)+int(b)
print("Their sum is",c)
Accepting Different Values
In One Line
Code:
s=input("Enter roll no,name and per:")
roll,name,per=s.split()
print("Roll no is",roll)
print("Name is",name)
print("Per is",per)
PYTHON
LECTURE 15
Today’s Agenda
Syntax:
eval(expression)
• Example: • Example:
x = eval(‘2+3*6’)
x = eval(’2+3’)
print(x)
print(x)
• Output:
5
• Output:
20
Examples
• Example: • Example:
x=eval('print(15)')
eval(‘print(15)’)
print(x)
• Output:
• Output:
15
15
None
Examples
• Example: • Example:
from math import sqrt
x=eval('print()')
x = eval(‘sqrt(4)’)
print(x) print(x)
• Output:
• Output: 2.0
None
Using eval( ) For
Type Conversion
Code:
age = eval(input("Enter your age "))
age=age+10
print("After 10 years , you will be ",age, "years old")
Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Command Line Arguments
For example:
python demo.py 10 20 30
The name of the program is passed as the first argument which is stored
at the 0th index in argv
Example
Code:
from sys import argv
print(argv[0])
print(argv[1])
print(argv[2])
Code:
If we try to access
from sys import argv argv beyond it’s last
print(argv[0]) index then
Python will throw
print(argv[1]) IndexError exception
print(argv[2])
Output:
cmdarg.py
IndexError: list index out of range
Obtaining Number
Of Arguments Passed
Code:
from sys import argv
n=len(argv)
print("You have passed",n-1,"arguments")
Output:
Using Slicing Operator
Output:
[]
Guess The Output
Code: addnos.py
from sys import argv
print(“First num is“,argv[1])
print(“Sec num is“,argv[2])
print(“Their sum is”,argv[1]+argv[2])
Code:
from sys import argv
a=eval(argv[1])
b=eval(argv[2])
print("Nos are",a,"and",b)
print("Their sum is",a+b)
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Output:
Hello Sachin Kapoor
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Syntax:
print(“format specifier” %(variable list))
Example:
a=10
print(“value of a is %d “ %(a))
Output:
value of a is 10 If a single variable is
there then parentesis
can be dropped
Using Format Specifiers
With print()
Example:
a=10
msg=“Welcome”
c=1.5
print(“values are %d , %s,%f“ %(a,msg,c))
Output:
Values are 10, Welcome, 1.500000 Number of format
specifiers must
exactly match with
the number of
vlaues in the
parenthesis
Key Points About Format Specifiers
However we can use %s with non string values also , like boolean
Examples
a=10
print(“%s” %a)
Output:
10
a=10
print(“%f” %a)
Output:
10.000000
Examples
a=10.6 a=10.6
print(“%f” %a) print(“%d” %a)
Output:
Output:
10
10.600000
a=10.6 a=10.6
print(“%s” %a)
print(“%.2f” %a)
Output:
Output:
10.6
10.60
Examples
a=True a=True
print(“%s” %a) print(“%f” %a)
Output:
Output:
1.000000
True
a=True
print(“%d” %a)
Output:
1
Examples
a=“Bhopal” a=“Bhopal”
print(“%s” %a) print(“%f” %a)
Output:
Output:
TypeError
Bhopal
a=“Bhopal”
print(“%d” %a)
Output:
TypeError: number required , not str
Examples
a=“Bhopal” x=65
print(“%c” %a[0]) print(“%c” %x)
Output:
Output:
A
B
x=65.0
a=“Bhopal”
print(“%c” %x)
print(“%c” %a[0:2]) Output:
Output: TypeError:
TypeError: %c requires int or char
%c requires int or char
Using The Function format()
Syntax:
print(“string with { }”.format(values))
Example
name=“Sachin”
age=36
print(“My name is {0} and my age is {1}”.format(name,age))
Output:
My name is Sachin and my age is 36
Examples
name=“Sachin”
age=36
print(“My name is {1} and my age is {0}”.format(age,name))
Output:
My name is Sachin and my age is 36
PYTHON
LECTURE 16
Today’s Agenda
• Concept of Indentation
Syntax:
if (expression):
statement1
statement2
.
.
statement..n
A code block starts with indentation and ends with the first unindented line.
The colon after if( ) condition is important and is a part of the syntax. However parenthesis
with condition is optional
Exercise
Solution 1:
a=eval(input("Enter a number:"))
if(a%2==0):
print("No is even") If the body of if( )
statement contains
if(a%2!=0): only one statement ,
print("No is odd") then we can write it
just after if( )
statement also
Solution 2:
if(a%2==0):print("No is even")
if(a%2!=0):print("No is odd")
What About Multiple Lines ?
OR
Solution 1:
if(a%2==0):
print("No is even")
print(“Hello”)
if(a%2!=0):
print("No is odd")
print(“Hi”)
Solution 2:
if(a%2==0): print("No is even");print(“Hello”)
if(a%2!=0): print("No is odd");print(“Hi”)
The if –else Statement
Syntax:
if (expression):
statement 1
statement 2
else:
statement 3
statement 4
a=eval(input("Enter a number:"))
if(a%2==0):
print("No is even")
else:
print("No is odd")
Exercise
Solution 1:
We also can use the
ch=input("Enter a character:") logical and operator
if "A"<=ch<="Z": and make the
print("You entered a capital letter") conditions separate
else:
print("You entered a small letter")
Solution 2:
ch=input("Enter a character:")
if ch>="A" and ch<="Z":
print("You entered a capital letter")
else:
print("You entered a small letter")
Guess The Output
Code:
ch=input("Enter a character:")
if 65<=ch<=90:
print("You entered a capital letter")
else:
print("You entered a small letter")
Output:
TypeError: <= not supported between int and str
Why Did The Exception Occur ?
ch=input("Enter a character:")
if 65<=ord(ch)<=90:
print("You entered a capital letter")
else:
print("You entered a small letter")
The if –elif-else Statement
The elif is short for else if. It allows us to check for multiple
expressions.
Syntax:
if (expression):
statement 1
statement 2
elif (expression):
statement 3
statement 4
else:
statement 5
statement 6
ch=input("Enter a character:")
if "A" <=ch <="Z":
print("You entered a capital letter")
elif "a" <=ch <="z":
print("You entered a small letter")
elif "0" <=ch <="9":
print("You entered a digit")
else:
print("You entered some symbol")
The nested if Statement
Syntax:
if (expression):
if (expression):
statement 1
statement 2
else:
statement 3
statement 4
statement 5
statement 6
Exercise
a,b,c=input("Enter 3 int").split()
a=int(a)
b=int(b)
c=int(c)
if a>b:
if a>c:
print("{0} is greatest".format(a))
else:
print("{0} is greatest".format(c))
else:
if b>c:
print("{0} is greatest".format(b))
else:
print("{0} is greatest".format(c))
Exercise
WAP to accept an year from the user and check whether it is a leap
year or not.
For example:
2017 is not a leap year
2012 is a leap year
1900 is a not leap year
2000 is a leap year
Ternary Operator In Python
Syntax:
Example 1:
age=12
msg=‘Kid’ if age<13 else ‘Teenager’
print(msg) These codes internally
become:
Output:
Kid if age<13:
msg=‘Kid’
else:
Example 2: msg=‘Teenager’
age=16
msg=‘Kid’ if age<13 else ‘Teenager’
print(msg)
Output:
Teenager
Example
Output:
Handling Multiple Conditions
Syntax:
<expression1> if <condition1> else <expression2> if <condition2> else
<expression3>
Example 1:
age=16
msg=‘Kid’ if age<13 else ‘Teenager’ if age<20 else ‘Adult’
print(msg) if age<13:
Output: msg=‘Kid’
else:
Teenager
if age<20:
msg=‘Teenager’
else:
Example 2:
msg=‘Adult’
age=21
msg=‘Kid’ if age<13 else ‘Teenager’ if age<20 else ‘Adult’
print(msg)
Output:
Adult
PYTHON
LECTURE 17
Today’s Agenda
• Iterative Statements
• Types of loop supported by Python
Syntax:
while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>
Some Important Points:
First the condition is evaluated. If the condition is true then statements in the while block is
executed.
After executing statements in the while block the condition is checked again and if it is still true,
then the statements inside the while block is executed again.
The statements inside the while block will keep executing until the condition is true.
When the condition becomes false loop terminates and program control comes out of the while
loop to begin the execution of statement following it.
Examples
• Example 1: • Example 2:
i=1
i=1
total=0
while i<=10: while i<=10:
print(i) print(i)
i=i+1 total+=i
print("done!") i=i+1
• Output:
print("sum is
{0}".format(total))
• Output:
Guess The Output
i=1 i=1
This is an while i<=10:
while i<=10: infinite print(i)
print(i) loop total+=i
i=i+1 i=i+1
print("done!") print("sum is
• Output: {0}".format(total))
• Output:
Another Form Of “while” Loop
Syntax:
while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
else:
<indented statement 1>
<indented statement 2>
Some Important Points:
Many programmer’s have a doubt that If the statements of the additional else part were
placed right after the while loop without an else, they would have been executed anyway,
wouldn't they.
Normally a while loop ends only when the test condition in the
loop becomes false.
• Example 1: • Example 2:
i=1
i=1
while i<=10:
while i<=10: print(i)
if(i==5): i=i+1
break else:
print(i) print("bye")
i=i+1
else: Output:
print("bye")
Output:
Exercise
Sample Output:
Exercise
import random
a=random.randint(1,20)
print("Random number is",a)
Output:
The “continue” Statement
i=0
while i<10:
i=i+1
if(i%2!=0):
continue
print(i)
Output:
Exercise
Sample Output:
Exercise
Sample Output:
Exercise
Sample Output:
The “pass” Statement
Example:
Example
i=0
while i<10:
i=i+1
if(i%2!=0):
pass
else:
print(i)
Output:
PYTHON
LECTURE 18
Today’s Agenda
Numeric Ranges
This kind of for loop is a simplification of the previous kind.
Starting with a start value and counting up to an end value, like
for i = 1 to 100
Python doesn't use this either.
The for Loop
This kind of for loop is known in most Unix and Linux shells and it
is the one which is implemented in Python.
Syntax Of for Loop In Python
Syntax:
for some_var in some_collection:
# loop body
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>
Some Important Points:
The for loop in Python can iterate over string , list, tuple , set,frozenset,
bytes,bytearray and dictionary
The first item in the collection is assigned to the loop variable.
Then the block is executed.
Then again the next item of collection is assigned to the loop variable, and the
statement(s) block is executed
This goes on until the entire collection is exhausted.
Examples
• Example 1: • Example 2:
word="Sachin"
fruits=["Apple","Bana
for ch in word: na","Guava","Ora
print(ch) nge"]
for fruit in fruits:
print(fruit)
Output:
• Output:
Exercise
Write a program using for loop to accept a string from the user
and display it vertically but don’t display the vowels in it.
Sample Output:
QUIZ- Test Your Skills
A. schn
B. Error
C. sachin
D. Exception
Correct Answer: B
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop
Correct Answer: A
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop
Correct Answer: C
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. No output
Correct Answer: D
QUIZ- Test Your Skills
x = 123
for i in x:
print(i)
A. 123
B. 1
2
3
C. TypeError
D. Infinite loop
Correct Answer: C
QUIZ- Test Your Skills
Correct Answer: A
QUIZ- Test Your Skills
i=1
while True:
if i%2 == 0:
break
print(i,end=“ “)
i += 2
A. 1
B. 1 2
C. Infinite loop
D. Syntax Error
Correct Answer: C
QUIZ- Test Your Skills
A. abcdef
B. iiiiii
C. Error
D. No output
Correct Answer: D
QUIZ- Test Your Skills
A. abcdef
B. Infinite loop
C. Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. aaaaaa
B. a
C. Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. aBCD
B. ABCD
C. abcd
D. Syntax Error
Correct Answer: C
QUIZ- Test Your Skills
A. aBCD
B. ABCD
C. abcd
D. Syntax Error
Correct Answer: B
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y, ,n,a,m,e, ,i,s, ,s,a,c,h,i,n,
C. Syntax Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y,n,a,m,e,i,s,s,a,c,h,i,n
C. Syntax Error
D. No output
Correct Answer: A
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y,n,a,m,e,i,s,s,a,c,h,i,n
C. Syntax Error
D. No output
Correct Answer: C
QUIZ- Test Your Skills
True = False
while True:
print(True)
break
A. True
B. False
C. No output(Blank Screen)
D. None of the above
Correct Answer: D
QUIZ- Test Your Skills
A. Infinite loop
B. 24
C. 23
D. None of the above
Correct Answer: B
The range Function
Syntax:
range(n)
Example:
a=range(10) As we can see that when we display
the variable a , we get to see the description
print(a) of the range object and not the values.
Output:
To see the values , we must convert
range object to list
The range Function
With One Parameter
Syntax:
range(m,n)
Example:
a=range(1,10) Here again when we display
the variable a , we get to see the description
print(a) of the range object and not the values.
Output: So we must use the function list( ) to get
the values
The range Function
With Two Parameter
Example:
a=range(-10,3) Since 3 falls on right of -10 ,
so we are getting range of numbers from
b=list(a)
-10 to 3
print(b)
Output:
Guess The Output
a=range(-10,-3) a=range(-3,-3)
b=list(a) b=list(a)
print(b)
print(b)
Output:
Output:
a=range(-3,-10)
b=list(a)
print(b)
Output:
The range Function
With Three Parameter
Syntax:
range(m,n,s)
Finally, the range() function can also take the third parameter .
This is for the step value.
Example:
a=range(1,10,2)
b=list(a) Since step value is 2 , so we got nos
print(b) from 1 to 9 with a difference of 2
Output:
Guess The Output
a=range(5,10,20)
b=list(a) Here, note that the
first integer, 5, is
print(b) always returned, even
though the interval 20
Output: sends it beyond 10
Guess The Output
a=range(5,10,0)
b=list(a) It raised a ValueError
because the interval
print(b) cannot be zero if we
Output: need to go from one
number to another.
Guess The Output
a=range(2,12)
The default value of
b=list(a) step is 1 , so the output
print(b) is from 2 to 11
Output:
a=range(12,2)
b=list(a) As usual , since the start
print(b) value is greater than
end value so we get an
Output: empty list
Using range( ) With for Loop
We can use range() and for together for iterating through a list
of numeric values
Syntax:
for <var_name> in range(end):
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(11):
print(i)
Output:
Using 2 Parameter
range( ) With for Loop
Syntax:
for <var_name> in range(start,end)
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(1,11):
print(i)
Output:
Exercise
Sample Output:
Solution
num=int(input("Enter an int:"))
total=0
for i in range(1,num+1):
total=total+i
print("sum of nos from 1 to {} is {}".format(num,total))
Exercise
Sample Output:
Using 3 Parameter
range( ) With for Loop
Syntax:
for <var_name> in range(start,end,step)
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(1,11,2):
print(i)
Output:
Example
Code:
for i in range(100,0,-10):
print(i)
Output:
Using for With else
Just like while , the for loop can also have an else part , which
executes if no break statements executes in the for loop
Syntax:
for <var_name> in some_seq:
indented statement 1
if test_cond:
break
else:
indented statement 3
indented statement 4
Example
Code: Output:
for i in range(10):
print(i)
else:
print(“Loop complete”)
Example
Code: Output:
for i in range(1,10):
print(i)
if i%5==0:
break
else:
print(“Loop complete”)
Using Nested Loop
Syntax:
for <var_name> in some_seq:
for <var_name> in some_seq:
indented statement 1
indented statement 2
Example
Code: Output:
numbers = [1, 2, 3]
alpha = ['a', 'b', 'c']
for n in numbers:
print(n)
for ch in alpha:
print(ch)
Exercise
Sample Output:
Solution
Code: Output:
for i in range(1,5):
for j in range(1,4):
print("*",end="")
print()
Solution
Code:
for i in range(1,5):
print("*"*3)
Exercise
Sample Output:
Solution
Code: Output:
for i in range(1,5):
for j in range(1,i+1):
print("*",end="")
print()
Exercise
Sample Output:
Solution
Code: Output:
for i in range(4,0,-1):
for j in range(1,i+1):
print("*",end="")
print()
Exercise
Code: Output:
x = int(input('Enter a number: '))
while x != 0:
for y in range (1, x+1):
print (y)
x = int(input('Enter a number: '))
PYTHON
LECTURE 19
Today’s Agenda
• Calling A Function
For example:
print(“hello”)
message=“Good Morning”
print(message.lower())
def add(a,b):
print("Values are",a,"and",b)
c=a+b
print("Their sum is",c)
How To Call A Function ?
Syntax:
function_name(arguments)
Complete Example
def add(a,b):
print("Values are",a,"and",b)
c=a+b
print("Their sum is",c)
add(5,10)
add(2.5,5.4)
Output:
Returning Values
From Function
Syntax:
return <expression>
Complete Example
def add(a,b):
c=a+b
return c
x=add(5,10)
print("Sum of 5 and 10 is",x)
y=add(2.5,5.4)
print("Sum of 2.5 and 5.4 is",y)
Output:
Exercise
Sample Output:
Solution
def absolute(n):
if n>0:
return n
else:
return -n
x=absolute(-7)
print("absolute of -7 is",x)
y=absolute(9)
print("absolute of 9 is",y)
Exercise
Sample Output:
Solution
def factorial(n):
f=1
while n>1:
f=f*n
n=n-1
return f
x=int(input("Enter an int:"))
y=factorial(x)
print("Factorial of",x,"is",y)
Guess The Output
def greet(name):
print("Hello",name)
greet("sachin")
greet()
Output:
Guess The Output
def greet(name):
print("Hello",name)
greet("sachin", "amit")
Output:
Guess The Output
def greet(name):
print("Hello",name)
return
print("bye")
greet("sachin")
Output:
Guess The Output
def greet(name):
print("Hello",name)
x=greet("sachin")
print("value in x is",x)
Output:
Returning Multiple Values
From Function
Syntax:
return <value 1, value 2, value 3, . . . >
For example:
return a,b,c
Syntax 1:
var 1,var 2,var 3=<function_name>()
Syntax 2:
var=<function_name>()
def calculate(a,b):
Here Python will
c=a+b automatically set x
d=a-b and y to be of int
type and z to be of
return c,d tuple type
x,y=calculate(5,3)
print("Sum is",x,"and difference is",y)
z=calculate(15,23)
print("Sum is",z[0],"and difference is",z[1])
Output:
PYTHON
LECTURE 20
Today’s Agenda
• Types Of Arguments
Parameters V/s Arguments?
Positional Argument
Keyword Argument
Default Argument
def attach(s1,s2):
s3=s1+s2 These are called
print("Joined String is:",s3)
POSITIONAL
ARGUMENTS
attach("Good","Evening")
Output:
Positional Arguments
def attach(s1,s2):
s3=s1+s2
print("Joined String is:",s3)
attach("Good")
Output:
Guess The Output
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery("Bread",20)
grocery(150,"Butter")
Output:
The Problem With
Positional Arguments
Syntax:
function_name(paramname1=value,paramname2=value)
Complete Example
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery(name="Bread",price=20)
grocery(price=150,name="Butter")
Output:
Point To Remember!
For example:
def display(num1,num2):
# some code
Syntax:
def function_name(paramname1=value,paramname2=value):
# function body
Complete Example
greet("Sachin")
greet("Amit","How are you?")
Output:
Point To Remember!
If we call it as :
show(5,7)
Still it will work and output will be 5 7 30
But if we call it as
show(5, ,7)
Then it will be an error
Exercise
def cal_area(radius,pi=3.14):
area=pi*radius**2
print("Area of circle with radius",radius,"is",area)
rad=int(input("Enter radius:"))
cal_area(rad)
Guess The Output ?
def addnos(a,b):
c=a+b
return c
def addnos(a,b,c):
d=a+b+c
return d
print(addnos(10,20))
print(addnos(10,20,30))
Output:
Why Did The Error Occur ?
def addnos(*a):
sum =0
for x in a:
sum=sum+x
return sum
print(addnos(10,20))
print(addnos(10,20,30))
Output:
Exercise
def findlargest(*names):
max=0
for s in names:
if len(s)>max:
max=len(s)
return max
print(findlargest("January","February","March"))
Output:
Exercise
def findlargest(*names):
max=0
largest=""
for s in names:
if len(s)>max:
max=len(s)
largest=s
return largest
print(findlargest("January","February","March"))
Output:
Point To Remember!
def addnos(*a,*b):
Point To Remember!
def addnos(*a,n):
sum =n
for x in a:
sum=sum+x
return sum
print(addnos(20,n=10,30))
Output:
SyntaxError: Positional argument follows keyword argument
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(10,20)
Output:
10 20 3 4
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(10,20,30,40)
Output:
10 20 30 40
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(d=10,a=20,b=30)
Output:
20 30 3 10
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show()
Output:
TypeError
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(c=30,d=40,10,20)
Output:
SyntaxError
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(30,40,b=15)
Output:
TypeError : got multiple values for argument ‘b’
PYTHON
LECTURE 21
Today’s Agenda
• Local Scope
• Global Scope
• Argument Passing
Variable Scopes
GLOBAL VARIABLE
LOCAL VARIABLE
A variable which is defined inside a function is local to that function.
Output:
I love Python
Example
def f():
print(s)
s = "I love Python"
f()
Even though the
variable s has been
Output: declared after the
function f( ) , still it is
I love Python considered to be
global and can be
accessed from
anywhere in our code
Example
def f():
print(s)
f()
s="I love Python"
def f():
s="I love Python"
print(s)
f()
The variable s now
becomes a local
Output: variable and a
I love Python function can easily
access all the local
variables inside it’s
definition
Example
def f():
s="I love Python"
print(s)
f()
print(s)
The variable s is local
Output: and cannot be
I love Python accessed from outside
it’s function’s
NameError! definition
Example
Output:
I love Python
I love C
I love C
Guess The Output ?
a=1
def f():
Output:
print ('Inside f() : ', a) global : 1
def g(): inside f( ):1
a=2 global: 1
print ('Inside g() : ',a) inside g( ): 2
def h(): global : 1
global a inside h( ): 3
a=3 global : 3
print ('Inside h() : ',a)
a=0 Output:
if a == 0: 7
3
b=1 0
def my_function(c): 1
NameError!
d=3
print(c)
print(d)
my_function(7)
print(a)
print(b)
print(c)
print(d)
Guess The Output ?
a, b, x, y = 1, 15, 3,4
foo(17, 4)
print(a, b, x, y)
Argument Passing
Call by value
Call by reference.
Call By Value
def show(a):
print("Inside show , a is",a," It's id is",id(a))
Since Python uses Pass by
object reference , so when
a=10 we passed a , Python
passed the address of the
print("Outside show, a is",a,"object
It'spointed
id is",id(a))
by a and this
show(a) address was received by
the formal variable a in the
function’s argument list. So
both the references are
Output: pointing to the same object
Guess The Output ?
def increment(a):
a=a+1
a=10 When we pass a to
increment(a), the function has
increment(a) the local variable a referring to
the same object. Since integer is
print(a) immutable, so Python is not
able to modify the object’s
value to 11 in place and thus it
created a new object. But the
original variable a is still
Output: referring to the same object
with the value 10
10
Guess The Output ?
def show(mynumbers):
print("Inside show , mynumbers is",mynumbers)
mynumbers.append(40)
print("Inside show , mynumbersSince
is",mynumbers)
list is a mutable type ,
mynumbers=[10,20,30] so any change made in the
formal reference
print("Before calling show, mynumbers is",mynumbers)
mynumbers does not
show(mynumbers) create a new object in
memory . Rather it changes
print("After calling show, mynumbers is",mynumbers)
the data stored in original
list
Output:
Guess The Output ?
def show(mynumbers):
mynumbers=[50,60,70]
print("Inside show , mynumbers is",mynumbers)
If we create a new
mynumbers=[10,20,30] object inside the
print("Before calling show, mynumbers is",mynumbers)
function , then Python
will make the formal
show(mynumbers)
reference mynumbers
print("After calling show, mynumbers refer
is",mynumbers))
to that new object
but the actual
argument mynumbers ,
Output: will still be refering to
the actual object
Guess The Output ?
def foo(x):
x.append (3)
x = [8]
return x
x=[1, 5]
y= foo(x)
print(x)
print(y)
Output:
[1,5,3]
[8]
Guess The Output ?
def swap(a,b):
a,b=b,a
a=10
b=20
swap(a,b)
print(a)
print(b)
Output:
10
20
Guess The Output ?
def changetoupper(s):
s=s.upper()
s="bhopal"
changetoupper(s)
print(s)
Output:
bhopal
Guess The Output ?
def changetoupper(s):
s=s.upper()
return s
s="bhopal"
s=changetoupper(s)
print(s)
Output:
BHOPAL
PYTHON
LECTURE 22
Today’s Agenda
Syntax:
lambda [arg1,arg2,..]:[expression]
def add(a,b):
return a+b
Output:
How To Use
Lambda Functions ?
Output:
Example
squareit=lambda a: a*a
print(squareit(25))
print(squareit(10))
Output:
Example
import math
sqrt=lambda a: math.sqrt(a)
print(sqrt(25))
print(sqrt(10))
Output:
Exercise
Solution:
firstchar=lambda str: str[0]
Output:
Exercise
Solution:
Solution:
iseven=lambda n: n%2==0
print("10 is even :",iseven(10))
print("7 is even:",iseven(7))
Output:
Exercise
Solution:
Output:
PYTHON
LECTURE 23
Today’s Agenda
r = map(func, iterable)
def square(num):
return num**2
What Is map( ) Function?
mynums=[1,2,3,4,5]
mynums=[1,2,3,4,5]
for x in mynums:
print(square(x))
Complete Code
def square(num):
return num**2
mynums=[1,2,3,4,5]
for x in mynums:
print(square(x))
Output:
1
4
9
16
25
Using map( ) Function
def square(num):
return num**2
mynums=[1,2,3,4,5]
result=map(square,mynums)
print(result)
Output:
mynums=[1,2,3,4,5] mynums=[1,2,3,4,5]
result=map(square,mynums) # we can club the 2 lines in 1 line
sqrnum=list(result)
sqrnum=list(map(square,mynums))
print(squrnum)
print(sqrnum)
Output:
Previous Code Using map( )
mynums=[1,2,3,4,5]
print(list(map(square,mynums)))
Output:
Previous Code Using map( )
In case we want to iterate over this list , then we can use for loop
def square(num):
return num**2
mynums=[1,2,3,4,5]
for x in map(square,mynums):
print(x)
Output:
Exercise
def inspect(mystring):
if len(mystring)%2==0:
return "EVEN"
else:
return mystring[0]
months=["January","February","March"]
print(list(map(inspect,months)))
Output:
What Is filter( ) Function?
filter(function, sequence)
The first argument should be a function which must return a boolean value
If the function returned True for that item , filter( ) returns that item
as part of it’s return value otherwise the item is not returned.
What Is filter( ) Function?
def check_even(num):
return num%2==0
What Is filter( ) Function?
mynums=[1,2,3,4,5,6]
mynums=[1,2,3,4,5,6]
for x in mynums:
if check_even(x):
print(x)
Complete Code
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
for x in mynums:
if check_even(x):
print(x)
Output:
2
4
6
Using filter( ) Function
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(filter(check_even,mynums))
Output:
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(list(filter(check_even,mynums)))
Output:
Previous Code Using filter( )
In case we want to iterate over this list , then we can use for loop
as shown below:
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
for x in filter(check_even,mynums):
print(x)
Output:
Guess The Output
def f1(num):
return num*num
Ideally , the function passed
to filter( ) should return a
mynums=[1,2,3,4,5] boolean value. But if it
print(list(filter(f1,mynums))) doesn’t return boolean value
, then whatever value it
returns Python converts it to
boolean . In our case for
Output: each value in mynums the
[1,2,3,4,5] return value will be it’s
square which is a non-zero
value and thus assumed to
be True. So all the elements
are returned by filter()
Guess The Output
def f1(num):
return num%2
For every even number
mynums=[1,2,3,4,5] the return value of the
print(list(filter(f1,mynums))) function f1( ) will be 0
which is assumed to be
False and for every odd
Output: number the return value
will be 1 which is
[1,3,5] assumed to be True .
Thus filter( ) returns only
those numbers for which
f1( ) has returned 1.
Guess The Output
def f1(num):
print("Hello")
Hello is displayed 5 times
mynums=[1,2,3,4,5] because the filter( )
print(list(filter(f1,mynums))) function has called f1( )
Output: function 5 times. Now for
each value in mynums ,
Hello since f1( ) has not
Hello returned any value , by
Hello default it’s return value is
Hello assumed to be None
which is a representation
Hello of False. Thus filter( )
[] returned an empty list.
Guess The Output
def f1(num):
pass
def f1():
pass The function filter() is trying
to call f1( ) for every value in
the list mynums. But since
mynums=[1,2,3,4,5] f1( ) is a non-parametrized
print(list(filter(f1,mynums))) function , this call generates
TypeError
Output:
Guess The Output
def f1():
pass
mynums=[]
print(list(filter(f1,mynums)))
Output:
[]
Guess The Output
def f1(num):
return num%2
def f1(num):
pass Since f1( ) is not returning
anything , so it’s return
value by default is assumed
mynums=[1,2,3,4,5] to be None and because
print(list(map(f1,mynums))) map( ) has internally called
f1 () 5 times , so the list
returned contains None 5
times
Output:
[ None,None,None,None ,None ]
Guess The Output
def f1():
pass
mynums=[]
print(list(map(f1,mynums)))
Output:
[]
Using Lambda Expression
With map( ) And filter( )
mynums=[1,2,3,4,5]
sqrnum=list(map(lambda num: num*num,mynums))
print(sqrnum)
Exercise
months=["January","February","March"]
print(list(map(lambda mystring: mystring[0],months)))
Output:
Exercise
months=["January","February","March"]
print(list(map(lambda mystring: "EVEN" if len(mystring)%2==0 else
mystring[0],months)))
Output:
Using Lambdas With filter( )
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(list(filter(check_even,mynums)))
mynums=[1,2,3,4,5,6]
print(list(filter(lambda num:num%2==0 ,mynums)))
Exercise
Output:
PYTHON
LECTURE 24
Today’s Agenda
• List -I
• What Is A List ?
• Creating A List
• Accessing The List Elements
• Adding New Data In The List
• The Slice Operator With List
What Is A List ?
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
mynums=[10,20,30,40,50]
print(mynums)
Output:
[10,20,30,40,50]
Accessing Individual Elements
For example:
mynums=[10,20,30,40,50]
mynums=[10,20,30,40,50]
print(mynums[0])
print(mynums[1])
print(mynums[-3])
print(mynums[-2])
Output:
10
20
30
40
Accessing List Elements Using
While Loop
mynums=[10,20,30,40,50]
n=len(mynums) Just like len( )
i=0 works with strings
while i<n: , similarly it also
print(mynums[i]) works with list
also and returns
i=i+1 number of
elements in the
Output: list
10
20
30
40
50
Accessing List Elements Using
For Loop
mynums=[10,20,30,40,50]
for x in mynums: Since list is a
print(x) sequence type , so
for loop can
Output: iterate over
10 individual
elements of the
20 list
30
40
50
Exercise
mynums=[10,20,30,40,50]
n=len(mynums)
for i in range(n-1,-1,-1):
print(mynums[i])
Output:
50
40
30
20
10
Adding New Data In The List
This method takes one argument and adds it at the end of the list
mynums=[10,20,30,40,50]
print(mynums)
Remember , lists are
mynums.append(60)
mutable . So append( )
print(mynums) method doesn’t create a
Output: new list , rather it simply
adds a new element to the
[10,20,30,40,50] existing list.
[10,20,30,40,50,60] CAN YOU PROVE THIS ?
Solution
mynums=[10,20,30,40,50]
print(mynums)
print(id(mynums)) As we can see in the both
mynums.append(60) the cases the id( )
function is returning the
print(mynums) same address . This
print(id(mynums)) means that no new list
was created.
Output:
Exercise
Output:
Solution
mynums=[]
i=1
while i<=5:
x=int(input("Enter "+str(i)+" element:"))
mynums.append(x)
i=i+1
print("The list is:")
sum=0
for x in mynums:
print(x)
sum+=x
print("Sum is",sum)
Slice Operator With List
Syntax: list_var[x:y]
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1:4]) print(mynums[3:5])
• Output: • Output:
[20,30,40] [40,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[0:4]) print(mynums[0:10])
• Output: • Output:
[10,20,30,40] [10,20,3040,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[2:2]) print(mynums[6:10])
• Output: • Output:
[] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1: ]) print(mynums[:3])
• Output: • Output:
[20,30,40,50 ] [10,20,30 ]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[ :-2]) print(mynums[-2:])
• Output: • Output:
[10, 20,30 ] [40,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2:1]) print(mynums[-2:-2])
• Output: • Output:
[] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2:2]) print(mynums[-2:4])
• Output: • Output:
[] [40]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-4:2]) print(mynums[1:-2])
• Output: • Output:
[20 ] [20,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2: -1]) print(mynums[-1:-2])
• Output: • Output:
[40] []
Using Step Value
s[begin:end:step]
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1:4:2]) print(mynums[1:4:0])
• Output: • Output:
[20,40] ValueError: Slice
step cannot be
0
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[4:1:1]) print(mynums[4:1:-1])
• Output: • Output:
[] [50,40,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[::]) print(mynums[::-1])
• Output: • Output:
[10,20,30,40,50 ] [50,40,30,20,10]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[::-2]) print(mynums[::2])
• Output: • Output:
[50,30,10 ] [10,30,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1:-4:]) print(mynums[-1:-4:-1])
• Output: • Output:
[] [50,40,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-4:-1:]) print(mynums[-4:-1:-1])
• Output: • Output:
[20,30,40] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1: :-2]) print(mynums[-1::2])
• Output: • Output:
[50,30,10] [50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1:4 :2]) print(mynums[-3::-1])
• Output: • Output:
[] [30,20,10]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[:-3:-1]) print(mynums[-1:-1:-1])
• Output: • Output:
[50,40] []
PYTHON
LECTURE 25
Today’s Agenda
• List -II
• Modifying A List
• Deletion In A List
• Appending / Prepending Items In A List
• Multiplying A List
• Membership Operators On List
Modifying A List
sports=["cricket","hockey","football"]
print(sports)
sports[3]="badminton"
print(sports)
Output:
Modifying Multiple Values
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=["badminton","tennis","rugby","table
tennis"]
The number of elements
print(sports) inserted need not be equal to
the number replaced. Python
Output: just grows or shrinks the list
as needed.
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:2]=["badminton","tennis","rugby","table
tennis"]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:1]=["badminton","tennis"]
print(sports) If we have end index same or less
than start index , then Python
doesn’t remove anything . Rather it
simply inserts new elements at the
given index and shifts the existing
Output: element
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:0]=["badminton","tennis"]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:-1]=["badminton","tennis"]
print(sports)
Since -1 is present in the list ,
Python removed items from 1 to
second last item of the list and
inserted new items there
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:-2]=["badminton","tennis"]
print(sports)
Output:
Deleting Item From The List
Example:
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[3]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[4]
print(sports)
Subscript operator will generate
IndexError whenever we pass
invalid index
Output:
Deleting Multiple Items
OR
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=[]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:5]=[]
print(sports)
Slice operator never generates
IndexError , so the code will work
fine and remove all the items from
given start index to the end of the
list
Output:
Example
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[1:3]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[1:5]
print(sports)
Here also , since we have used the
slice operator , no exception will
Output: arise
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[0:4]
print(sports)
Output:
Deleting Entire List
Example:
outdoor=["cricket","hockey","football"]
indoor=["carrom","chess","table-tennis"]
allsports=outdoor+indoor
print(allsports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=["carrom","chess","table-tennis"]+sports
print(sports)
Output:
Guess The Output ?
evens=[4,6,8]
evens=2+evens
print(evens)
Output:
Guess The Output ?
evens=[4,6,8]
evens=list(2)+evens
print(evens)
Output:
Guess The Output ?
evens=[4,6,8]
evens=[2]+evens
print(evens)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+"boxing"
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+list("boxing")
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+["boxing"]
print(sports)
Output:
Multiplying A List
sports=["cricket","hockey","football"]
sports=sports*3.0
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports*["boxing"]
print(sports)
Output:
Membership Operator On List
Example:
sports=["cricket","hockey","football"]
print("cricket" in sports)
Output:
Exercise
myints=[]
print("Enter 5 unique integers:")
i=0
while i<=4:
item=int(input("Enter element:"))
if item in myints:
print("Item already present!")
continue
myints.append(item)
i=i+1
Output:
PYTHON
LECTURE 26
Today’s Agenda
• List -III
• Built In Functions For List
Built In Functions For List
These are:
len()
max()
min()
sum()
sorted()
list()
any()
all()
The len( ) Function
Output:
4
The max( ) Function
Example:
nums=[5,2,11,3]
print(max(nums))
Output:
11
Guess The Output ?
months=["january","may","december"]
print(max(months))
Output:
may
Guess The Output ?
booleans=[False,True]
print(max(booleans))
Output:
True
Guess The Output ?
mynums=[1.1,1.4,0.9]
print(max(mynums))
Output:
1.4
Guess The Output ?
mynums=[True,5,False]
print(max(mynums))
Output:
5
Guess The Output ?
mynums=[0.2,0.4,True,0.5]
print(max(mynums))
Output:
True
Guess The Output ?
mynums=["True",False]
print(max(mynums))
Output:
Guess The Output ?
values=[10,"hello",20,"bye"]
print(max(values))
Output:
Guess The Output ?
fruits=["apple","banana","orange"]
print(max(fruits))
Output:
orange
Guess The Output ?
fruits=["apple","banana","orange",None]
print(max(fruits))
Output:
The min( ) Function
Example:
nums=[5,2,11,3]
print(min(nums))
Output:
2
Guess The Output ?
months=["january","may","december"]
print(min(months))
Output:
december
The sum( ) Function
Example:
nums=[10,20,30]
print(sum(nums))
Output:
60
Guess The Output ?
nums=[10,20,30,True,False]
print(sum(nums))
Output:
61
Guess The Output ?
nums=['1','2','3']
print(sum(nums))
Output:
Guess The Output ?
nums=[2.5,3.5,4.5]
print(sum(nums))
Output:
10.5
The sorted( ) Function
Example:
nums=[7,4,9,1]
print(sorted(nums))
print(nums)
Output:
Guess The Output ?
months=["january","may","december"]
print(sorted(months))
Output:
[“december”,”january”,”may”]
Guess The Output ?
months=["january","may","december",3]
print(sorted(months))
Output:
Guess The Output ?
values=[2.4,1.0,2,3.6]
print(sorted(values))
Output:
[1.0,2,2.4,3.6]
Guess The Output ?
values=["bhopal","bhop","Bhopal"]
print(sorted(values))
Output:
[“Bhopal”,”bhop”,”bhopal”]
Sorting In Descending Order
Example:
nums=[3,1,5,2]
print(sorted(nums,reverse=True))
Output:
The list( ) Function
Example:
city="bhopal"
x=list(city)
print(x)
Output:
Guess The Output ?
n=20
x=list(n)
print(x)
Output:
Guess The Output ?
n="20"
x=list(n)
print(x)
Output:
Guess The Output ?
t=(10,20,30)
x=list(t)
print(x)
This is a
Output: tuple
The any( ) Function
Example:
x = [1, 3, 4, 0]
print(any(x))
Output:
Guess The Output ?
x = [0, False]
print(any(x))
Output:
Guess The Output ?
x = [0, False, 5]
print(any(x))
Output:
Guess The Output ?
x= []
print(any(x))
Output:
The all( ) Function
Syntax:
all(iterable)
Example:
x = [1, 3, 4, 0]
print(all(x))
Output:
Guess The Output ?
x = [0, False]
print(all(x))
Output:
Guess The Output ?
x = [1,3,4,5]
print(all(x))
Output:
Guess The Output ?
x = [0, False, 5]
print(all(x))
Output:
Guess The Output ?
x= []
print(all(x))
Output:
PYTHON
LECTURE 27
Today’s Agenda
• List -IV
• Methods Of List
List Methods
These are:
append()
extend()
insert()
index()
count()
remove()
pop()
clear()
sort()
reverse()
The append( ) Method
Syntax:
list_var.append(item)
Example:
primes=[2,3,5,7]
primes.append(11)
print(primes)
Output:
Guess The Output ?
Output:
Exercise
Output:
Solution
Syntax:
list_var.extend(iterable)
Output:
Example:
primes=[2,3,5,7]
primes.extend([11,13,17])
print(primes)
Guess The Output ?
primes=[2,3,5,7]
primes.extend(11)
print(primes)
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.extend([11])
print(primes)
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
colors=["red","green"]
colors.extend("blue")
print(colors)
Output:
Guess The Output ?
colors=["red","green"]
colors.extend(["blue"])
print(colors)
Output:
Guess The Output ?
a = [1, 2, 3]
b = [4, 5, 6].extend(a)
print(b)
Output:
The insert( ) Method
Syntax:
list_var.insert(index,item)
Example:
Output:
primes=[2,3,7,9]
primes.insert(2,5)
print(primes)
Guess The Output ?
primes=[2,3,7,9]
primes.insert(-2,5)
print(primes)
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.insert(5,9)
print(primes)
The method insert( ) works like
slicing operator . So even if the
index given is beyond range , it will
add the element at the end.
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.insert(-5,9)
print(primes)
Output:
Exercise
Output:
Solution
i=1
sortednums=[]
print("Enter any 5 random integers:")
while i<=5:
n=int(input())
pos=0
for x in sortednums:
if x>n:
break
pos=pos+1
sortednums.insert(pos,n)
i=i+1
print("Sorted list is:")
print(sortednums)
The index( ) Method
Syntax:
list_var.index(item)
Output:
Example:
primes=[2,3,5,7]
pos=primes.index(5)
print("position of 5 is",pos)
Guess The Output ?
Output:
Guess The Output ?
mynums = [10,20,30,40,50]
x = mynums.index(20)
print("20 occurs at",x,"position")
x = mynums.index(60)
print("60 occurs at",x,"position")
x = mynums.index(10)
print("10 occurs at",x,"position")
Output:
Guess The Output ?
Output:
The count( ) Method
Syntax:
list_var.count(item)
Output:
Example:
country=['i','n','d','i','a']
x=country.count('i')
print("i occurs",x,"times in",country)
Guess The Output ?
Output:
Guess The Output ?
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
print("9 occurs",x,"times")
Output:
Guess The Output ?
Output:
The remove( ) Method
Syntax:
list_var.remove(item)
Output:
Example:
vowels=['a','e','i','o','u']
vowels.remove('a')
print(vowels)
Guess The Output ?
subjects=["phy","chem","maths"]
subjects.remove("chem")
print(subjects)
Output:
Guess The Output ?
subjects=["phy","chem","maths","chem"]
subjects.remove("chem")
print(subjects)
subjects.remove("chem")
print(subjects)
subjects.remove("chem")
print(subjects)
Output:
The pop( ) Method
The pop() method removes and returns the element at the given
index (passed as an argument) from the list.
Syntax:
list_var.pop(index)
If the index passed to the pop() method is not in the range, it throws IndexError:
pop index out of range exception.
The pop() method returns the element present at the given index.
Also, the pop() method updates the list after removing the element
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
del v/s pop( ) v/s remove( )
Syntax:
list_var.clear( )
Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits)
fruits.clear() Output:
print(fruits)
The sort( ) Method
Syntax:
list_var.sort(reverse=True|False, key=name of func)
Parameter Values:
Parameter Name Description
reverse Optional. reverse=True will sort
the list descending. Default is
reverse=False
key Optional. A function to specify the
sorting criteria(s)
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
mylist = ["a",10,True]
mylist.sort()
print(mylist)
Output:
Guess The Output ?
mylist = [25,10,True,False]
mylist.sort()
print(mylist)
Output:
Passing Our
Own Function As Key
def sortSecond(val):
return val[1]
list1 = [(1,2),(3,3),(1,1)]
list1.sort(key=sortSecond)
print(list1)
Output:
Guess The Output ?
def sortSecond(val):
return 0
list1 = [(1,2),(3,3),(1,1)]
list1.sort(key=sortSecond)
print(list1)
Output:
Guess The Output ?
Output:
Guess The Output ?
def myFunc(val):
return val[2]
Output:
The reverse( ) Method
Syntax:
list_var.reverse( )
Example:
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os)
Output:
os.reverse()
print('Updated List:', os)
PYTHON
LECTURE 28
Today’s Agenda
• List -V
• List Comprehension
What Is Comprehension ?
text="Bhopal"
myList=[]
for x in text:
myList.append(x)
print(myList)
Output:
Using Lambda
Output:
Understanding
List Comprehension
Output:
Syntax For
List Comprehension
Syntax:
Explanation
Output:
Using for Loop
squaresList=[]
for i in range(1,6):
squaresList.append(i**2)
print(squaresList)
Using List Comprehension
Output:
Using for Loop
text=input("Type a string:")
uppersList=[]
for x in text.split():
uppersList.append(x.upper())
print(uppersList)
Using List Comprehension
text=input("Type a string:")
uppersList=[x.upper()for x in text.split()]
print(uppersList)
Exercise
Output:
Using for Loop
myNums=[]
text=input("Enter 5 integers:")
for x in text.split():
myNums.append(int(x))
print("List is:",myNums)
print("Sum is:",sum(myNums))
Using List Comprehension
text=input("Enter 5 integers:")
myNums=[int(x) for x in text.split()]
print("List is:",myNums)
print("Sum is:",sum(myNums))
Adding Conditions In
List Comprehension
Syntax:
Solution
squaresList=[x**2 for x in range(1,6) if x%2!=0]
print(squaresList)
Output:
Exercise
Output:
Using for Loop
def removevowels(text):
myList=[]
for x in text:
if x not in "aeiou":
myList.append(x)
return myList
text=input("Type a string:")
finalList=removevowels(text)
print(finalList)
Using List Comprehension
def removevowels(text):
myList=[x for x in text if x not in "aeiou"]
return myList
text=input("Type a string:")
finalList=removevowels(text)
print(finalList)
Exercise
Output:
Solution
def get_numbers(myList):
mynumberList=[x for x in myList if type(x) is int]
return mynumberList
myList=["bhopal",25,"$","hello",34,21,"indore",22]
print("Actual List")
print(myList)
print("List with numbers only")
mynumberList=get_numbers(myList)
print(mynumberList)
Exercise
Output:
Solution
def getlength(str):
myList=[len(x) for x in str.split() if x!="the"]
return myList
text=input("Type a string:")
myList=getlength(text)
print(myList)
Adding Multiple Conditions
In List Comprehension
Syntax:
Solution
myList=[x**2 for x in range(1,21) if x%2==0 if x%3==0]
print(myList)
Output:
Previous Code Using for Loop
myNums=[]
for x in range(1,21):
if x%2==0:
if x%3==0:
myNums.append(x**2)
print(myNums)
Exercise
Output:
Solution
text=input("Type a string:")
myList=get_upper(text)
print(myList)
What About
Logical Operators ?
Example:
a = [1,2,3,4,5,6,7,8,9,10]
b = [x for x in a if x % 2 == 0 or x % 3 == 0]
print(b)
Output:
Exercise
Output:
Solution
def remove_min_max(myList):
myNewList=[x for x in myList if x!=min(myList) and x!=max(myList)]
return myNewList
a=[10,3,15,12,24,6,1,18]
print("Original list")
print(a)
print("After removing min and max element")
print(remove_min_max(a))
If – else
In List Comprehension
Syntax:
Output:
Nested
List Comprehension
a=[20,40,60]
b=[2,4,6] Explanation:
Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Nested
List Comprehension
a=[20,40,60]
b=[2,4,6]
c=[x * y for x in a for y in b]
print(c)
Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Exercise
Output:
Solution
def flatten(mylist):
newlist=[y for x in mylist for y in x]
return newlist
mylist = [[1,2,3],[4,5,6],[7,8]]
print("Before calling flatten list is")
print(mylist)
newlist=flatten(mylist)
print("After calling flatten list is")
print(newlist)
PYTHON
LECTURE 29
Today’s Agenda
• Tuple-I
• What Is A Tuple ?
• Differences With List
• Benefits Of Tuple
• Creating Tuple
• Packing / Unpacking A Tuple
• Accessing A Tuple
What Is A Tuple ?
# empty tuple
my_tuple = ()
my_tuple = (2,)
print(my_tuple)
print(type(my_tuple))
Output:
Guess The Output ?
my_tuple = ()
print(my_tuple)
print(type(my_tuple))
Output:
Packing And Unpacking
A Tuple
Packing:
Packing is a simple syntax which lets us create tuples "on the fly"
without using the normal notation:
a = 1, 2, 3
This creates a tuple of 3 values and assigned it to a. Comparing this to
the "normal" way:
a = (1, 2, 3)
Packing And Unpacking
A Tuple
Unpacking:
We can also go the other way, and unpack the values from a tuple
into separate variables:
a = 1, 2, 3
x, y, z = a
Next, the tuple is assigned to the left hand side of the = sign:
Output:
Guess The Output ?
def add(a,b,c,d):
print("Sum is",a+b+c+d)
mytuple=(10,20,30,40)
add(*mytuple)
Output:
Accessing The Tuple
values=(10,20,30,40)
print(values)
Output:
Accessing
Individual Elements
For example:
mynums=(10,20,30,40,50)
mynums=(10,20,30,40,50)
print(mynums[0]) Even though we
print(mynums[1]) create tuple using
the symbol of ( ) but
print(mynums[-3]) when we access it’s
individual element ,
print(mynums[-2]) we still use the
subscript or index
operator [ ]
Output:
Accessing Tuple Elements
Using
While Loop
mynums=(10,20,30,40,50)
n=len(mynums) Just like len( )
works with list,
i=0 similarly it also
while i<n: works with tuple
and returns
print(mynums[i]) number of
i=i+1 elements in the
tuple
Output:
Accessing Tuple Elements
Using
For Loop
mynums=(10,20,30,40,50)
for x in mynums: Since tuple is a
print(x) sequence type , so
for loop can
iterate over
Output: individual
elements of the
tuple
Exercise
title,singer,year,songs=album
print("Title:",title)
print("Year:",year)
print("Singer:",singer)
for info in songs:
print("\tSong Number:{0},Song
Name:{1}".format(info[0],info[1]))
Slice Operator With Tuple
Just like we can apply slice operator with lists and strings
, similarly Python allows us to apply slice operator with
tuple also.
Syntax: tuple_var[x:y]
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1:4]) print(mynums[3:5])
• Output: • Output:
(20,30,40) (40,50)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[0:4]) print(mynums[0:10])
• Output: • Output:
(10,20,30,40) (10,20,3040,50)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[2:2]) print(mynums[6:10])
• Output: • Output:
() ()
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1: ]) print(mynums[:3])
• Output: • Output:
(20,30,40,50 ) (10,20,30)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
Mynums=(10,20,30,40,50)
40,50)
print(mynums[ :-2]) print(mynums[-2:])
• Output: • Output:
(10, 20,30 ) (40,50)
Using Step Value
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1:4:2]) print(mynums[1:4:0])
• Output: • Output:
(20,40) ValueError: Slice
step cannot be
0
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[4:1:1]) print(mynums[4:1:-1])
• Output: • Output:
() (50,40,30)
The Slicing Operator
• Example: • Example:
Mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[::]) print(mynums[::-1])
• Output: • Output:
(10,20,30,40,50 ) (50,40,30,20,10)
PYTHON
LECTURE 30
Today’s Agenda
• Tuple-II
• Changing The Tuple
• Deleting The Tuple
• Functions Used With Tuple
Changing A Tuple
mynums=(10,20,30,40,50)
mynums[0]=15
Output:
Guess The Output ?
mynums=([10,20],30,40,50)
print(mynums) Why did the code run?
mynums[0][0]=15 Although a tuple is immutable,
print(mynums) but if it contains a mutable
data then we can change
it’s value
Output:
Guess The Output ?
myvalues=("hello",30,40,50)
print(myvalues)
myvalues[0]="hi"
print(myvalues)
Output:
Guess The Output ?
myvalues=(["hello",20],30,40,50)
print(myvalues)
myvalues[0][0]="hi"
print(myvalues)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums) Why did the code run?
mynums=(15,25,35,45,55) Tuple object is immutable ,
print(mynums) but tuple reference is mutable.
So we can assign a new
tuple object to the same reference
Output:
Deleting A Tuple
mynums=(10,20,30,40,50)
print(mynums)
del mynums[0]
print(mynums)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums)
del mynums[2:4]
print(mynums)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums)
del mynums
print(mynums)
Output:
Built In Functions For Tuple
But only those functions work with tuple which do not modify it
Can you figure out which of these functions will work with
tuple ?
Answer:
len()
All of them will work with tuple.
max()
min() Will sorted( ) also work ?
sum()
sorted() Yes, even sorted( ) function
tuple() will also work since it does not
any() change the original tuple ,
all() rather it returns a sorted copy
of it
The len( ) Function
Output:
4
The max( ) Function
Example:
nums=(5,2,11,3)
print(max(nums))
Output:
11
Guess The Output ?
months=("january","may","december“)
print(max(months))
Output:
may
Guess The Output ?
booleans=(False,True)
print(max(booleans))
Output:
True
Guess The Output ?
Mynums=(True,5,False)
print(max(mynums))
Output:
5
Guess The Output ?
mynums=("True",False)
print(max(mynums))
Output:
Guess The Output ?
values=(10,"hello",20,"bye")
print(max(values))
Output:
Guess The Output ?
fruits=("apple","banana","orange")
print(max(fruits))
Output:
orange
Guess The Output ?
fruits=("apple","banana","orange",None)
print(max(fruits))
Output:
The min( ) Function
Example:
nums=(5,2,11,3)
print(min(nums))
Output:
2
Guess The Output ?
months=("january","may","december")
print(min(months))
Output:
december
The sum( ) Function
Example:
nums=(10,20,30)
print(sum(nums))
Output:
60
Guess The Output ?
nums=(10,20,30,True,False)
print(sum(nums))
Output:
61
Guess The Output ?
nums=('1','2','3')
print(sum(nums))
Output:
Guess The Output ?
nums=(2.5,3.5,4.5)
print(sum(nums))
Output:
10.5
The sorted( ) Function
Output:
Guess The Output ?
months=("january","may","december")
print(sorted(months))
Output:
[“december”,”january”,”may”]
Guess The Output ?
months=("january","may","december",3)
print(sorted(months))
Output:
Guess The Output ?
values=(2.4,1.0,2,3.6)
print(sorted(values))
Output:
[1.0,2,2.4,3.6]
Guess The Output ?
values=("bhopal","bhop","Bhopal")
print(sorted(values))
Output:
[“Bhopal”,”bhop”,”bhopal”]
Sorting In Descending Order
Example:
nums=(7,4,9,1)
print(sorted(nums,reverse=True))
print(nums)
Output:
The tuple( ) Function
Example:
city="bhopal"
x=tuple(city)
print(x)
Output:
Guess The Output ?
n=20
x=tuple(n)
print(x)
Output:
Guess The Output ?
n="20"
x=tuple(n)
print(x)
Output:
Guess The Output ?
l=[10,20,30]
x=tuple(l)
print(x)
Output:
The any( ) Function
Example:
x = (1, 3, 4, 0)
print(any(x))
Output:
Guess The Output ?
x = (0, False)
print(any(x))
Output:
Guess The Output ?
x = (0, False, 5)
print(any(x))
Output:
Guess The Output ?
x= ()
print(any(x))
Output:
Guess The Output ?
x= ("","0", "")
print(any(x))
Output:
Guess The Output ?
x= ("",0, "")
print(any(x))
Output:
Guess The Output ?
x= (4)
print(any(x))
Output:
Guess The Output ?
x= (4,)
print(any(x))
Output:
The all( ) Function
Syntax:
all(iterable)
Example:
x = (1, 3, 4, 0)
print(all(x))
Output:
Guess The Output ?
x = (0, False)
print(all(x))
Output:
Guess The Output ?
x = (1,3,4,5)
print(all(x))
Output:
Guess The Output ?
x = (0, False, 5)
print(all(x))
Output:
Guess The Output ?
x= ()
print(all(x))
Output:
PYTHON
LECTURE 31
Today’s Agenda
• Tuple-III
• Methods Used With Tuple
Syntax:
tuple_var.index(item)
Output:
Example:
primes=(2,3,5,7)
pos=primes.index(5)
print("position of 5 is",pos)
Guess The Output ?
mynums = (10,20,30,40,50)
p = mynums.index(20)
print("20 occurs at",p,"position")
p = mynums.index(60)
print("60 occurs at",p,"position")
p = mynums.index(10)
print("10 occurs at",p,"position")
Output:
The count( ) Method
Syntax:
tuple_var.count(item)
Output:
Example:
country=('i','n','d','i','a')
x=country.count('i')
print("i occurs",x,"times in",country)
Guess The Output ?
Output:
Operations Allowed On Tuple
These are:
Membership Operators
Concatenation Operator
Multiplication
Relational Operators
Membership Operators
my_tuple = ('a','p','p','l','e',)
print('a' in my_tuple)
print('b' in my_tuple)
print('g' not in my_tuple)
Output:
Concatenation On Tuple
odds=(1,3,5)
evens=(2,4,6)
all=odds+evens
print(all)
Output:
Guess The Output ?
ages=(10,20,30)
names=("amit","deepak","ravi")
students=ages+names
print(students)
Output:
Multiplication On Tuple
a=(10,20,30)
b=a*3
print(b)
Output:
Guess The Output ?
a=(10,20,30)
b=a*3.0
print(b)
Output:
Relational Operators
On Tuples
a=(1,2,3)
b=(1,3,4)
print(a<b)
Output:
True
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output ?
a=(1,3,2)
b=(1,2,3)
print(a<b)
Output:
False
Guess The Output ?
a=(1,3,2)
b=(1,3,2)
print(a<b)
Output:
False
Guess The Output ?
a=(1,2,3)
b=(1,2,3,4)
print(a<b)
Output:
True
Guess The Output ?
a=(5,2,7)
b=(1,12,14)
print(a>b)
Output:
True
Guess The Output ?
a=()
b=(0)
print(a<b)
Output:
TypeError : < not supported between instances of
‘tuple’ and ‘int’
Guess The Output ?
a=()
b=(0,)
print(a<b)
Output:
True
Guess The Output ?
a=(1,2)
b=("one","two")
print(a<b)
Output:
Guess The Output ?
a=(1,"one")
b=(1,"two")
print(a<b)
Output:
True
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 32
Today’s Agenda
• Strings -I
• What Is A String ?
• Creating A String
• Different Ways Of Accessing Strings
• Operators Which Work On Strings
What Is A String ?
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Output:
How Can Strings
Be Accessed ?
city="Bhopal"
print(city)
Output:
Bhopal
Accessing Individual
Elements
For example:
city=“Bhopal”
city="Bhopal"
print(city[0])
print(city[1])
print(city[-1])
print(city[-2])
Output:
B
h
l
a
Guess The Output ?
city="Bhopal"
print(city[6])
Output:
IndexError: String index out of range
Guess The Output ?
city="Bhopal"
print(city[1.5])
Output:
TypeError: String indices must be integers
Accessing String Elements Using
while Loop
city="Bhopal"
i=0
Just like len( )
while i<len(city): works with lists
print(city[i]) and tuple
i=i+1 similarly it also
works with string
returns number of
Output: elements in the
B string
h
o
p
a
l
Accessing String Elements Using
for Loop
city="Bhopal"
for ch in city: Since string is a
print(ch) sequence type , so
for loop can
Output: iterate over
individual
B
elements of the
h string
o
p
a
l
Exercise
city="Bhopal"
for i in range(len(city)-1,-1,-1):
print(city[i])
Output:
l
a
p
o
h
B
Slice Operator With String
Just like we can apply slice operator with lists and tuples,
similarly Python allows us to apply slice operator with
strings also.
Syntax: string_var[x:y]
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[3:5])
print(city[1:4])
• Output: • Output:
pa
hop
The Slicing Operator
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[0:10])
print(city[0:4])
• Output: • Output:
Bhopal
Bhop
The Slicing Operator
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[:4])
print(city[1:])
• Output: • Output:
Bhop
hopal
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
The Slicing Operator
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[-2:])
print(city[:-2])
• Output: • Output:
al
Bhop
Using Step Value
s[begin:end:step]
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[1:4:0])
print(city[1:4:2])
• Output: • Output:
ValueError: Slice
hp
step cannot be
0
The Slicing Operator
• Example: • Example:
city="Bhopal" city="Bhopal"
print(city[4:1:-1])
print(city[4:1:1])
• Output: • Output:
apo
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[::-1])
print(city[::])
• Output:
• Output: lapohB
Bhopal
The Operators
With Strings
Example:
a="Good"
b="Morning"
c="User"
print(a+b+c)
Output:
GoodMorningUser
The Operator *
Example:
a="Bye"
print(a*2)
print(2*a)
Output:
ByeBye
ByeBye
Guess The Output ?
a="Bye"
print(a*0) The * operator
print(a*-2) allows it’s
operand to be
negative or 0 in
which case it
Output: returns an empty
string
Guess The Output ?
x="Ba"+"na"*2
print(x)
Output:
Banana
The Operator in
Example:
a="banana"
print(“nana” in a)
print(“nani” in a)
Output:
True
False
The Operator not in
Example:
a="banana"
print(“nana” not in a)
print(“nani” not in a)
Output:
False
True
The Relational Operators
False
"tim" == "tie" True
"free" != "freedom" True
"arrow" > "aron" True
"right" >= "left“ False
"teeth" < "tee" False
True
"yellow" <= "fellow"
"abc" > " "
The Identity Operators
Example: Output:
a = 'London'
b = 'London' True
c = 'Paris' False
print(a is b) False
print(a is c) False
print(b is c) True
print(b is not a)
print(b is not c)
PYTHON
LECTURE 33
Today’s Agenda
• Strings -II
• Built In String Functions
• Printing string using f-string
• Modifying Strings
Built In String Functions
These are:
len()
max()
min()
chr()
ord()
The len( ) Function
Example:
name="Sachin"
print(len(name))
Output:
6
The max( ) Function
Example:
name="bhopal"
print(max(name))
Output:
p
Guess The Output ?
str="abc123#$.y@*"
print(max(str))
Output:
y
Guess The Output ?
str="False,True"
print(max(str))
Output:
u
Guess The Output ?
str="1.1,0.4,1.9"
print(max(str))
Output:
9
The min( ) Function
Example:
name="bhopal"
print(min(name))
Output:
a
Guess The Output ?
str=“Bhopal"
print(min(str))
Output:
B
Guess The Output ?
str="abc123#$.y@*"
print(min(str))
Output:
#
Guess The Output ?
str="1.1,0.4,1.9"
print(min(str))
Output:
,
The chr( ) Function
Example:
print(chr(122))
Output:
z
Guess The Output ?
print(chr(43))
Output:
+
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output ?
print(chr(1))
Output:
Guess The Output ?
print(chr(0))
Output:
Guess The Output ?
print(chr(-1))
Output:
ValueError: chr() argument not in range
The ord( ) Function
Example:
print(ord(‘a’))
Output:
97
Guess The Output ?
print(ord("+"))
Output:
43
Guess The Output ?
print(ord("5"))
Output:
53
The str( ) Function
Example:
print(str(49.2))
Output:
49.2
Guess The Output ?
print(str(True))
Output:
True
Guess The Output ?
print(str(25))
Output:
25
String Interpolation
To understand this feature , can you tell how can we print the
following 2 variables using print( ):
name=“Sachin”
age=34
name="Sachin"
age=34
print(f"My name is {name} and my age is {age}")
Arbitary Expressions
a=10
b=20
print(f"sum is {a+b}")
Output:
Function Calls
import math
a=10
b=20
print(f"max of {a} and {b} is {max(a,b)}")
print(f"Factorial of {a} is {math.factorial(10)}")
Output:
Method Calls
vowels=["a","e","i","o","u","a"]
ch="a"
print(f"{ch} is occuring in {vowels}
{vowels.count(ch)} times")
Output:
PYTHON
LECTURE 34
Today’s Agenda
• Strings -III
• String Methods
String Methods
capitalize( )
Returns a copy of the string with first character
capitalized and rest of the characters in lower case.
Example:
name="guido van rossum"
newname=name.capitalize()
print(f"Original name is {name}\nCapitalized name is {newname}")
Output:
String Conversion Methods
Output:
String Conversion Methods
swapcase()
Returns a copy of the string with the case of every
character swapped . Means that lowercase characters
are changed to uppercase and vice-versa.
Example:
name="Sachin Kapoor"
newname=name.swapcase()
print(f"Original name is {name}")
print(f"Swapped name is {newname}")
Output:
String Conversion Methods
title()
Returns a copy of the string converted to proper case or
title case. i.e. , all words begin with uppercase letter and
the rest are in lowercase.
Example:
text="we got independence in 1947"
newtext=text.title() print(f"Original
text is {text}") print(f"Title text is
{newtext}")
Output:
String Conversion Methods
Output:
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
String Conversion Methods
text = "physics,chemistry,maths"
print(text.title())
Output:
String Conversion Methods
text = "physics_chemistry_maths"
print(text.title())
Output:
String Conversion Methods
text = "physics1chemistry2maths"
print(text.title())
Output:
String Conversion Methods
Output:
String Comparison Methods
Example:
s = 'this is good'
print(s.islower())
Example:
s = "THIS IS GOOD!"
print(s.isupper())
Example:
s = ""
print(s.isupper())
print(s.islower())
Output:
String Comparison Methods
istitle( )
Example: Output:
s = 'Python Is Good.' True
print(s.istitle()) False
True
s = 'Python is good'
True
print(s.istitle())
False
s = 'This Is @ Symbol.'
print(s.istitle())
s = '99 Is A Number'
print(s.istitle())
s = 'PYTHON'
print(s.istitle())
String Comparison Methods
isalpha( )
Example: Output:
name = "Monalisa" True
print(name.isalpha()) False
False
name = "M0nalisa"
print(name.isalpha())
isdigit( )
Example: Output:
text = "12345" True
print(text.isdigit()) True
False
text = "012345" False
print(text.isdigit())
text = "a12345"
print(text.isdigit())
String Comparison Methods
isalnum( )
Example: Output:
name = "M234onalisa" True
print(name.isalnum()) False
True
name = "M3ona Shah " True
print(name.isalnum())
name = "Mo3nalisaSha22ah"
print(name.isalnum())
name = "133"
print(name.isalnum())
String Comparison Methods
isspace( )
Example: Output:
s = ' \t' True
print(s.isspace()) False
True
s='a' False
print(s.isspace())
s=''
print(s.isspace())
s = ''
print(s.isspace())
String Comparison Methods
startswith( )
Example: Output:
text = "Python is easy to learn." False
True
result = text.startswith('is easy')
True
print(result)
True
result = text.startswith('Python is ')
print(result)
endswith( )
Example:
text = "Python is easy to learn." Output:
False
result = text.endswith('to learn')
print(result) True
True
result = text.endswith('to learn.') False
print(result)
False
result = text.endswith('learn.', 7) True
print(result)
index( )
Returns the index of first occurrence of a substring
inside the string (if found).
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.index('is a fun') 16
print(result) ValueError
result = text.index('day')
print(result)
result = text.index('day',7)
print(result)
result = text.index('night')
print(result)
String Searching Methods
find( )
Returns the first index of a substring inside the string (if
found).
If the substring is not found, it returns -1
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.find('is a fun') 16
print(result) -1
result = text.find('day')
print(result)
result = text.find('day',7)
print(result)
result = text.find('night')
print(result)
String Searching Methods
count( )
Returns the number of occurrences of a substring in the
given string
Example: Output:
text = "Python is awesome, isn't it?" 2
1
substring = "is"
0
count = text.count(substring)
print(count)
substring = "i"
count = text.count(substring, 8, 25)
print(count)
substring="ton"
count = text.count(substring)
print(count)
String Replacement Methods
replace( )
Returns a copy of the string where all occurrences of a substring is
replaced with another substring.
The replace() method returns a copy of the string where old substring is
replaced with the new substring. The original string is unchanged.
If the old substring is not found, it returns the copy of the original string.
String Replacement Methods
Example: Output:
text = "Blue Blue Blue" Black Black Black
newtext= text.replace("ue","ack") Black Black Blue
Blue Blue Blue
print(newtext)
newtext= text.replace("ue","ack",2)
print(newtext)
newtext= text.replace("eu","ack")
print(newtext)
String Replacement Methods
strip( )
Returns a copy of the string with both leading and trailing
characters removed (based on the string argument passed).
Example: Output:
text = " Good Morning " Original text:[ Good Morning ]
newtext= text.strip() New text:[Good Morning]
print("Original text:["+text+"]")
print("New text:["+newtext+"]")
Exercise
def get_full_name():
pass
def get_password():
pass
def get_first_name(fullname):
pass
fullname=get_full_name()
pwd=get_password()
firstname=get_first_name(fullname)
print("Hello",firstname,"\nThank you for joining us!")
String Replacement Methods
split( )
The split() method breaks up a string at the specified
separator and returns a list of strings.
The split() breaks the string at the separator and returns a list of
strings.
String Replacement Methods
Example: Output:
text= 'Live and let live' [‘Live’,’and’,’let’,’live’]
[‘Milk’,’ Butter’,’ Bread’]
print(text.split())
[‘Milk, Butter, Bread’]
grocery = 'Milk, Butter, Bread'
print(grocery.split(', '))
print(grocery.split(':'))
Exercise
join( )
The join() method returns a string concatenated with the
elements of an iterable.
Syntax: <str>.join(<iterable>)
String Replacement Methods
Example:
mylist = ["C","C++","Java","Python"]
s = "->"
print(s.join(mylist))
Output:
C→C++→Java→Python
String Replacement Methods
Example:
letters = 'PYTHON'
letters_spaced = ' '.join(letters)
print(letters_spaced)
Output:
PY TH ON
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 35
Today’s Agenda
• Dictionary-I
• What Is A Dictionary ?
• What Is Key-Value Pair ?
• Creating A Dictionary
• Important Characteristics Of A Dictionary
• Different Ways To Access A Dictionary
• An Important Point
What Is A Dictionary ?
Syntax:
d={
<key>: <value>,
<key>: <value>,
...
<key>: <value>
}
How To Create A Dictionary?
# empty dictionary
my_dict = { }
• Strings -III
• String Methods
String Methods
capitalize( )
Returns a copy of the string with first character
capitalized and rest of the characters in lower case.
Example:
name="guido van rossum"
newname=name.capitalize()
print(f"Original name is {name}\nCapitalized name is {newname}")
Output:
String Conversion Methods
Output:
String Conversion Methods
Output:
String Conversion Methods
swapcase()
Returns a copy of the string with the case of every
character swapped . Means that lowercase characters
are changed to uppercase and vice-versa.
Example:
name="Sachin Kapoor"
newname=name.swapcase()
print(f"Original name is {name}")
print(f"Swapped name is {newname}")
Output:
String Conversion Methods
title()
Returns a copy of the string converted to proper case or
title case. i.e. , all words begin with uppercase letter and
the rest are in lowercase.
Example:
text="we got independence in 1947"
newtext=text.title() print(f"Original
text is {text}") print(f"Title text is
{newtext}")
Output:
String Conversion Methods
Output:
String Conversion Methods
text = "physics,chemistry,maths"
print(text.title())
Output:
String Conversion Methods
text = "physics_chemistry_maths"
print(text.title())
Output:
String Conversion Methods
text = "physics1chemistry2maths"
print(text.title())
Output:
String Conversion Methods
Output:
String Comparison Methods
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
String Comparison Methods
Example:
s = 'this is good'
print(s.islower())
Example:
s = "THIS IS GOOD!"
print(s.isupper())
Example:
s = ""
print(s.isupper())
print(s.islower())
Output:
String Comparison Methods
istitle( )
Example: Output:
s = 'Python Is Good.' True
print(s.istitle()) False
True
s = 'Python is good'
True
print(s.istitle())
False
s = 'This Is @ Symbol.'
print(s.istitle())
s = '99 Is A Number'
print(s.istitle())
s = 'PYTHON'
print(s.istitle())
String Comparison Methods
isalpha( )
Example: Output:
name = "Monalisa" True
print(name.isalpha()) False
False
name = "M0nalisa"
print(name.isalpha())
isdigit( )
Example: Output:
text = "12345" True
print(text.isdigit()) True
False
text = "012345" False
print(text.isdigit())
text = “a12345"
print(text.isdigit())
String Comparison Methods
isdecimal( )
Example: Output:
text = "12345" True
print(text.isdecimal()) True
False
text = "012345" False
print(text.isdecimal())
text = “a12345"
print(text.isdecimal())
String Comparison Methods
isnumeric( )
Example: Output:
text = "12345" True
print(text.isnumeric()) True
False
text = "012345" False
print(text.isnumeric())
text = “a12345"
print(text.isnumeric())
isdigit( ) V/s isdecimal( ) V/s
isnumeric( )
In Python:
Example: Output:
s = '\u00B23455'
print(s)
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
s = '\u00BD'
print(s)
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
String Comparison Methods
isalnum( )
Example: Output:
name = "M234onalisa" True
print(name.isalnum()) False
True
name = "M3ona Shah " True
print(name.isalnum())
name = "Mo3nalisaSha22ah"
print(name.isalnum())
name = "133"
print(name.isalnum())
String Comparison Methods
isspace( )
Example: Output:
s = ' \t' True
print(s.isspace()) False
True
s='a' False
print(s.isspace())
s=''
print(s.isspace())
s = ''
print(s.isspace())
String Comparison Methods
startswith( )
Example: Output:
text = "Python is easy to learn." False
True
result = text.startswith('is easy')
True
print(result)
True
result = text.startswith('Python is ')
print(result)
endswith( )
Example:
text = "Python is easy to learn." Output:
False
result = text.endswith('to learn')
print(result) True
True
result = text.endswith('to learn.') False
print(result)
False
result = text.endswith('learn.', 7) True
print(result)
index( )
Returns the index of first occurrence of a substring
inside the string (if found).
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.index('is a fun') 16
print(result) ValueError
result = text.index('day')
print(result)
result = text.index('day',7)
print(result)
result = text.index('night')
print(result)
String Searching Methods
find( )
Returns the first index of a substring inside the string (if
found).
If the substring is not found, it returns -1
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.find('is a fun') 16
print(result) -1
result = text.find('day')
print(result)
result = text.find('day',7)
print(result)
result = text.find('night')
print(result)
String Searching Methods
rfind( )
Returns the highest index of a substring inside the string
(if found).
Example: Output:
text= 'Sunday is a fun day' 7
16
result = text.rfind('is a fun') 16
print(result) -1
result = text.rfind('day')
print(result)
result = text.rfind('day',0)
print(result)
result = text.rfind('night')
print(result)
String Searching Methods
count( )
Returns the number of occurrences of a substring in the
given string
Example: Output:
text = "Python is awesome, isn't it?" 2
1
substring = "is"
0
count = text.count(substring)
print(count)
substring = "i"
count = text.count(substring, 8, 25)
print(count)
substring="ton"
count = text.count(substring)
print(count)
String Replacement Methods
replace( )
Returns a copy of the string where all occurrences of a substring is
replaced with another substring.
The replace() method returns a copy of the string where old substring is
replaced with the new substring. The original string is unchanged.
If the old substring is not found, it returns the copy of the original string.
String Replacement Methods
Example: Output:
text = "Blue Blue Blue" Black Black Black
newtext= text.replace("ue","ack") Black Black Blue
Blue Blue Blue
print(newtext)
newtext= text.replace("ue","ack",2)
print(newtext)
newtext= text.replace("eu","ack")
print(newtext)
String Replacement Methods
strip( )
Returns a copy of the string with both leading and trailing
characters removed (based on the string argument passed).
Example: Output:
text = " Good Morning " Original text:[ Good Morning ]
newtext= text.strip() New text:[Good Morning]
print("Original text:["+text+"]")
print("New text:["+newtext+"]")
Exercise
def get_full_name():
while True:
nam e=input("Type your full name:").strip()
if nam e.find(" ")!=-1:
return name
print("Please enter y our full name!")
def get_password():
while True:
pwd=input("Type y our password:")
cap_letter_present=False
digit_present=False
for x in pwd:
if x .isdigit():
digit_present=True
elif x .isupper():
cap_letter_present=True
if digit_present==False or cap_letter_present==False or len(pwd)<8:
print("Password must be of 8 or m ore characters in length\nwith atleast 1 digit and 1 capital
letter")
else:
return pwd
def get_first_name(fullname):
spacepos=fullname.find(" ")
return fullname[0:spacepos]
fullname=get_full_name()
pwd=get_password()
firstname=get_first_name(fullname)
print("Hello",firstname,"\nThank you for joining us!")
String Replacement Methods
split( )
The split() method breaks up a string at the specified
separator and returns a list of strings.
The split() breaks the string at the separator and returns a list of
strings.
String Replacement Methods
Example: Output:
text= 'Live and let live' [‘Live’,’and’,’let’,’live’]
[‘Milk’,’ Butter’,’ Bread’]
print(text.split())
[‘Milk,Butter,Bread’]
grocery = 'Milk, Butter, Bread'
print(grocery.split(', '))
print(grocery.split(':'))
String Replacement Methods
join( )
The join() method returns a string concatenated with the
elements of an iterable.
Syntax: <str>.join(<iterable>)
String Replacement Methods
Example:
mylist = ["C","C++","Java","Python"]
s = "->"
print(s.join(mylist))
Output:
C→C++→Java→Python
String Replacement Methods
Example:
letters = 'PYTHON'
letters_spaced = ' '.join(letters)
print(letters_spaced)
Output:
PY TH ON
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 36
Today’s Agenda
• Dictionary-II
• Updating Elements In Dictionary
• Removing Elements From Dictionary
• Functions Used In Dictionary
Updating A Dictionary
These are:
assignment operator or
Output:
Guess The Output ?
Output:
Updating Using
update( ) Method
dict_var.update( dict_var2)
accounts={101:50000,102:45000,103:55000}
print("Current Accounts Present")
print(accounts)
id=int(input("Enter account id:"))
amt=int(input("Enter amount:"))
balance=accounts.get(id)
if balance == None:
accounts[id]=amt
print("New Account Created")
else:
newbalance=balance+amt
accounts[id]=newbalance
print("Account updated")
print("Account Details:")
print(accounts)
Removing Data From
Dictionary
These are:
pop(key): removes the entry with provided key and returns it’s
value
clear(): clears all the items in the dictionary and returns an empty
dictionary
The pop() Method
dict_var.pop(key,[default])
Just like list , Python also allows us to delete an item from the
dictionary by calling the operator/keyword del
del dict_var[key]
If we do not pass the key then del deletes the entire dictionary
object
Guess The Output ?
Output:
The clear() Method
dict_var.clear( )
Output:
Functions Used With
Dictionary
len()
max()
min()
any()
all()
sorted()
The len( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(len(sixMonths))
Output:
6
The max( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(max(sixMonths))
Output:
May
Guess The Output ?
Output:
Guess The Output ?
Output:
6
Guess The Output ?
Output:
True
Guess The Output ?
data={False:0,True:1,None:2}
print(max(data))
Output:
Exercise
players={}
i=1
while i<=5:
name=input("Enter player name:")
runs=int(input("Enter runs:"))
players[name]=runs
i=i+1
print(players)
runs=max(players.values())
print("Highest runs are :",runs)
Exercise
Modify the previous code so that you are able to find out
the name of the player also who has scored the highest
score
Sample Output
Solution
players={}
i=1
while i<=5:
name=input("Enter player name:")
runs=int(input("Enter runs:"))
players[name]=runs
i=i+1
print(players)
max=0
pl=""
for name,runs in players.items():
if runs>max:
max=runs
pl=name
print("Player with top score is",pl,"with score of",max)
The min( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(min(sixMonths))
Output:
Apr
The any( ) Function
Example:
data={1:31,2:28,3:30}
print(any(data))
Output:
Guess The Output ?
data={0:1,False:2,'':3}
print(any(data))
Output:
Guess The Output ?
data={'0':1,False:2,'':3}
print(any(data))
Output:
Guess The Output ?
data= { }
print(any(data))
Output:
The all( ) Function
Example:
data={1:31,2:28,3:30,0:10}
print(all(data))
Output:
Guess The Output ?
data={1:31,2:28,3:30}
print(all(data))
Output:
Guess The Output ?
data={'0':1,True:2,' ':3}
print(all(data))
Output:
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output ?
data= { }
print(all(data))
Output:
The sorted( ) Function
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
The kwargs Function
Argument
Example:
def addnos(x,y,z):
print("sum:",x+y+z)
addnos(10,20,30)
addnos(10,20,30,40,50)
Output:
The kwargs Function
Argument
def addnos(*args):
sum=0
for x in args:
sum=sum+x
print("sum:",sum)
addnos(10,20,30)
addnos(10,20,30,40,50)
Output
The args Function
Argument
def show_details(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
show_details(Firstname="Amit", Lastname="Sharma",
Email="[email protected]", Country="India", Age=25,
Phone=9893198931)
The kwargs Function
Argument
PYTHON
LECTURE 37
Today’s Agenda
• Dictionary-III
• Dictionary Methods
• Dictionary Comprehension
• Restrictions On Keys
Dictionary Methods
clear()
copy()
get()
items()
keys()
pop()
update()
values()
The copy( ) Method
Syntax:
dict.copy()
Example:
original = {1:'one', 2:'two'}
new = original.copy()
print('new: ', new)
print('original: ', original)
Output:
copy( ) v/s =
Output: Output:
Using in And not in
With Dictionary
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
print(cars)
print("Hyundai is present:","Hyundai" in cars)
print("Audi is present:" ,"Audi" in cars)
print("Renault not present:","Renault" not in cars)
Output:
Dictionary Comprehension
Syntax:
Explanation
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
newcars={ k:v for (k,v) in cars.items()}
print(newcars)
Output:
Exercise
Output:
Exercise
Output:
Exercise
Output:
Solution
str=input("Type a string:")
mydict={ch:str.count(ch) for ch in str}
for k,v in mydict.items():
print(k,":",v)
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Adding Conditions To
Dictionary Comprehension
Syntax:
dict_variable = { key:value for (key,value) in iterable <test_cond>}
Output:
Exercise
Output:
Exercise
Output:
Restrictions On
Dictionary Keys
Example:
d={65:"A", 3.14:"pi", True:1}
print(d)
Output:
Restrictions On
Dictionary Keys
Example:
d={int:1, float:2, bool:3}
print(d)
print(d[float])
Output:
Restrictions On
Dictionary Keys
Example:
d={"MP":"Indore","UP":"Lucknow","RAJ":"Jaipur"}
print(d)
d["MP"]="Bhopal"
print(d)
Output:
Restrictions On
Dictionary Keys
Output:
Restrictions On
Dictionary Keys
Example:
d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
print(d)
print(d[(1,2)])
Output:
Restrictions On
Dictionary Keys
Example:
d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
print(d)
Output:
Restrictions On
Dictionary Values
IN→India
US→America
AU→Australia
CA→Canada
Sample Output
Solution
def show_menu():
print("SELECT AN OPTION:")
print("view: View country names")
print("add: Add a country")
print("del: Delete a country")
print("exit- Exit the program")
print()
def show_codes(countries):
pass
Solution
def view_country(countries):
pass
def add_country(countries):
pass
def del_country(countries):
pass
Solution
countries={"IN":"India","US":"America","AU":"Australia","CA
":"Canada"}
while True:
show_menu()
choice=input("Your choice:")
if choice=="view":
view_country(countries)
elif choice=="add":
add_country(countries)
elif choice=="del":
del_country(countries)
elif choice=="exit":
break;
else:
print("Wrong choice ! Try again!")
Exercise
Modify the previous code , so that now you are able to store
3 values for each key . These are COUNTRY NAME ,
CAPITAL CITY and POPULATION. Provide same options
to the user and start with the following data
IN→India , Delhi,1320000000
US→America,Washington,320000000
AU→Australia,Canberra,24000000
CA→Canada,Ottawa,940000
Sample Output
PYTHON
LECTURE 38
Today’s Agenda
In all the programs we wrote till now, we have designed our program
around functions i.e. blocks of statements which manipulate
data.
Syntax:
class <class_name>:
# class members
Example:
class Emp:
pass
Creating Objects
Syntax:
var_name=class_name( )
Example:
e=Emp()
Full Code
class Emp:
pass
1.The first line shows the class
name which is Emp.
Output:
Adding
Data Members/Attributes
class Emp:
def init (self):
print("Object created. . .")
class Emp:
def init (self):
print("Object created. . .")
e=Emp()
f=Emp()
g=Emp()
Output:
The argument self ?
What is self ?
Why it is required ?
What Is self ?
class Emp:
def init ():
print("Object created. . .")
As you can observe ,
Python has generated an
e=Emp() exception , since it has
passed the object address
as argument while calling
the method init () but
we have not declared any
argument to receive it
Output:
Can We Give Some Other Name
To self ?
class Emp:
def init (myself):
print("Object created. . .")
As you can observe ,
e=Emp() Python has allowed us to
use the name myself
instead of self , but the
convention is to always use
the word self
Output:
More About self
No , not at all
class Emp:
def init (self):
print("Object Created...")
e=Emp()
print(self)
Output:
The Most Important Role
Of self
Syntax:
class <class_name>:
def init (self):
self.<var_name>=value
.
.
Example
The variables
class Emp: self.age,self.name
and self.salary are
def init (self): called instance
variables
self.age=25
self.name="Rahul" Remember , we cannot
use self outside the class
self.salary=30000.0 . So outside the class we
will have to use the
reference variable e
e=Emp()
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Another very important
point to understand if you
Output: are from C++ background is
that in Python by default
everything in a class is
public . So we can direclty
access it outside the class
A Very Important Point!
Inside the methods of the class , they are always accessed using self so
that Python will refer them for current object
Outside the class , we cannot access them using self because self is
only available within the class.
So outside the class we have to access them using the object reference
we have created
Guess The Output ?
class Emp:
def init (self):
Unlike C++ or Java ,
self.age=25 in Python we can
self.name="Rahul" create instance
variables outside the
class by directly using
e=Emp() the object reference
e.salary=30000.0
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Output:
A Problem With The Code
class Emp:
def init (self,age,name,salary):
self.age=age
The variables age,
self.name=name
name an salary are
self.salary=salary called local variables
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
An Important Point
The variables age , name and salary used in the argument list
of init__() are called parameters or local variables.
class Emp:
def init (self,x,y,z):
self.age=x
self.name=y
self.salary=z
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
Guess The Output ?
class Emp:
e1=Emp("amit")
def init (self,name):
e2=Emp("sumit",23)
self.name=name
e3=Emp("deepak",34,50000.)
def init__(self,name,age):
print(e1.name)
self.name=name print(e2.name,e2.age)
self.age=age print(e3.name,e3.age,e3.sal)
def init (self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
Output:
Why Didn’t The Code Run ?
Yes !
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Solution
class Emp:
def init (self,name,age=0,sal=0.0):
self.name=name
self.age=age
self.sal=sal
e1=Emp("amit")
e2=Emp("sumit",23)
e3=Emp("deepak",34,50000.)
print(e1.name)
print(e2.name,e2.age)
print(e3.name,e3.age,e3.sal)
Output:
PYTHON
LECTURE 39
Today’s Agenda
• Types Of Methods
• Adding Instance Methods
• Obtaining Details Of Instance Variables
• Different Ways To Create Instance Variables
• Deleting Instance Variables
Adding
Methods In Class
class Emp:
def init (self,age,name,salary):
self.age=age
self.name=name
self.salary=salary
def show(self):
print("Age:",self.age,"Name:",self.name,"Salary:",self.salary)
e=Emp(25,"Rahul",30000.0)
f=Emp(31,"Varun",45000.0)
e.show()
f.show()
Output:
Exercise
import math
class Circle:
def init (self,radius):
self.radius=radius
def cal_area(self):
area=math.pi*math.pow(self.radius,2)
print("Area of circle is",area)
def cal_circumference(self):
circumf=math.tau * self.radius
print("Circumference of circle is",circumf)
radius=int(input("Enter radius:"))
cobj=Circle(radius)
cobj.cal_area()
cobj.cal_circumference()
Guess The Output ?
class Emp:
Output:
Guess The Output ?
class Emp:
Output:
Guess The Output ?
class Emp:
e1=Emp()
e1.show()
Output:
Obtaining Details Of
Instance Variables
class Emp:
e1=Emp()
print(e1. dict )
Output:
Guess The Output ?
class Emp:
e1=Emp()
print(e1. dict )
Output:
Guess The Output ?
class Emp:
e1=Emp() print(e1.
dict )
e1.set_sal()
print(e1.__dict )
Output:
Guess The Output ?
class Emp:
Since dict is a
def init (self): dictionary , we can
self.name="Amit" manipulate it and
self.age=24 add/del instance
self.sal=50000.0 members from it
def show(self):
print(self.name,self.age,self.sal,self.department)
e1=Emp()
print(e1.__dict )
e1.__dict ['department']='IT'
print(e1.__dict )
e1.show()
Output:
How Many Ways Are There To
Create Instance Variables ?
class Emp:
e1=Emp("Amit",24,30000.0)
def init (self,name,age,sal):
e2=Emp("Sumit",34,45000.0)
self.name=name
e1.setDept("Finance")
self.age=age
e1.setProject("Banking Info System")
self.sal=sal e1.setBonus(20000.0)
def setDept(self,department): e2.setDept("Production")
self.department=department print(e1.__dict )
def setProject(self,project): print() Since Python is
self.project=project print(e2. dictdyn)amically typed
def setBonus(self,bonus): language so object’s of
self.bonus=bonus same class can have
different number of
instance variables
Output:
Deleting Instance Variables
class Boy:
def init (self,name,girlfriend):
self.name=name
self.girlfriend=girlfriend
def breakup(self):
del self.girlfriend
b1=Boy("Deepak","Jyoti")
print(b1. dict )
b1.breakup()
print(b1.girlfriend)
Output:
Guess The Output ?
class Engineer:
def init (self,girlfriend,job):
self.girlfriend=girlfriend
self.job=job
def fired(self):
del self.job
e1=Engineer("Rani","Software Engineer")
print(e1.__dict )
e1.fired()
del e1.girlfriend
print(e1.__dict )
Output:
Guess The Output ?
class Emp:
def init (self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
e1=Emp("Amit",24,50000.0)
print(e1.__dict )
del e1
print(e1. dict )
Output:
Guess The Output ?
Output:
Guess The Output ?
For example :
Syntax:
class <class_name>:
<var_name>=<value>
def init__(self):
This is called a
// object specific code class variable
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
How To Modify
Class Variables?
Using name of the class anywhere inside the methods of the class
class CompStudent:
The variable
stream = 'cse' stream is class
def init (self,name,roll): variable
self.name = name
self.roll = roll
Everytime we will access
obj1 = CompStudent('Atul',1) the class variable stream
obj2 = CompStudent('Chetan', 2) from any object , the
print(obj1.name) value will remain same
print(obj1.roll)
print(obj1.stream)
print(obj2.name)
print(obj2.roll) Output:
print(obj2.stream)
print(CompStudent.stream)
Exercise
class Emp:
raise_amount=7.5
def init (self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
def increase_sal(self):
self.sal=self.sal+(self.sal*Emp.raise_amount/100)
def display(self):
print(self.name,self.age,self.sal)
e1=Emp("Amit",24,50000.0)
e2=Emp("Sumit",26,45000.0)
print("Before incrementing :")
print(" ");
e1.display()
e2.display()
e1.increase_sal()
e2.increase_sal()
print()
print("After incrementing by",Emp.raise_amount,"percent:")
print(" _");
e1.display()
e2.display()
Declaring Class Variable
Inside Constructor
def init__(self):
<class name>.<var_name>=<value>
self.<var_name>=<value>
.
.
.
Example
class CompStudent:
We have shifted the
var decl from class
def init (self,name,roll): body to constructor
CompStudent.stream='cse' body , but still it will
self.name = name be treated as class
self.roll = roll variable because we
have prefixed it with
classnname
obj1 = CompStudent('Atul',1)
obj2 = CompStudent('Chetan', 2)
print(obj1.name)
print(obj1.roll)
print(obj1.stream)
print(obj2.name)
print(obj2.roll) Output:
print(obj2.stream)
print(CompStudent.stream)
Declaring Class Variable
Inside Instance Method
def <method_name>(self):
<class name>.<var_name>=<value>
self.<var_name>=<value>
.
.
.
Example
class Emp:
raise_per=7.5
comp_name="Google"
def init (self):
self.name="Amit"
self.age=24
self.sal=50000.0
e1=Emp()
print(e1. dict )
print()
print(Emp.__dict )
Output:
How many class variables
will be created by this code?
class Sample:
i=10
def init (self):
Sample.j=20
def f1(self): Three class variables
Sample.k=30 will be created by the
Sample.m=40 code called i,j and m
s1=Sample()
print(Sample.__dict )
Output:
How many class variables
will be created by this code?
class Sample:
i=10
def init__(self):
Sample.j=20
def f1(self):
Sample.k=30
Sample.m=40
s1=Sample()
s2=Sample()
s1.f1()
s2.f1()
print(Sample. dict )
Output:
Guess The Output ?
class Sample:
i=10
def init__(self):
print("Constructor called. . .")
print(Sample.i)
print(self.i)
def f1(self):
print("f1 called. . .")
print(Sample.i)
print(self.i)
s1=Sample()
s1.f1()
Output:
Guess The Output ?
As mentioned previously , if
class Sample: we use self or object reference
i=10 to modify a class variable ,
then Python does not modify
def init (self): the class variable . Rather it
self.i=20 creates a new instance
variable inside the object’s
memory area by the same
name.
s1=Sample() So in our case 2 variables by
print(Sample.i) the name i are created . One as
class variable and other as
instance variable
Output:
Guess The Output ?
class Sample:
i=10
def init (self):
self.i=20
s1=Sample()
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def init (self):
Sample.i=20
s1=Sample()
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init (self):
Sample.i=20
s1=Sample()
s1.i=30
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init (self):
self.j=20
s1=Sample()
s2=Sample()
s1.i=100
s1.j=200
print(s1.i,s1.j)
print(s2.i,s2.j)
Output:
Guess The Output ?
class Sample:
i=10
def f1(self):
self.j=20
s1=Sample()
s2=Sample()
s1.i=100
s1.j=200
print(s1.i,s1.j)
print(s2.i,s2.j)
Output:
Deleting Class Variables
class Sample:
i=10
def init (self):
del Sample.i
print(Sample.__dict )
s1=Sample()
print()
print(Sample.__dict )
Output:
Guess The Output ?
class Sample:
i=10
def init (self):
del self.i
print(Sample.__dict )
s1=Sample()
print()
print(Sample.__dict )
Output:
Guess The Output ?
class Sample:
i=10
def init (self):
del Sample.i
print(Sample.__dict )
s1=Sample()
del Sample.i
print()
print(Sample.__dict )
Output:
PYTHON
LECTURE 41
Today’s Agenda
• Class Methods
• Creating Class Methods
• Accessing Class Methods
• Static Methods
• Accessing Static Methods
• Difference Between Instance Method , Class Method and Static
Methods
Class Methods
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Exercise
• Encapsulation
• The Destructor
Encapsulation
self.name="Rahul"
self.salary=30000.0
e=Emp()
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Output:
How To Achieve Encapsulatio n
In Python ?
Syntax:
self.__<var_name>=<value>
Achieving Encapsulation
e=Emp()
print("Age:",e.age)
print("Name:",e.name)
print("Salary:",e.__salary)
Output:
Achieving Encapsulation
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Achieving Encapsulation
class Emp:
def init (self):
self.__age=25
self.__name="Rahul"
self.__salary=30000.0
def show(self):
print("Age:",self.__age,"Name:",self.__name,"Salary:",self.__salary)
e=Emp()
e.show()
Output:
Private Methods
class Emp:
def init (self):
self.__age=25
self.__name="Rahul"
self.__salary=30000.0
def show(self):
print("Age:",self.__age,"Name:",self.__name,"Salary:",self.__salary)
e=Emp()
e.__show()
Output:
An Important Point
class Emp:
def init (self):
self. age=25
self. name="Rahul"
self. salary=30000.0
def show(self):
print("Age:",self. age,"Name:",self. name,"Salary:",self. salary)
e=Emp()
e.show()
print("Age:",e._Emp age,"Name:",e._Emp name,"Salary:",e._Emp salary)
Output:
The str () Method
For predefined classes like list ,tuple or str , we get the contents of
the object
For our own class objects we get the class name and the id of the
object instance (which is the object’s memory address in CPython.)
Why Is It So ?
obj=object()
print(type(obj))
print(dir(obj))
Output:
The str () Method
class Emp:
def init (self,age,name,salary):
self.age=age
self.name=name
self.salary=salary
def str (self):
return f"Age:{self.age},Name:{self.name},Salary:{self.salary}"
e=Emp(25,"Rahul",30000.0)
print(e)
Output:
Destructor
class Test:
def init (self):
print("Object created")
class Test:
We must remember that Python
def init (self): destroys the object only when the
print("Object created") reference count becomes 0 . Now
in this case after deleting t1 , still
the object is being refered by t2 .
def del (self): So the del__() was not called
print("Object destroyed") on del t1. It only gets called when
t1=Test() t2 also goes out of scope at the
end of the program and reference
t2=t1 count of the object becomes 0
del t1
print("done")
Output:
Guess The Output ?
class Test:
def init (self):
print("Object created")
def del__(self):
print("Object destroyed")
t1=Test()
t2=t1
del t1
print("t1 deleted")
del t2
print("t2 deleted")
print("done")
Output:
PYTHON
LECTURE 43
Today’s Agenda
• Inheritance
• Types Of Inheritance
• Single Inheritance
• Using super( )
• Method Overriding
Inheritance
The new class is called derived (or child) class and the
one from which it inherits is called the base (or parent)
class.
Real Life Examples
Real Life Examples
Benefits
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
For Ex:
class Account:
pass
class SavingAccount(Account):
pass
Example
class A:
def init (self):
print("Instantiating A...")
As you can see,
class B(A): Python called the
constructor of class
pass A , since B class
doesn’t has any
b=B() constructor defined
Output:
How Constructors Behave
In Inheritance ?
class A:
def init (self):
print("Instantiating A...")
This time , Python
class B(A): did not call the
constructor of class
def __init (self): A as it found a
print("Instantiating B...") constructor in B
itself
b=B()
Output:
How Constructors Behave
In Inheritance ?
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Calling Parent Constructor
Using Name
class Rectangle:
def init (self): Notice that we have
self.l=10 to explicitly pass the
self.b=20 argument self while
calling init ()
method of parent
class Cuboid(Rectangle): class
def __init (self):
Rectangle. init (self)
self.h=30
def volume(self):
print("Vol of cuboid is",self.l*self.b*self.h)
obj=Cuboid()
obj.volume()
Output:
Calling Parent Constructor
Using super( )
class Rectangle:
Again notice that this
def init (self): time we don’t have to
self.l=10 pass the argument
self.b=20 self when we are
using super( ) as
class Cuboid(Rectangle): Python will
def __init (self): automatically pass it
super(). init ();
self.h=30
def volume(self):
print("Vol of cuboid is",self.l*self.b*self.h)
obj=Cuboid()
obj.volume()
Output:
What Really Is super( ) ?
We don’t have to pass self while calling any method using super( ).
If the name of parent class changes after inheritance then we will not
have to rewrite the code in child as super( ) will automatically connect
itself to current parent
class Person:
def init (self,age,name):
self.age=age
self.name=name
def str (self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def init (self,age,name,id,sal):
super().__init (age,name)
self.id=id
self.sal=sal
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Explanation
Now since the class Person has this method , Python calls
the str () method of Person which returns only the
name and age
Method Overriding
class Person:
def init (self,age,name):
self.age=age
self.name=name
def str (self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def init (self,age,name,id,sal):
super().__init (age,name)
self.id=id
self.sal=sal
def str (self):
return f"Age:{self.age},Name:{self.name},Id:{self.id},Salary:{self.sal}"
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Role Of super( )
In Method Overriding
class Person:
def init (self,age,name):
self.age=age
self.name=name
def str (self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def init (self,age,name,id,sal):
super(). init (age,name)
self.id=id
self.sal=sal
def str (self):
str=super(). str ()
return f"{str},Id:{self.id},Salary:{self.sal}"
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Exercise
init_ () : This method should accept an argument and initialize radius with it
init_ () : This method should initialize instance members radius and height
with the parameter passed.
area( ): This method should override Circle’s area( ) to calculate and return area of
Cylinder . ( formula: 2πr2+2πrh)
Output:
A Very Important Point!
Syntax:
<base_class_name>.<method_name>(<der_obj>)
Example
Output:
PYTHON
LECTURE 44
Today’s Agenda
• MultiLevel Inheritance
• Hierarchical Inheritance
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
class C(B):
# class C inheriting property of class B
# thus, class C also inherits properties of class A
# more properties of class C
Exercise
class Person:
def init (self,age,name):
self.age=age
self.name=name
print("Person constructor called. . .")
def str (self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def init (self,age,name,id,sal):
super().__init (age,name)
self.id=id
self.sal=sal
print("Emp constructor called. . .")
def income(self):
return self.sal
class Manager(Emp):
def init (self,age,name,id,sal,bonus):
super().__init (age,name,id,sal)
self.bonus=bonus
print("Manager constructor called. . .")
def income(self):
total=super().income()+self.bonus
Output:
return total
def str (self):
str=super().__str ()
return f"{str},Bonus:{self.bonus}"
m=Manager(24,"Nitin",101,45000,20000)
print(m)
print("Manager's Salary:",Emp.income(m))
print("Manager's Total Income:",m.income())
Hierarchical Inheritance
class SchoolMember:
def tell(self):
class Teacher(SchoolMember):
def tell(self):
super().tell()
print("Salary:",self.salary)
Example
class Student(SchoolMember):
Syntax:
class MyBase(object):
pass
class MyDerived(MyBase):
pass
print(issubclass(MyDerived, MyBase))
print(issubclass(MyBase, object))
print(issubclass(MyDerived, object))
print(issubclass(MyBase, MyDerived))
Output:
Guess The Output ?
class MyBase:
pass In Python 3 , every
class implicitly
inherits from object
class MyDerived(MyBase):
class but in Python 2
pass it is not so. Thus in
Python 2 the 2nd and
3rd print( ) statements
print(issubclass(MyDerived, MyBase))
would return False
print(issubclass(MyBase, object))
print(issubclass(MyDerived, object))
print(issubclass(MyBase, MyDerived))
Output:
Alternate Way
Syntax:
class MyBase:
pass Output:
class MyDerived(MyBase):
pass
d = MyDerived()
b = MyBase() print(isinstance(d,
MyBase)) print(isinstance(d,
MyDerived))
print(isinstance(d, object))
print(isinstance(b, MyBase))
print(isinstance(b, MyDerived))
print(isinstance(b, object))
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 45
Today’s Agenda
• Multiple Inheritance
• The MRO Algorithm
• Hybrid Inheritance
• The Diamond Problem
Multiple Inheritance
class A:
# properties of class A
class B:
#properties of class B
class C(A,B):
# class C inheriting property of class A
# class C inheriting property of class B
# more properties of class C
Example
def getroll(self):
return self.roll
Output:
def getper(self):
return self.per
Guess The Output ?
class A:
Output:
def m(self):
print("m of A called")
Why did m( ) of A
class B: got called ?
def m(self): This is because of a
print("m of B called") special rule in
Python called MRO
class C(A,B):
pass
obj=C()
obj.m()
What Is MRO In Python ?
MRO RULE :
In the multiple inheritance scenario, any specified attribute is searched
first in the current class. If not found, the search continues into
parent classes, left-right fashion and then in depth-first
without searching same class twice.
Can We See This MRO ?
class A:
def m(self):
print("m of A called")
class B:
def m(self):
print("m of B called")
class C(A,B):
pass
print(C.mro())
Output
Another Way To See MRO ?
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Example
class A:
def m(self):
print("m of A called")
class B:
def m(self):
print("m of B called")
class C(A,B):
pass
print(C.__mro )
Output
The Hybrid Inheritance
class A: obj=D()
def m1(self): obj.m1()
print("m1 of A called") obj.m2()
class B(A): obj.m3()
def m2(self):
print("m2 of B called")
class C(A):
def m3(self):
print("m3 of C called")
class D(B,C):
pass
Output:
The Diamond Problem
class A:
obj=D()
def m(self):
print("m of A called") obj.m()
class A:
obj=D()
def m(self):
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(C,B):
pass
Output:
Guess The Output
class A:
obj=D()
def m(self):
obj.m()
print("m of A called")
Why m() of C was called ?
class B(A):
pass MRO goes from left to right first
and then depth first. In our case
class C(A): Python will look for method m()
def m(self): in B but it won’t find it there .
Then it will search m() in C
print("m of C called")
before going to A. Since it finds
m() in C, it executes it dropping
class D(B,C): the further search
pass
Output:
Guess The Output
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(B,C):
def m(self):
print("m of D called")
Output:
PYTHON
LECTURE 46
Today’s Agenda
• Exception Handling
• Introduction To Exception Handling
• Exception Handling Keywords
• Exception Handling Syntax
• Handling Multiple Exceptions
• Handling All Exceptions
What Is An Exception ?
Output:
How To Handle
Such Situations ?
try
except
else
raise
finally
Exception Handling Syntax
try: Remember !
In place of Exception I and
You do your operations here; Exception II , we have to use
the names of Exception
......................
classes in Python
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Improved Version
Of Previous Code
A try statement may have more than one except clause for
different exceptions.
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(3)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Exercise
If the user enters a non integer value then ask him to enter only integers
If denominator is 0 , then ask him to input non-zero denominator
Repeat the process until correct input is given
Only if the inputs are correct then display their division and
terminate the code
Sample Output
Solution
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
Single except,
Multiple Exception
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except (ValueError,ZeroDivisionError):
print("Either input is incorrect or denominator is 0. Try
again!")
Sample Output
Handling All Exceptions
In this case for every exception this except clause will run
.
The only problem will be that we will never know the type
of exception that has occurred!
Exception Handling Syntax
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:")) c=a/b
print("Div is ",c) break
except:
print("Some problem occurred. Try again!")
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Sample Output
PYTHON
LECTURE 47
Today’s Agenda
• Exception Handling
• Using Exception Object
• Getting Details Of Exception
• Raising An Exception
• Using finally Block
• Creating User Defined Exceptions
Using Exception Object
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except (ValueError,ZeroDivisionError) as e:
print(e)
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Sample Output
Obtaining Exception Details
Using traceback class
import traceback
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except:
print(traceback.format_exc())
Sample Output
Raising An Exception
Syntax:
raise ExceptionClassName
raise ExceptionClassName( message )
Exercise
If the user enters a non integer value then ask him to enter only integers
If denominator is 0 , then ask him to input non-zero denominator
If any of the numbers is negative or numerator is 0 then
display the message negative numbers not allowed
Repeat the process until correct input is given
Only if the inputs are correct then display their division and
terminate the code
Sample Output
Solution
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
if a<=0 or b<0:
raise Exception("Negative numbers not allowed!Try again")
c=a/b
print("Div is ",c)
break;
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
except Exception as e:
print(e)
The finally Block
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output ?
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except ZeroDivisionError:
print("Denominator should not be zero")
finally:
print("Thank you for using the app!")
Output:
Creating User Defined
Exception
• Operator Overloading
class Point:
def init (self,x,y):
self.x=x
self.y=y
def str (self): Why did TypeError occur?
return f"x={self.x},y={self.y}"
TypeError was raised since
Python didn't know how to
p1=Point(10,20) add two Point objects
p2=Point(30,40) together.
p3=p1+p2
print(p3)
Output:
How To Perform
Operator Overloading?
class Point:
def init (self,x,y):
self.x=x
self.y=y
def add (self,other):
x=self.x+other.x
y=self.y+other.y
p=Point(x,y)
return p
It searched for the magic method add () in our Point class since
the left side operand i.e. p1 is of Point class.
Finally addition was done and a new object p was returned which was
copied to p3
Guess The Output
class Point:
def init (self,x,y):
self.x=x
self.y=y
def add (self,other):
x=self.x+other.x
y=self.y+other.y
p=Point(x,y)
return p
init_ () : This method should accept 2 arguments and initialize feet and
inches with it
str (): This method should return string representation of feet and inches
add () : This method should add 2 Distance objects and return another
Distance object as the result. While adding if sum of inches becomes >=12 then it
should be appropriately converted to feet
Solution
Output:
Solution
init__() : This method should accept 2 arguments and initialize nameand price
with it
str (): This method should return string representation of name and price
add () : This method should add price of 2 Books and return the total price
Solution
Output:
Guess The Output ?
Output:
Why Did TypeError Occur ?
So Python called add () method of Book class since the left operand
is b1 which is object of class Book
Now Python used 800 as the calling object and b3 as argument so the
call became 800.__add (b3).
So Python now looks for a method add () in int class which can add
an int and a book but it could not find such a method in int class which can
take Book object as argument .
init_ () : This method should accept 2 arguments and initialize feet and
inches with it
str (): This method should return string representation of feet and inches
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
PYTHON
LECTURE 49
Today’s Agenda
• What Is DBMS ?
• What Is SQL ?
What is Data?
What is Database ?
Introduction
What is Data?
What is a Database?
A database is a collection of inter-related data or information that is
organized so that it can easily be accessed, managed, and updated .
Let's also consider the Facebook. It needs to store, manipulate and present
data related to members, their friends, member activities, messages,
advertisements and lot more. Here also database is used
How Databases
Store The Data ?
Oracle
MySQL
MS SQL Server
SQLite
PostgreSQL
IBM DB2
Advantages:
Platform-independent
No complex setup
Fully transactional.
DROP a column.
ADD a constraint.
SQLite Limitations
We can use SQLite from the command line tools, but there
is a GUI-based utility which lets us use SQLite through
a decent graphical interface.
import sqlite3
Step 2-
Establishing The Connection
After importing the module ,we must open the connection to the
SQlite.
It can also hold the set of rows returned by the query and lets us
work with the records in that set, in sequence, one at a time.
cur=conn.cursor()
Important Attributes/Methods Of
Cursor Object
Syntax:
For example:
cur.execute('select * from allbooks')
The execute( ) Method
Example:
cur.close()
conn.close()
An Important Point!
The Cursor object holds all the rows it retrieved from the
database as tuples.
Execute the query to select name of the book and it’s price from the
table Allbooks
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks")
for x in cur:
print(x)
except (sqlite3.DatabaseError)as ex:
print("Error in connecting to Sqlite:",ex)
finally:
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Exercise
import sqlite3
conn=None We will just have to unpack
try: each row of the tuple to get
the individual values
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks")
for name,price in cur:
print(name,price)
except (sqlite3.DatabaseError)as ex:
print("Error in connecting to Sqlite:",ex)
finally:
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Using The Method fetchone( )
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Sample Output
Solution
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks order by bookprice desc")
x=cur.fetchone()
if x is not None:
print(x)
Syntax:
cur.fetchall()
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks order by bookprice desc")
x=cur.fetchall()
print(x)
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Output
Exercise
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks
order by bookprice desc")
booklist=cur.fetchall()
recnum=int(input("Enter the record number(1 to
"+str(len(booklist))+"):"))
Solution
It has 2 syntaxes:
After executing insert if we want to get the number of row inserted we can
use the cursor attribute rowcount
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Insert into allbooks values(108,'Python Web
Prog',500,'Python')")
n=cur.rowcount
print(n," row inserted")
conn.commit()
s ex:
except (sqlite3.DatabaseError)a
print("Error in connecting to Sqlite:",ex)
finally:
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Executing Dynamic Queries
It has 2 syntaxes:
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Update allbooks set bookprice=500 where bookid=201 ")
n=cur.rowcount
print(n," row updated")
conn.commit()
except (sqlite3.DatabaseError)as ex:
print("Error in connecting to Sqlite:",ex)
finally:
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Exercise
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Sample Output
Sample Run 1
Sample Run 2
Solution
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
subject=input("Enter subject name:")
amount=int(input("Enter the amount to increase:"))
cur=conn.cursor()
cur.execute("Update allbooks set bookprice=bookprice+:1 where
subject=:2",(amount,subject))
n=cur.rowcount
if n==0:
print("No rows updated")
else:
print(n, "rows updated")
conn.commit()
It has 2 syntaxes:
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Delete from allbooks where bookid=109")
n=cur.rowcount
print(n," row deleted")
conn.commit()
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Sample Output
Sample Run 1
Sample Run 2
Solution
import sqlite3
conn=None
try:
conn=sqlite3.connect("d:/mysqlitedb/library.db")
print("Connected successfully to the DB")
cur=conn.cursor()
subject=input("Enter subject name:")
cur.execute("Delete from allbooks where subject=:1",(subject,))
n=cur.rowcount
if n==0:
print("No rows deleted")
else:
print(n," rows deleted")
conn.commit()
except (sqlite3.DatabaseError)as ex:
print("Error in connecting to Sqlite:",ex)
finally:
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
PYTHON
LECTURE 52
Today’s Agenda
• File Handling
• What Is File Handling ?
• What Is The Need Of File Handling ?
• Examples Where Files Are Used?
• Python’s Way Of Handling Files
• File Opening Modes
• Writing In A File
• Different Ways For Reading From A File
What Is File Handling ?
Mobile’s Phonebook
Computer/Mobile Games
Call Logs
Gallery In Mobile
Windows Registry
Steps Needed For File Handling
Syntax:
Mode Description
Mode Description
Example 1:
f = open("employees.txt", "r")
Example 2:
f = open("teams.txt", "w")
Example 3:
f = open("teams.txt", "a")
For example:
f = open("C:/Users/sachin/documents/README.txt", "w")
f = open(r"C:\Users\sachin\documents\README.txt", "w")
f.close()
The TextIOWrapper Class
Method Description
Reads the specified number of characters
from the file and returns them as string.
read([num]) If num is omitted then it reads the entire
file.
readline() Reads a single line and returns it as a string.
Reads the content of a file line by line and
readlines()
returns them as a list of strings.
Writes the string argument to the file and
write(str) returns the number of characters written to
the file.
Moves the file pointer to the given offset
seek(offset, origin)
from the origin.
Now ask the user to type a message and write it in the file .
Also properly handle every possible exception the code can throw
Sample Output
Solution
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Solution
fin=None
try:
fin=open("d:\\message.txt","r")
text=fin.read()
print(text)
except FileNotFoundError as ex:
print("Could not open the file: ",ex)
finally:
if fin is not None:
fin.close()
print("File closed successfully")
Output:
Exercise
Now ask the user to continuously type messages and save them in the
file line by line.
Also properly handle every possible exception the code can throw
Sample Output
Solution
fout=None
try:
fout=open("d:\\message.txt","w")
text=input("Type your message and to stop just press ENTER on a newline\n")
lines=0
while True:
if text=="":
break
lines+=1
fout.write(text+"\n")
text=input()
finally:
if fout is not None:
fout.close()
print("File closed successfully")
Exercise
Now read and display the contents of the file line by line.
try:
fin=open("d:\\message.txt","r")
lines=0
while True:
text=fin.readline()
if text=="":
break
lines+=1
print(text,end="")
finally:
if fin is not None:
fin.close()
print("File closed successfully")
Using for Loop To
Read The File
The only point is that when we use for loop on the file
object , Python reads and returns one line at a time.
Exercise
Now read and display the contents of the file line by line.
fin=None
try:
fin=open("d:\\message.txt","r")
lines=0
for text in fin:
print(text,end="")
lines+=1
print("Total lines read are :",lines)
finally:
if fin is not None:
fin.close()
print("File closed successfully")
PYTHON
LECTURE 53
Today’s Agenda
• File Handling
• The seek( ) Method
• Appending In A File
• Using with Statement
The seek( ) Method
Syntax:
seek(offset, whence).
If it is 2, then the bytes are counted from the end of the file.
offset describes how far from whence that the cursor moves.
seek( ) Examples
f.seek(45,0)
would move the cursor to 45 bytes/letters after the beginning of the file.
f.seek(10,1)
would move the cursor to 10 bytes/letters after the current cursor position.
f.seek(-77,2)
would move the cursor to 77 bytes/letters before the end of the file (notice the -
before the 77)
Special Note:
Python 3 only supports text file seeks from the beginning of the file.
If we try to call seek() with non-zero value for offset from cur or end then the
code will throw an exception called:
UnsupportedOperation: can't do nonzero end-relative seeks
Thus for seek() to work , the file must be a binary file like image file, music file
etc.
Exercise
Now ask the user to continuously type messages and save them in the
file line by line.
Now read and display the contents of the file line by line.
Finally also display total number of lines read from the file.
Also properly handle every possible exception the code can throw
Sample Output
Solution
try:
fobj=open("d:\\message.txt","w+")
text=input("Type your message and to stop just press ENTER on a newline\n")
lines=0
while True:
if text=="":
break
lines+=1
fobj.write(text+"\n")
text=input()
while True:
text=fobj.readline()
if text=="":
break
lines+=1
print(text,end="")
finally:
if 'fobj' in globals():
fobj.close()
print("File closed successfully")
Appending Data In a File
When we open the file in “a” or “a+” mode , the internal file
pointer is placed at the end while writing the new data.
Thus , the new text we write does not overwrite the previous
contents of the file.
days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
fobj=None
try:
fobj=open("d:\\days.txt","a")
items=0
for day in days[:3]:
fobj.write(day+"\n")
items+=1
fobj.close()
print(items," values written")
print("File closed")
items=0
fobj=open("d:\\days.txt","a")
for day in days[3:]:
fobj.write(day+"\n")
items+=1
fobj.close()
print(items," more values written")
print("File closed")
print("Press any key to read back the file")
input()
Example
fobj=open("d:\\days.txt","r")
for day in fobj:
print(day,end="")
finally:
if fobj is not None:
fobj.close()
print("File closed successfully")
Using with Statement
try:
with open("d:\\message.txt","r") as fin:
lines=0
for x in fin:
print(x,end="")
lines+=1
print("Total lines read are :",lines)
print("File closed successfully!")
except FileNotFoundError as ex:
print("Could not open the file: ",ex)
PYTHON
LECTURE 54
Today’s Agenda
• Modules
• What is a module ?
• Different ways of importing module
• The concept of the variable name
What Is A Module ?
variables
functions
classes
Defining A Module
def greet(name):
print("Good Morning ",name,"!")
welcome.py
def greet(name):
print("Good Morning ",name,"!")
Using A Module
Using import
Using aliasing
Using from
Using wildcard
First Way
(Direct import)
Syntax:
welcome.greet(<arg>)
First Way
(Direct import)
test.py
import welcome
name=input("What is your name?")
welcome.greet(name)
Run:
python test.py
Output:
What is your name?Sachin
Good Morning Sachin !
Second Way
(Using aliasing)
Syntax:
import <module_name> as <new_name>
Second Way
(Using aliasing)
test.py
import welcome as w
name=input("What is your name?")
w.greet(name)
Run:
python test.py
Output:
What is your name?Sachin
Good Morning Sachin !
Guess The Output ?
test.py
import welcome as w
name=input("What is your name?")
welcome.greet(name)
Run:
python test.py
Output:
What is your name?Sachin
NameError: name 'welcome' is not defined
Guess The Output ?
test.py
import welcome
import welcome as w
name=input("What is your name?")
welcome.greet(name)
w.greet(name)
Run:
python test.py
Output:
What is your name?Sachin
Good Morning Sachin!
Good Morning Sachin!
Third Way
Syntax:
from modname import name1[, name2[, ... nameN]]
Third Way
test.py
from welcome import greet
name=input("What is your name?")
greet(name)
Run:
python test.py
Output:
What is your name?Sachin
Good Morning Sachin !
Guess The Output ?
m1.py m2.py
def greet(name): def greet(name):
print("Good Morning ",name,"!")) print("Good Evening ",name,"!"))
test.py Execution
from m1 import greet Run:
from m2 import greet python test.py
name=input("What is your name?") Output:
greet(name) What is your name?Sachin
Good Evening Sachin !
Guess The Output ?
m1.py m2.py
def greet(name): def greet(name):
print("Good Morning ",name,"!")) print("Good Evening ",name,"!"))
test.py Execution
from m1 import greet Run:
from m2 import greet python test.py
name=input("What is your name?") Output:
m1.greet(name) What is your name?Sachin
NameError: name 'm1' is not defined
Guess The Output ?
welcome.py
def greet1(name):
print("Good Morning ",name,"!")
def greet2(name):
print("Good Afternoon ", name, "!")
test.py Execution
from welcome import greet1 Run:
name=input("What is your name?") python test.py
greet1(name) Output:
greet2(name) What is your name?Sachin
Good Morning Sachin !
NameError: name ‘greet2' is not defined
Fourth Way
Syntax:
from modname import *
This allows us to use all the items from a module into the
current file
Fourth Way
welcome.py
def greet1(name):
print("Good Morning ",name,"!")
def greet2(name):
print("Good Afternoon ", name, "!")
test.py Execution
from welcome import * Run:
name=input("What is your name?") python test.py
greet1(name) Output:
greet2(name) What is your name?Sachin
Good Morning Sachin !
Good Afternoon Sachin !
Defining A Class
In A Module
shape.py
import math
class Circle:
def init (self,radius):
self.radius=radius
def area(self):
print("Area is",math.pi*math.pow(self.radius,2))
Using The Class
Outside The Module
useshape.py
import shape
radius=int(input("Enter radius:"))
obj=shape.Circle(radius)
obj.area()
Run:
python useshape.py
Output:
Enter radius:3
Area is 28.274333882308138
The Concept Of
name ==‘ main__’
if name==‘ main ’:
Some code
add(10,20)
subtract(10,20)
Run:
python calculate.py
Output:
Sum of 10 and 20 is 30
Diff of 10 and 20 is -10
The Concept Of
name ==‘ main__’
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
Guess The Output
calculate.py Execution
def add(a, b): Run:
print("Sum of",a,"and",b,"is",a+b) python test.py
Output:
def subtract(a, b):
Sum of 10 and 20 is 30
print("Diff of", a, "and", b, "is", a - b)
Diff of 10 and 20 is -10
add(10, 20) Sum of 5 and 7 is 12
subtract(10, 20)
test.py
import calculate
calculate.add(5,7)
Why 3 Outputs ?
import calculate
Otherwise this variable has the name of the file as it’s value
The Concept Of
name ==‘ main__’
calculate.py Execution
def add(a, b): Run:
print("Sum of",a,"and",b,"is",a+b) python test.py
Output:
def subtract(a, b):
Sum of 5 and 7 is 12
print("Diff of", a, "and", b, "is", a - b)
if name =="__main__":
add(10, 20)
subtract(10, 20)
test.py
import calculate
calculate.add(5,7)
These Notes Have Python_world_In Notes Copy rights under copy right
Acts of Government of India. So commercial Use of this notes is Strictly prohibited
CONTENT
Chapter 1: Introduction To C
Chapter 2: Start Learning C
Chapter 3: Arithmetic Instruction
Chapter 4: Control Instruction
Chapter 5: Iterative Control Instruction
Chapter 6: Function and Storage Classes
Chapter 7: Arrays
Chapter 8: Strings
Chapter 9: Pointers
Chapter 10: Structure and DMA
Chapter 1: Introduction To C
Content
1.1 What is a Computer?
1.3 Hardware
1.4 Files
1.10 History of C
1.11 IDE
You can deliver this exe file to your client. He can enjoy your software without seeing your
code. In the later segment you would understand why he can’t see your programming code.
1.5 Program and Process
Program is a set of instruction to perform a particular task.
Active state of a program is called process. Running the program instructions is called
process.
1.6 Software and its Types
A computer is just a machine. It can’t do anything without any instructions. Set of
instructions given to a computer in a precise manner to do a task is called Software.
Set of instructions are written in a programming language.
Software can be classified into following two main categories or types
1. System Software:
It includes program that are necessary to operate and control a computer
system.
E.g. Operating System, Device Drivers
2. Application Software: A program or set of programs designed for a specific
purpose.
E.g. MS Word, Web Browser
1.7 Operating System
Operating system is essential software which provides an interface between user and
machine. OS is also a program which enables the computer hardware to work with the
computer software. It acts as a manager in the system, which manages hardware and
software resources. It also does process management, memory management and file
management.
Examples of Operating systems are windows XP, Windows 2007, Windows 2008, Linux, etc.
1.8 How a Program Executes
It is important to describe the role of few of the hardware resources during execution of
program. Earlier we talked about an executable file. Here we are describing execution
process of any one of such exe file.
Firstly, your program (sum.exe) file is stored somewhere in hard disk of your system. Now
we clicked on it to run this program. This click event from mouse is listened by operating
system and loads this file from hard disk to RAM (random access memory) using loader (a
dedicated program to load content to RAM). Here it is important to note that each time when
some program need to be activate, program must load in to RAM. RAM is also known as
primary memory which is volatile in nature that is nothing can reside permanently. RAM
contains only those programs that are active at a particular instant.
It’s the job of Operating system to allocate memory for our program in RAM. First
instruction goes to the processor and resides in instruction register. This instruction is
decoded by control unit. Control unit sends appropriate signal to ALU. ALU performs
specific task.
Registers, control unit and Arithmetic Logic Unit are part of processor. ALU is responsible to
perform all kind of arithmetic, logical and shift instructions.
Again next instruction moves to processor and stored at instruction register, control unit
decode it and sends a signal to ALU. Every instruction of the program executes in similar
fashion in a sequential manner.
As soon as the last instruction is executed memory of the program will released from RAM.
Executable files are machine code which is operating system dependent and hardware dependent.
To create such file we need to know about hardware specifications and OS policies. This increases
extra learning overhead to the programmer. One easy solution is to learn a simple hardware
independent coding language like C.
Once you learn C language you can write code (known as source code) and save it as a source file(*.c
extension only). This code is not readable for machine. You need to convert it into machine code. A
software known as compiler is used as a translator, which translates your source code in to object
code (binary code).
Object files containing machine code are not sufficient to understand by computer, you need to link
this code with predefined code needed for execution of a program stored in library files. This can be
done with the help of software called linker. Linker generates an executable file. (*.exe file)
· C language was developed by Dennis Ritchie in 1972 at AT & T’s Bell Labs, New Jersy, USA.
· C is a middle level language that is a combination of high level and low level language.
1.11 IDE
· Compiler or interpreter
· Build automation
· A debugger
There are’ n’ numbers of IDEs available for C. They are specific to operating system. These IDEs not
only gives you facility to write and edit code but also provide facility to compile and link to create
object file and executable file. Turbo is one of the IDE for executing C Programs.
Compile: It is a process of compiling your source code and producing object code
Debug: It is an activity to remove errors in your source code. Errors are called bugs.
Error: Errors are categorized as syntax error (compile time error), Linker error, Run time error,
Logical error. These are mistakes in your program which needs to be handled
Run: When you run your program it means execution of your program.
The files conio.h and stdio.h are known as header files, they contains declaration of
predefined functions and declarations for other identifiers. The conio.h file contains
declaration for the functions clrscr() and getch(). Similarly, stdio.h contains
declarations for printf() and scanf().
We will more enlighten header files later in chapter covering functions.
2) C language is a block structured programming language. Pair of curly braces forms a
block “{ }”.
In the above program we use a block containing all the instructions. This block is
identified by a name main(). Execution always begin with main() function. The
prefix of main() is void, which says it returns no value. We enlighten this thing later
in functions chapter.
3) The line int a, b, c; declares variables which will be used to hold data.
clrscr() is a function used to clear the content of the output screen.
The next line is used to print a message on the screen to provide direction to the user.
This is done with the help of a function printf().
The function scanf() is used to take input from keyboard. Input data is then stored in
the variables a and b which is declared previously.
Next instruction is arithmetic instruction used to calculate sum of values stored in a
and b, and result is then assigned to variable c. The expression is same as we do
calculation in mathematics.
Again function printf() is used to show the result to end user in an output screen.
Last line is the call to function getch(). The job of this function is to get a character
from keyboard. This function call is required to hold the output screen, as if all the
lines gets over output screen disappears immediately.
1.15 Execution of C Program
C Program executes in following four steps:
1) Creating a Program:
Developers will a create a C program with “.c” extension. The file contains source
code.
2) Compiling a Program:
Program need to be compiled to get an object file which is containing the translated
form of your C program. Compiler translated source code into the operating system
understandable format. This is the job of compiler to compile program and converts it
into object code(binary code)
3) Linking a Program:
Object file is then needed to be linked with library files needed for the execution of a
program to get an executable file. The linker is used to link program with the libraries.
4) Executing a Program:
Now you can execute your software i.e. an exe file. One cannot see source code by
just executing executable file.
Check Yourself:
Objective Questions:
1) In the context of C Programming language, what is the extension of source file?
a. C b. CPP
c. EXE d. OBJ
2) In the context of C Programming language, what is the extension of executable file?
a. C b. CPP
c. EXE d. OBJ
3) Who developed the C programming language?
a. Ken Thompson b. Dennis Ritchie
c. Martin Richards d. Bjarne Stroustrup
4) Which of the following is an operating system?
a. RAM b. ALU
c. Windows 7 d. MS Office
2.2 Constituents of C
2.3 Identifiers
2.4 Constant
2.5 Variable
2.6 Keywords
For example alphabets are basic constituents of English language then learn to combine these
alphabets into words which in turn to sentences and then paragraph.
In a similar fashion we have to learn basic constituents of C language. The basic constituents
are alphabets, digits, special symbol which will combine called basic letters.
Alphabets A to Za to z
Digits 0 to 9
Special Symbol ~ ‘ ! @ # % ^ & * ( ) _ - + = | \ { } [ ] : ; “ ‘ <> , . ? /
2.3 Identifiers
Combination of basic letters forms Identifiers. Identifiers are smallest unit in the program that
has some meaning. We know that compiler will be reading our source code to translate it in
object code. So compiler should know about all the words of our program. Few words are
predefined to compiler and rest need to be declared by the programmer. These words are
identifiers as they can be identified by compiler.
Identifier includes constants, variables, keywords, macros, functions etc.
Here we are going to understand three of these; they are constants, variables and keywords.
2.4 Constant
Software is developed to handle information. This information is called constant. Sometimes
it is termed as data. Value of constant does not change.
1. Integer Constant:
All numbers either positive or negative without decimal point are Integer Constant
For example: 35, -20, 0, 123 are valid Integer constant.
2. Real Constant:
All numbers either positive or negative with decimal point involved in it are real
constant.
For example: 3.14, -43.56, 3.0 are valid Real constant.
3. Character Constant:
All character symbols are character constants if they are enclosed in single quotes and
of unit length.
For example: ‘A’, ‘b’, ‘+’, ‘3’, ‘ ‘
2.4.2 Secondary Constants:
Secondary constants are also known as derived constants, as they are derived from primary
constants.
Arrays, strings, pointers, structures, union, enumerators are secondary constants.
We will see them in great detail in later chapters.
2.5 Variables
Variables are the name of memory locations where we store our data. When C program is
under execution, operating system allocates memory to store instructions of the program and
also allocates space to store data.
Programmer has to decide how much space he is required with to store data. He also specifies
the names of memory locations in his program code. These names are called variables. These
locations can contain integer, real and character constants.
We can change its value according to programming requirement.
These keywords cannot be used as variable or function names as they already have some meaning
known to compiler.
A program is a set of instructions. Instructions are also known as commands or statements. They are
the sentences in program. Just like any other language, C also provides variety of instructions.
Arithmetic instruction
Control instruction
From the list of keywords few are designed to use in declaration instruction. They are required to
declare variables and functions. These keywords are
Here we are only concern with variable declaration. Declaration of functions will be deal in later
chapter.
int x=5, y;
float k=2.34;
These are examples of data type declaration instruction. Compiler when read these instructions, it
would get aware of four things:
Size of int type block is 2 bytes, size of float block is 4 bytes, size of char block is 1 byte, size of
double block is 8 bytes
3) Type of content
int variable can contain integer constant, float and double variable can contain real constant and
char variable can contain character constant.
4) Value in variable
Variables y and ch are not initialized but they are not empty. They contain unpredictable values
which are of no use in the program, so we call them garbage values.
Here is the list of all possible combination of use of modifiers with data type:
Create variables to store integers:
int, short int, signed int, long int, unsigned int, unsigned short int, unsigned long int.
Create variables to store real constant
float, double, long double
Create variables to store character constant
char, unsigned char
Modifiers affect size of data type (short and long), data range (signed and unsigned)
printf()
Syntax:
printf(“format string”, variable list);
Format string is a message that you want to print on the screen.
Variable list is optional. We can also write expression in place of variable list.
Example:
printf(“Saurabh Shukla”);
printf(“Hello SCA”);
Write your first program
main()
{
printf(“Hello SCA”);
}
Step 2: Compile it
Step 3: Run
Your program executes in a flash and you would not able to see its output.
Modified Program:
main()
{
printf(“Hello SCA”);
getch();
}
When your program runs, first instruction prints a message Hello SCA.
Second instruction is a call to a function getch() whose job is to take one character from
keyboard. Until you press any key this line wouldn’t finish its job. As call to getch() is the
last line of the program, termination of program depends on when you enter a character. This
let you see output window till you press any key.
You probably wonder why your older output is still on the screen every time you run your
program. This is due to your consecutive execution of program using same output window.
This problem can be solved by using clrscr() before printf().
Modified program:
main()
{
clrscr();
printf(“Hello SCA”);
getch();
}
Write a program to display values of two variables on the monitor. Declare these two
variables of any type and assigned some values to them.
main()
{
int a=3,b=56;
clrscr();
printf(“%d %d”,a,b);
getch();
}
Output:
3 56
In the above example printf is use to display contents of variables a and b. Notice that %d is
a special symbol called format specifier. They are used to specify format of data to be
printed. In the format string %d will be replaced by values of the variables.
Output: 3 56 59
Notice that printf contains three format specifiers (%d) as there are three expressions in the
variable list. First two are simply variables and third one is an expression which first solved
then the result gets printed in the place of third %d.
2.11 Escape Sequences
Escape sequences are special symbols prefixed with a back slash ( \ ). These symbols are
used in printf to provide a formatted output.
\f Form Feed Moves the cursor to the first position of the next page.
\n New Line Moves the cursor to the first position of the next line.
\r Carriage Return
Moves the cursor to the first position of the current line.
\t Horizontal Tab Moves the cursor to the next horizontal tabular position.
\v Vertical Tab Moves the cursor to the next vertical tabular position.
\’ Produces a single quote.
\” Produces a double quote.
\\ Produces a single backslash.
\0 Produces a null character.
\ddd Defines one character by the octal digits (base-8 number).
Multiple characters
may be defined in the same escape sequence, but the value is implementation-
specific.
\xdd Defines one character by the hexadecimal digit (base-16
number).
main()
{
int a=3,b=56;
clrscr();
printf(“%d\n%d”,a,b);
getch();
}
Output
3
56
Here output comes in two lines. Notice \n in the printf , first value (3) gets printed then \n
moves cursor to the next line and then 56 gets printed.
Use list of different escape sequences in your program and observe the effect.
2.12 Input Instruction
Default input device is keyboard. Input instruction makes possible to input data from
keyboard.
scanf()
scanf() is a predefined function. It is used to input data from keyboard and stores in variables
of the program.
Syntax:
scanf(“format specifier”, address of variable);
Example:
main()
{
int a;
scanf(“%d”,&a);
}
In this program, we have declared a variable a of type int. scanf makes possible one integer
value through keyboard. scanf receives this value and stores it in variable a.
Here it is important to notice address of operator (&) before variable a. don’t forget to put this
operator before variable name. We will understand this operator in great detail in later
chapter.
Multiple input:
main()
{
int a;
float y;
scanf(“%d%f”,&a,&y);
}
For float variable format specifier should be %f. Here we can input two values, first an
integer and second one is float.
Write a program to add two numbers.
main()
{
int a,b,c;
clrscr();
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum is %d”,c);
getch();
}
Output
Enter two numbers5
6
Sum is 11
Now you can use scanf for user input. We will again study scanf in great detail during
functions in later chapter.
Check Yourself
Objective Questions:
1) Which of the following is an integer constant?
a. -3.4 b. ‘a’
c. ‘5’ d. 34
2) Which of the following is a character constant?
a. -44 b. 2.1
c. ‘3’ d. “a”
3) Which of the following is a secondary constant?
a. Integer b. String
c. Character d. Real
4) Which is a valid variable name?
a. A-1 b. 2d
c. S.i d. B_2
5) Which of the following is not a keyword in C language?
a. static b. double
c. this d. void
6) Which of the following is a keyword in C language?
a. class b. new
c. extern d. public
7) What is the full form of ANSI?
a. American National Standards Institute
b. American National Statistical Institute
c. American Numbering Standards Institute
d. American Native Standard Institute
8) Which of the following is a real constant?
a. “3.4” b. -3.0
c. ‘4’ d. None of the Above
9) Which of the following is correct statement?
a. A valid variable name can start with a digit
b. Keywords are words that should be declared by programmer
c. Identifier is the smallest unit of the program
d. C is a case insensitive language
0) Which of the following keyword is not a data type?
a. void b. static
c. double d. char
11) float variable consumes __________ bits in memory
a. 16 b. 4
c. 32 d. 8
12) Which of the following is incorrect statement?
a. A variable name can be a combination of alphabet, digit and underscore
b. Keyword char can also be written in upper case (CHAR), without losing its
meaning
c. Every statement in C language is terminated by semicolon
d. A program is a set of instruction
Write following programs:
1) Write a program to print your name on the first line and surname on the second line of
console window.
2) Write a program to print your name on the screen, as soon as a key is pressed name
should disappear from the screen, again on pressing any key, surname gets printed.
3) Write a program to input a character from keyboard and display its ASCII code.
4) Write a program calculate simple interest. Data should be supplied by user through
keyboard.
5) Write a program to calculate area of circle.
6) Write a program to input three data, each of type int, char and float. Also display
them.
7) Write a program to calculate average of three numbers. Numbers are taken from
keyboard.
8) Write a program to calculate volume of a cuboid. Data should be taken from keyboard
Content
3.1 Arithmetic Instruction
To understand operators in a better way we put them in 8 groups. This also helps you in
learningprecedence rule of operators. Each group contains operators of same nature. So it
would be better if you learn the group names in the same order as listed below.
⚫ Unary Operators
⚫ Arithmetic Operators
⚫ Bitwise Operators
⚫ Relational Operators
⚫ Logical Operators
⚫ Conditional Operators
⚫ Assignment Operators
⚫ Miscellaneous Operators
3.2 Unary Operators (+, -, ++, —, sizeof() )
Operators required operands to perform its operation. Unary operators are those who required
with only single operand to perform its task.
Unary + and –
These operators are not addition and subtraction, rather they are unary + and – that shows
direction of data. For example -3, +4, -345 etc
Increment Operator ++
Increment operator (++) increase value of variable by one. Let us assume we have an int
variable x containing 4.
int x=4; //declaration of variable x and assign 4 to it.
x++; //Value of variable x is incremented by one and become 5
++x; // Value of variable x is incremented by one and become 6
Here notice that we have two conventions to use increment operator. You can put operator
before operand or after operand. If it is after operand known as post increment, otherwise
known as pre increment. Both these convention have same effect over operand x as they
increase its value by 1. But these two conventions differ in priority rule. Pre increment has
the highest priority among all the operators. Post increment has the lowest priority among all
the operators.
sizeof() operator
sizeof() operator is used to know size of data type, variable or constant.
Example :
main()
{
int x,y;
float k;
char ch;
double d;
x=sizeof(float); // sizeof returns 4 and assigned to x
x=sizeof(char); // sizeof returns 1 and assigned to x
x=sizeof(int); // sizeof returns 2 and assigned to x
x=sizeof(double); // sizeof returns 8 and assigned to x
x=sizeof(d); // sizeof returns 8 and assigned to x
x=sizeof(k); // sizeof returns 4 and assigned to x
x=sizeof(ch); // sizeof returns 1 and assigned to x
x=sizeof(y); // sizeof returns 2 and assigned to x
x=sizeof(45); // sizeof returns 2 and assigned to x
Always remember that the size of real constant is 8 bytes and character constant is 2 bytes.
Character constants are internally treated as integers. Each character constant has a unique
integer code called ASCII code. ASCII stands for American Standard Code for
Information Interchange.
Associativity rule for unary operators is right to left. Which means when more than two unary
operators of same priority appears in a single arithmetic expression, they will be solved from
right to left.
Divide operator ( / )
main()
{
int x;
x=5/2;
printf(“%d”,x);
}
Output:
2
Compiler understands numbers in two categories one is integer and second is real. We have
used both the operands integer in above program. When two integers operate, result is always
an integer. So 5/2 yield 2 and not 2.5
To get result 2.5 we need to make at least one of the operand real.
main()
{
int x;
x=5/2.0;
printf(“%d”,x);
}
Output:
2
Here we made one operand real but still result is 2. It happens because variable x is of type
int and could not hold real constant. So choose float variable.
main()
{
float x;
x=5/2.0;
printf(“%d”,x);
}
Output:
2
Oh man! Again the output is 2. Although we made one of the operand real and variable is
also of type float, but notice the format specifier used in printf to display content of x, which
is wrong. You have to use %f for float variable.
main()
{
float x;
x=5/2.0;
printf(“%f”,x);
}
Output:
2.500000
Modulo operator gives remainder in result. It cannot work for real constants.
main()
{
int x;
x=5%2;
printf(“%d”,x);
}
Output is:
1
When 5 is divided by 2 remainder comes 1.
Note: Modulo operator is good to check divisibility of a number. When remainder is 0,
number is divisible.
Nature of operators
Bitwise OR ( | )
0|0 is 0
0|1 is 1
1|0 is 1
1|1 is 1
main()
{
int x;
x=5&12;
printf(“%d”,x);
}
Output is:
4
Shift Operators
Right shift >>
Left shift <<
main()
{
int x;
x=12>>2;
printf(“%d”,x);
}
Output:
3
Convert 12 into binary and shift bits to their right 2 times. This makes last two bits out and
two new bits (always 0) append at the left.
12=00000000 00001100
Right shift two times
3 =00000000 00000011
main()
{
int x;
x=12<<2;
printf(“%d”,x);
}
Output :
48
Convert 12 into binary and shift bits to their left 2 times. This makes last two left most bits
out and two new bits (always 0) append at the right.
12=00000000 00001100
Left shift two times
48=00000000 00110000
Output is:
0
As the relation 5<3 is false, x will contain 0 as a result of relational operator.
C1 && C2 Result
T && T T
T && F F
F && X F
C1 || C2 Result
F || F F
F || T T
T || X T
Example:
main()
{
int x;
x= 5>3&&4<0;
printf(“%d”,x);
}
Output is:
0
Here, two conditions 5>3 and 4<0 are combined to form a single condition using && operator as
5>3&&4<0. Condition one is evaluated as TRUE as 5 is greater than 3. Since condition one is TRUE
condition two is tested and evaluated as FALSE as 4 is not less than 0. According to the above chart,
T&&F is treated as FALSE thus 0 is stored in x.
Logical NOT ( ! )
! operator is used to invert the truth value.
main()
{
int x;
x=!(5>4);
printf(“%d”,x);
}
Output is:
0
5>4 is evaluated as TRUE, NOT (!) operator invert this result and make it FALSE.
Thus 0 is stored in x.
3.7 Conditional Operator ( ? : )
Conditional operator is also known as ternary operator. We will discuss it in our next chapter control
instructions.
main()
{
int x;
x=4;
}
main()
{
int x=5;
x+=4; //same as x=x+4
}
Here, += is also an assignment operator, but used to store data after small manipulation. First 4 is
added to the content of x and then assigned to x.
The same operation can be performed using = and + operator as x=x+4, but this expression contains
two operators which requires precedence rule during evaluation.
Although, generated results are same that is x is containing 9.
main()
{
int x=3, y=3;
x*=4+3;
y=y*4+3;
}
Now you can understand difference between the two expressions. First x*=4+3, + is operated first as
it has higher priority than *=. So 4+3 becomes 7. x is then multiply to 7 to give result 21. This 21 is
getting stored in x.
Second expression y=y*4+3 which is thought as the substitute of first expression but it does not work
in similar fashion. * has the highest priority then + and then = comes at the last. Content of y is
multiplied by 4 which give 12. 12 is added to 3 which becomes 15 and get stored in y.
Content:
4.1 Control Instruction
4.2 Decision Control Instruction
4.3 If
4.4 if-else
4.5 Conditional operator
if is a keyword which let compiler to identify decision control instruction. Immediately after if some
condition is there. This condition is any valid expression in C. If the result of expression is non-zero it
is considered as TRUE otherwise FALSE.
Immediately after this condition there is a block of code. Since this block is immediately after if, it is
known as if block. Whatever we write in if block will be execute only when condition is TRUE.
When condition is false control skip if block and execute statements written after if block.
Example:
main()
{
int marks;
printf(“Enter marks “);
scanf(“%d”,&marks);
if(marks>=33)
{
printf(“You are PASS”);
}
if(marks<33)
{
printf(“You are FAIL”);
}
}
Sample Output:
Enter marks 45
You are PASS
Sample Output:
Enter marks 23
You are FAIL
In this program output depends on the value given by user. Variable marks hold the value entered by
user. We have used two if statements. In the first if statement we use the condition marks>=33, thus if
the marks are greater than or equal to 33 condition becomes TRUE, so if block executed, otherwise if
block is skipped.
Whatever may the result of first if condition, control has to reach second if statement.
If marks are less than 33 condition will be TRUE and execute if block otherwise if block is skipped.
4.4 if-else
Syntax
main()
{
..…
…..
if(some condition)
{
Statement1;
Statement2;
….
}
else
{
Statement1;
Statement2;
….
}
…
}
This is similar to if but the else block is new add on. If the condition of if is TRUE if block will be
executed and if the condition of if is FALSE else block will be executed.
It is important to mention that only one from the two blocks (if block and else block) can be executed
as the condition may have only two results, TRUE or FALSE
You can use if statement without else block but else must have paired with if.
Else block should appear immediately after if block otherwise an error occurred during compilation.
Example:
main()
{
int marks;
printf(“Enter marks “);
scanf(“%d”,&marks);
if(marks>=33)
{
printf(“You are PASS”);
}
else
{
printf(“You are FAIL”);
}
}
The same program was discussed using only if statements. This one is refined version of program and
hence better than that of the previous one.
Notice that, there is only one condition need to be evaluated, if the condition is TRUE if block will
work otherwise else block will be executed.
Note: If there is only one statement in if block then mentioning block using curly braces is optional.
Same rule is applied to else block.
4.5 Conditional operator ( ? :)
It is also known as ternary operator which means operator need three operands to perform its
operation.
Syntax:
Expression1 ? expression2 : expression3;
Expression 1 is a condition, which is first evaluated as TRUE or FALSE. If the condition is TRUE
executes expression2 otherwise execute expression3.
Conditional operator works similar to if-else, but we do not have to use keyword if and else.
Example:
main()
{
int x,y;
printf(“Enter two numbers”);
scanf(“%d%d”,&x,&y);
x>y ? printf(“%d is greater”,x) : printf(“%d is greater”,y);
}
Output:
Enter two numbers45
33
45 is greater
In this program user enters two numbers which is then get stored in x and y. Notice the last line of the
program that is conditional operator, which is used to select one from the two printf() statements. If
x>y then value of x get printed otherwise value of y is printed.
main()
{
int x,y,max;
printf(“Enter two numbers”);
scanf(“%d%d”,&x,&y);
max=x>y ? x : y;
printf(“Greater number is %d”,max);
}
Output is:
Enter two numbers85
100
Greater number is 100
In this program conditional operator is used to select one from x and y to assign value of either x or y
in variable max.
4.6 Nested if-else
When if-else statements written in if block or else block, it is called nested if-else.
Example:
In the above program if a is greater than b then if-block is executed otherwise else block is executed.
Notice that another if-else reside inside if-block and else-block. This sort of structure is known as
nested if-else.
4.7 else if ladder
Syntax:
if()
{
—————
————
}
else if( )
{
—————
————
}
else if( )
{
—————
————
}
else
{
—————
————
}
Example:
main()
{
int year;
printf(“Enter a year”);
scanf(“%d”,&year);
if(year%4!=0)
printf(“Not a Leap year”);
else if(year%100!=0)
printf(“Leap year”);
else if(year%400!=0)
printf(“Not a Leap Year”);
else
printf(“Leap Year”);
}
The above program is to check whether a year is leap year or not. You can analyze how we used if-
else ladder in the above program
Check Yourself:
Objective Questions:
1) What is the output of the following code?
main()
{
if(3>4)
printf(“3”);
printf(“4”);
else
printf(“7”);
}
a. 7 b. 34
c. 347 d. Error
2) What is the output of the following program?
main()
{
int x=0, y= -1;
if(x++&&++y)
printf(“%d %d”,x,y);
else
printf(“%d %d”,y,x);
}
a. 0 -1 b. 1 -1
c. 1 0 d. -1 1
3) Find the output of the following program
main()
{
int x=0, y= -1;
if(++x&&++y)
printf(“%d %d”,x,y);
else
printf(“%d %d”,y,x);
}
a. 1 0 b. 01
c. 1 -1 d. -1 1
4) Find the output of the following program
main()
{
float a=0.7;
if(a<0.7)
printf(“Dennis”);
else
printf(“Ritchie”);
}
a. Error b. Dennis
c. Ritchie d. Dennis Ritchie
5) Find the output of the following program
main()
{
int x=5;
if( x=4)
printf(“%d”, x+1);
else
printf(“%d”, x-1);
}
a. 6 b. 4
c. 5 d. 3
6) Find the output of the following program
main()
{
int x=3,y=5;
if( x++ || ++y)
printf(“%d %d”, ++x, x++);
printf(“ %d %d”, ++y, y=++x);
}
a. 6 4 8 7 b. 5567
c. 5 6 7 7 d. 5678
7) Find the output of the following program
main()
{
int x = 0, y = -1;
if(x++ || y++ && ++x)
printf(“%d %d”, x, y);
else
printf(“%d %d”, y, x);
}
a. 2 0 b. 02
c. 1 -1 d. -1 1
8) Find the output of the following program
main()
{
int x = 1,y = 2,z=0;
if(x!=y>z) printf(“1”);
else printf(“0”);
}
a. Error b. 0
c. 1 d. 10
9) Find the output of the following program
main()
{
int a=210,b=120;
if(a>b) printf(“%d”,a=a-b);
if(b>a) printf(“%d”,b=b-a);
if(a>b) printf(“%d”,a=a-b);
if(b>a) printf(“%d”,b=b-a);
}
a. 903060-30 b. 903060
c. 906030-30 d. 906030
Content
5.1 Iterative Control Instruction
5.2 While
5.3 Do-while
5.4 For
5.5 Nested loop
5.6 The keyword break
Example:
main()
{
int i=1;
….
while(i<=5)
{
printf(“SCA “);
i++;
}
printf(“Out of loop”);
}
Output:
SCA SCA SCA SCA SCA Out of loop
In this example, printf inside while loop is executed 5 times. You have to think about three
things to control loop execution. They are initialization, termination condition and flow.
Here, i is used to control loop. In the very first line of the main function i is initialized by 1.
So when the condition is evaluated first time it is interpreted as 1<=5, thus it is TRUE.
Control enters in while block and execute printf statement. After printf i is incremented by 1.
This is important as we want to execute loop body only five times. Initially i was 1 and in
each iteration it is incremented by 1, this makes i to reach a value where condition i<=5
becomes FALSE. If no termination condition is defined under while loop you get trapped in
an infinite loop.
main()
{
….
….
do
{
….
….
} while(condition);
…
}
Learn a new keyword do. The code block that has to put in loop is prefixed with keyword do
and post-fixed with keyword while along with termination condition. Remember to put
semicolon after while.
do-while works similar to while but the only difference is earlier is executed at least once.
Since in while loop condition is evaluated first then goes into loop body, on the other hand in
do while loop first control enters in loop body then condition will be checked. This makes
possible to control enters in loop body even though the condition is false. Although once the
condition is checked FALSE loop is terminated.
Example:
main()
{
int i=5;
do
{
printf(“SCA”);
}while(i>6);
getch()
}
Output:
SCA
When we execute the above program SCA is printed in output screen once as the printf
statement will get executed one time and then the condition will be check which will return
FALSE as 5 is not greater than 6. If the above program is written by using while loop at the
very first time condition will return FALSE and SCA will not get printed in output screen. do
while loop is used in case where we want to execute the condition at least one time.
5.4 for loop:
Syntax of for
main()
{
….
for( ; ;)
{
…
}
…
}
for loop is programmers choice as it contains initialization, termination and flow at same
place. Notice the two semicolons inside for’s round braces, these are part of syntax, hence
should always be mentioned.
Two semicolons create three sections. First section is used for initialization, second section is
used for termination condition and third section is used to mention flow.
First the variable gets initialized, and then the condition is getting checked. If the condition
returns TRUE the statements (body of the loop) get executed and then increment the value of
the variable. Again the control transfer to check the condition. If the condition returns FALSE
no statement will get executed inside the for body and transfer the control to the first
statement outside the loop.
Example:
main()
{
int i;
for(i=1;i<=5;i++)
{
printf(“\n Number = %d”, i); // Statement 1
}
getch();
}
Output:
Number = 1
Number = 2
Number = 3
Number = 4
Number = 5
In the above program control of for loop starts with the initialization of i as 1 and then the
condition get checked which returns TRUE as 1<=5. Statement 1 will print the number as 1.
Now increment statement will get executed, i will get incremented to 2 and again the
condition will check. This happens 5 times until value of i remain as 5. As soon as the value
of i becomes 6 condition get checked and return FALSE and control transfers out of the for
loop.
Output
Enter a number 4
Factorial is 24
User enters a number which is stored in n. This loop executes n times as it goes from 1 to n.
Let us suppose value entered by user is 4. So n contains 4. Loop start with initialization of i
from 1. After initialization, termination condition is evaluated, which is TRUE, thus control
moves inside the code block. Initially f is containing 1 and it is multiplied by i which also
contains 1. The product is finally stored in f. Now control moves to the flow part (i++).
Condition is evaluated again but this time i become 2. Condition is again TRUE. Control
again enters in code block and the product of f and i will store in f.
Same process is repeated till the condition i<=n becomes FALSE.
5.5 Nested Loop
Using loop inside the body of loop is known as nesting of loops. Sometimes it is desirable to
repeat the repetitions.
Example: Write a program to print 5 lines with each containing 10 asterisk (*) symbols.
main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1;j<=10;j++)
printf(“*”);
printf(“\n”);
}
getch();
}
In the above program, we have two action statements in the outer loop. First is a for loop and
second is a printf() function responsible to move cursor on the next line. These two
statements will execute for 5 times. So the inner loop will work out for five times, which
means printf(“*”) encounters 50 times.
5.6 The Keyword break
The keyword break is used only in:
⚫ Loop body
⚫ Switch body
int x,i=1;
while(i<=5)
scanf(“%d”,&x);
if(x%2==0)
printf(“You Win”);
break;
i++;
if(i==6)
printf(“You lost”);
In this program, break is used to terminate loop when user enters an even number. This
program is a sort of game where user has at most 5 chances to enter correct value. If he is fail
to enter correct value in all five chances he would lost the game. He may win the game if he
enters correct value in any of the five chances. Game must stop as soon as he enters the
correct data.
Let us assume first time user enters 3. Since x contains 3, condition x%2==0 is FALSE so
skipped if block and increments i by 1. On its second iteration, assume user enters 6. This
time condition x%2==0 is TRUE, so enters in if block. User gets a message “You Win”. Now
break works and it transfers the control out of while block. Where another condition is
evaluated, which is false.
Try executing above program for different inputs.
5.7 The Keyword continue
The keyword continue is used only in loop body. It is used to move control at termination
condition in the case of while and do-while loop. continue is used in for loop to transfer
control at flow part (increment/decrement).
Example
main()
{
int x;
while(1)
{
printf(“Enter an even number”);
scanf(“%d”,&x);
if(x%2==1)
continue;
else
{
printf(“This is the correct value”);
break;
}
}
}
This time condition of while loop is always TRUE as we wrote 1 which is a non zero number.
(Non zero number is always treated as TRUE). The loop only ends at the execution of break.
If the user enters an odd number condition x%2==1 becomes TRUE, thus continue works.
Continue transfers the control at while loop condition.
As long as user enters odd number, continue works every time, but when user enters an even
number, break terminates loop.
They are good enough to select one from the two available options. When choices are two,
we can use if-else. Even if we have multiple choices we can use multiple if-else, sometimes
we use if-else ladder or nested if-else. You probably experienced that as the number of
available options/choices are large, if-else becomes complex.
So when we have many choices, we can use switch case control in place of if-else.
In this section we are going to use three keywords switch, case and default
Syntax of switch case
main()
{
….
….
switch( expression)
{
case constant1 :
….
case constant2 :
….
case constant3 :
….
…
default:
……
}
…..
}
Switch case control is used when user have multiple choices. Switch transfers the control to a
case written in its body depending on the value evaluated by expression in switch parenthesis.
In switch body each case is post fixed by a constant. This constant could be integer or
character but not real. It is also worth mentioning here that the constant in each case must be
distinct.
When value of expression does not match with any case constant then control moves on
default segment.
Another important point to notice that once control moves from switch to appropriate case, it
not just execute statement written in that case but also execute all the statements written in
following cases including default, but not cases written above. If you are concern with only
one case execution, use break keyword as the last statement of every case
5.9 Menu driven Programming
Switch case control is very useful in menu driven program. The following example illustrates
menu driven program. It is also use break to terminate switch
main()
{
int a, b, result, ch;
Example
main()
{
int cm;
printf(“Enter length in centimeters”);
scanf(“%d”,&cm);
if(cm<100)
goto label;
cm=cm%100;
printf(Wrong input is trimed”);
label:
printf(“cm=%d”, cm);
}
Explanation:
1) goto is a keyword that moves control to a location in the program mentioned by
location name ‘label’.
2) If value of cm is more than or equal to 100, it should be trimmed. For example if user
enters 435, it becomes 35, 4 should be trimmed out.
3) Try executing this program for different inputs.
Check Yourself:
Objective Questions
Content
6.1 Functions
6.2 Modularization
6.6 Recursion
6.1 Functions
Functions in C language are small blocks of code, design to achieve a particular task.
The main program need of such task arises. So by dividing a large programme into multiple
functions we get following advantages as follows
1. The redundancy of statements can be reduced since instead of repeating the same set of
lines again and again, we can write down the same code in a single line of statement.
2. The debugging of program becomes easier if it is divided into multiple function. This is
because we do not find errors into the entire code rather we just have to look for them in a
smalll portion of our program i.e. inside the function body. Moreover any correction done
inside the function are automatically reflected at every place where the function has been
called.
3. We can also create our own header files containing our own functions which we can use in
any program as and when needed by including the header file .
6.2 Modularization
Modular programming is a software design technique that increases the extent to which
software is composed of separate, interchangeable components, called modules by breaking
down program functions into modules, each of which accomplishes one function and contains
everything necessary to accomplish this
Suppose a C program is designed to perform a task. And say this task can be divided into few
subtasks, each of which is independent functionality. Each subtask can be coded in a separate
block known as function.
Program Execution always starts from main(). main can then call other function. Any
function can call other function. This call is an invitation to that function to perform its
subtask.
6.3 Technical terms
⚫ Calling Function: Function who call another function
⚫ Called Function : Function who is called by another function
⚫ Function call: Action of calling a function
You have been using few functions from the starting of programming. For example printf(),
scanf(), clrscr() and getch(). These are all functions and you often call them to perform task
for which they are designed.
There are many more such functions. They are called predefined functions. There code is kept in
library files. These files are comprehensively called built-in C library
6.4 Function Types
A) Predefined Functions OR Library Functions: These are the functions which are pre
defined in library file. We do not need to create them. We can simply use them by including
corresponding header file in our program.
B)User Defined Functions: When user want to create a function which is not available in the
library of C. These functions are known as User defined functions.
2.Function call
3. Function Definition or function body
Difference between header file and Library file
Header Files Library Files
It contains declaration of pre defined It contains function definition
functions
They have .h file extensions These have .lib extensions
Header files are located Inside sub directory These are located inside Lib folder
Include
Header files are included in our programme It is the linker which links the library files
by pre-processor(i.e. #) with our programme while execution
The pre-processor executes the statements All the functions we have called in our
and copies the entire coding inside header programme get linked with their actual
files. bodies by linker
These files are in human readable format These are in binary format
Note:
1. C doesn't support function overloading.
2. a function may accept none or multiple values but can return at most single value .
Types of Functions:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
printf("\n",i);
sleep(1)/*delay(1000) here delay and sleep pause execution for a while delay takes time in
milli seconds while sleeps takes in second*/
getch();
}
Using textcolor and cprintf
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
textcolor(YELLOW);
cprintf(" Sanjeev");
getch();
}
#include<stdio.h>
#include<conio.h>
void sum(int,int) /*int,int are signature in prototype declaration*/
/*void is special data tpye used when function take nothing to return nothing*/
void main()
{
int n, x,y;
clrscr();
printf("enter two integers");
scanf("%d %d",&x,&y);
n=sum(x,y) /*x,y are actual parameters* and this is function called/
printf("sum of x and y is=%d",n)
getch();
}
/*function definition*/
void sum(int p,int q)//P and Q are formal parameters
{
printf("Sum is=%d",p+q);
}
#include<stdio.h>
#include<conio.h>
int sum(void) /*int,int are signature in prototype declaration*/
/*void is special data tpye used when function take nothing to return nothing*/
void main()
{
int n;
clrscr();
n=sum() /*x,y are actual parameters* and this is function called/
printf("sum of x and y is=%d",n)
getch();
}
/*function definition*/
void sum(int p,int q)//P and Q are formal parameters
{
int x,y;
printf("enter two integers");
scanf("%d %d",&x,&y);
return(p+q);
}
#include<stdio.h>
#include<conio.h>
void sum(void) /*int,int are signature in prototype declaration*/
/*void is special data tpye used when function take nothing to return nothing*/
void main()
{
clrscr()
getch();
}
/*function definition*/
void sum(void)//P and Q are formal parameters
{
int n, x,y;
clrscr();
printf("enter two integers");
scanf("%d %d",&x,&y);
printf("Sum is=%d",x+y);
}
10 Basic Questions
1) Can we call a function several times in a single program?
Ans: Yes.
2) Can user define function become a calling function?
Ans: Yes.
3) Can we pass values through functions?
Ans: Yes, it is called “Call by value”.
4) Can we have a c program without main function.
Ans: No
5) Is there any limit of total number of functions that can ‘c’ programs have?
Ans: No
6) Can two functions have same name with different definitions?
Ans: No
7) Who calls main?
Ans: An operating system.
8) Can a function call main() ?
Ans: Yes
9) Can a function call itself ?
Ans: Yes, it is called recursion.
10) Why write separate functions at all? Why not squeeze the entire logic into one function
main()?
Ans:
1. Writing functions avoids rewriting the same code over and over.
2. It provides strong readability.
3. It makes program easy to debug.
4. It becomes easy to modify.
5. Better memory utilization
Explanation:
In this program we wrote two functions, one is sum() and second is main().
It is not necessary to define sum() before main(). There would be no difference in, what order
of function definition is positioned in your program. This is completely a programmer choice.
Whatever may the order of function definition, program execution always starts from main().
Notice the first line of main() function (void sum(void);). This is called declaration of
function. Declaration of function tells the compiler about return type, function name and
argument type. Since we are not returning any value we mentioned so by void. Function
name is sum. Since there is no argument we mentioned it so by using keyword void in the
parenthesis. We will discuss more about function declaration later in this chapter.
Second line in the main function is a call to a predefined function clrscr(). Since clrscr()
function defined in such a way that it takes nothing, we left its parenthesis empty.
Next line is a call to a function sum(). This function takes nothing, so the parenthesis is
empty. Due to call to function sum(), control moves to the definition of function sum(). In
sum(), three int type variables are declared. After call to printf() and scanf(), c is assigned a
value which is an addition of value stored in a and b. Lastly the call to printf() displays the
result.
When all the statements of function sum() worked out, control returns back from where sum()
was called. Hence control comes back to main() and the last function getch() execute.
2) Takes something returns nothing
main()
{
void sum(int, int);
int a,b;
clrscr();
printf(“Enter two numbers:-”);
scanf(“%d%d”,&a,&b);
sum(a, b);
getch();
}
void sum(int x, int y)
{
int c;
c=x+y;
printf(“Sum is %d”,c);
}
Explanation:This time we passed two int type values during call to function sum(a,b). these
values arecalled actual arguments or parameters. Notice the subsequent change in function
declaration and definition. Values of a and b are collected in x and y. Variable x and y are
called formal arguments.
It is important to note that any function can access only those variables that are declared in
their body. So the scope of variable is limited to the function in which it is declared.
3) Takes nothing returns something
main()
{
int sum(void);
int s;
clrscr();
s=sum();
printf(“Sum is %d”,s);
getch();
}
int sum()
{
int a,b,c;
printf(“Enter two numbers:-”);
scanf(“%d%d”,&a,&b);
c=a+b;
return(c)}
Explanation:In this example we do not pass anything but function sum returns an int type
value, which is addition of two numbers. Notice the change in return type in function
declaration and definition part. Also notice how we collect the return value in function main.
Whatever sum() returns, it goes back at the same place from where a function is called. It is
then assigned to s.
The keyword return is used to return value of any type. We can only return single value using
return.
As soon as return is executed control comes back to the calling function, thus it is
meaningless to expect any statement could execute after return in function sum().
4) Takes something returns something
main()
{
int sum(int,int);
int s;
clrscr();
printf(“Enter two numbers:-”);
scanf(“%d%d”,&a, &b);
s=sum(a,b);
printf(“Sum is %d”,s);
getch();
}
Explanation:This time function sum() is called by passing two int values and addition is
returned back to calling function.
Another example:
Program to calculate area of a circle.
float area(int);
main()
{
int r;
float a;
clrscr();
printf(“Enter radius of circle:-”);
scanf(“%d”,&r);
a=area(r);
printf(“Area of circle is %f “,a);
getch();
}
float area(int r)
{
float A;
A=3.14*r*r;
return(A);
}
Function prototype
Function prototype also known as function declaration. Although you have already seen how
functions has to be declared. Here we would like to throw some light on function declaration.
1) In C language, function declaration is recommended but not mandatory. Some of the
compiler allow programmer to use function without declaration, but we recommend to
declare all functions used in your program. It is so because subsequent languages
including C++ are very strict about function declaration.
2) Function prototype has general form:
Return type function name ( argument type);
3) All predefined functions are already declared and there declaration is kept in some
header file, all you need to include that header file. For example printf() and scanf()
functions are declared in stdio.h. Similarly, clrscr() and getch() are declared in conio.h
Few Points to be noted regarding function:
Consider below sample program:
void main()
{
int add(int,int);
int a, b, c;
clrscr();
a=10;b=20;
c=add(a,b);
printf(“\n Addition of %d and %d results in %d”,a,b,c);
}
int add(int x, int y)
{
int z;
z=x+y;
return(z);
}
6.6 Recursion
Function calling itself is called recursion.
Example:
int fun(int );
void main()
{
int x, k=3;
x = fun (k);
printf(“%d”, x);
}
int fun ( int a)
{
int f;
if (a == 1) return(1);
f = 2 + fun (a – 1);
return(f);
}
Output:
5
Explanation:
Operating system calls main() function. Memory for x and k are being allotted. k is assigned
with 3. Now fun() is called by main() and passes value of k(called by value). Memory for the
function fun(3) is allotted, in which there are two variables f and a. a contains 3.
Now condition a==1 is false so control moves on f=2+fun(a-1). Here, again make a call to
function fun(). fun() is calling fun(), this is called recursion.
Remember this time a new and separate memory is being allotted, call it fun(2). It also uses
the same definition but its variable a contains 2. The condition a==1 is again false. And
again control moves to f=2+fun(a-1). Again function fun(1) is called from fun(2) and
recursion continues. Again separate memoryis allocated for fun(1). This time a would
contain 1 and the condition a==1 is true and return(1) to the calling function that is
fun(2). You can easily understand these successive returns to the calling functions.
For example
main()
{
int x;
…
}
Here we can easily understand that the variable name is ‘x’. Size it takes is two bytes. Type
of the content it can store is integer. So we can say data type declaration instruction provides
three basic properties of variable. One can learn these properties by just examine data type
declaration instruction.
Apart from these three properties of a variable, there are four more properties of a variable.
A variable in the program belongs to one of the four storage classes. These storage classes
talk about following four properties of a variable:
⚫ Storage
⚫ Default value
⚫ Scope
⚫ Life
Example
main()
{
auto int x = 2;
printf(“%d “, x);
{
auto int x = 5;
printf(“%d “, x);
}
printf(“%d “, x);
}
Output is 2 5 2
Some strange things, like declaration of x two times and declaration instruction after printf().
You remember the data type declaration instruction is possible only if it occur before any
other action statement. But this rule has a scope within the block. We are using two blocks.
Second declaration is the first statement in the inner block hence it is perfectly legal. Scope
and life of second x is limited to the block hence cannot be accessed outside.
6.9 Register Storage Class
⚫ Keyword used is register
⚫ Storage in register
⚫ Default value is garbage
⚫ Scope is limited to the block in which it is declared.
⚫ Life retains till the control moves in the block in which it is declared.
Register storage is a request only, allotment of register to the variable is depend on the
availability of register which is monitored by operating system. Sometimes we feel a
particular variable is used frequently, in such cases we do request to the operating system to
hold its data in the processor register so the program execution becomes faster.
6.10 Static Storage Class
⚫ Keyword used is static
⚫ Storage in main memory
⚫ Default value is 0 (zero).
⚫ Scope is limited to the block in which it is declared.
⚫ Life retains till the execution of program.
Example:
main()
inc( );
inc( );
inc( )
static int x;
Output:
12
Explanation: In this program, x is a static variable in function inc(). Static variables are
created only once in a program but its life time is whole program. Scope of static variable is
limited to the block in which it is declared, thus we cannot access variable ‘x’ from outside
the inc() function. Since the variable remains alive in memory in subsequent function call of
inc(), any change in variable ‘x’ is available for next call to function inc().
6.11 External Storage Class:
⚫ Keyword used is extern
⚫ Storage in main memory
⚫ Default value is 0 (zero).
⚫ Scope is global.
⚫ Life retains till the execution of program.
Example:
int x=5; //global variable
main()
printf(“%d”, x);
fun();
int fun()
{
printf(“%d”,x);
Output
55
External variables are declared outside all functions. They are also known as global variables.
All function in the program can access global variable. There will be a single copy of global
variable, shared between all functions.
If any function declared a local variable with the same name in its body, local variables get
preference over global variable.
The keyword extern should not be used during declaration of global variable. It should be
used to inform compiler if we are using any global variable in the block.
Let us take an example:
main()
{
printf(“%d”, x);
fun();
}
int x=5; //global variable
int fun()
{
printf(“%d”,x);
}
In the above code, global variable is declared after main function. Compiler will yield an
error message as undefined symbol x in main function. This happens due to early encounter
of action statement using variable x and the variable declaration is yet not visited. To
overcome this issue we must mention extern statement in main().
Here is the solution:
main()
{
extern int x;
printf(“%d”, x);
fun();
}
int x=5; //global variable
int fun()
{
printf(“%d”,x);
}
Check Yourself:
Objective Questions
1) What is the output of the following code?
#include<stdio.h>
int fun(int,int);
main()
{
int x=3,y=4;
fun(x,y);
printf(“%d %d”, x, y);
}
fun(int y, int x)
{
x=x+y; y=x-y; x=x-y;
}
a. 3 4 b. 43
c. Error d. 33
2) What is the output of the following program?
#include<stdio.h>
int fun(int,int);
main()
{
int x=3,y=4;
fun(x, y);
printf(“%d %d”, x, y);
}
fun(int y, int x)
{
x=x+y; y=x-y; x=x-y;
return(x,y);
}
a. 3 4 b. 43
c. Error d. 44
3) Find the output of the following program
#include<stdio.h>
int max(int,int);
int min(int,int);
main()
{
int k,x=3,y=4;
k=max(max(x,y),min(y,x));
printf(“%d”,k);
}
max(int x, int y) { return(x>y ? x: y); }
min(int x, int y) { return(x>y ? y: x); }
a. 3 b. 4
c. 5 d. 2
4) Find the output of the following program
#include<stdio.h>
int f1(int);
int f2(int);
main()
{
int k,x=3;
k=f1( f2( f1( f2(f1(x) ) ) ) );
printf(“%d”,k);
}
f1(int x) { return(++x); }
f2(int x) { return(x++); }
a. 4 b. 5
c. 6 d. 7
5) Find the output of the following program
#include<stdio.h>
int f1(int);
int f2(int);
main()
{
int k,x=3;
k=f1(x);
printf(“%d”,k);
}
f1(int x) { return(f2(++x)); }
f2(int x) { return(—x); }
}
a. 2 b. 3
c. 4 d. 5
6) Find the output of the following program
#include<stdio.h>
int f1(int);
int f2(int);
main()
{ int x=24,y=36;
printf(“%d”,abc(x,y));
}
abc(int a,int b)
{ if(a==b) return(a);
if(a>b) if(a%b==0) return(b);
else return(abc(a%b,b));
else if(b%a==0) return (a);
else return(abc(a,b%a));
}
a. 12 b. 18
c. 6 d. 4
7) Find the error in the following program
dummy(int a, int b)
{
int a;
a=20;
return a;
}
a. Missing parenthesis in return statement
b. Function return type should be mentioned
c. Re-declaration of variable a
d. None
8) Find the error in the following program
#include<stdio.h>
int fun(int);
int main()
{
int b;
b=fun(20);
printf(“%d”, b);
return(0);
}
int fun(int a)
{
a>20 ? return(10): return(20);
}
a. Error in prototype
b. No error
c. The return statement cannot be used with conditional operator
d. The function main cannot return any value
9) Find the output of the following program
#include<stdio.h>
void fun (void);
main()
{
fun();
fun();
fun();
}
void fun()
{
static int x;
x++;
printf(“%d”,x);
}
a. 123 b. 111
c. garbage d. Error
Content
7.1 Arrays
7.2 Array Declaration
7.3 Initializing Arrays
7.4 Memory allocation in an array
Introduction
Till now we have been designing solution to small problems that require less number of
variables to handle program data. Think about a scenario where you need to handle hundreds
of variables or even more than that. In such scenario, you might be thinking about what
variable names should be used, how to reduce redundant code, etc.
Assume you have to store marks of 100 students and then think about the following:
1) What could be your variable naming convention?
2) How you can efficiently write input instruction to store 100 data.
3) How could you easily manipulate data like adding all of them in a less complex style?
The answer to all these questions is subscript notation also known as Arrays.
7.1 Arrays
Array is a collection of similar elements. These similar elements could be all ints, floats,
doubles, chars, etc. Array is also known as subscript variable.
C programming language provides a data structure called the array, which can store a fixed-
size sequential collection of elements of the same type. Array elements are stored in
contiguous memory block.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Properties of Array:
1) Indexing of an array begins from zero (0).
2) The variable name of array contains the base address of the memory block.
3) The array variable are created at the time of compilation.
4) The size of the array cannot be altered at runtime.
7.2 Array Declaration
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows
<data type> arrayName [arraySize];
This is called single dimension Array.
[] is subscript operator and arraySize is the size of an array ie. how many elements are going
to be stored in an array.
• int a[5]={34,56};
Initializing an array with lesser values than its size is allowed and the remaining array blocks
will contains zero.
• int a[5]={34,56,78,99,12,44,66};
We cannot initialize an array with values exceeding its size.
• int a[ ]={34,56,78,99,12};
We can declare an array without mentioning its size only when initializing array during
declaration.
int a[5];
In the above declaration 5 is the size of an array or we can say an array is a collection of 5
variables.
Variables in an array do not have names. These variables can be recognized by their position
number in an array known as index. Index of the very first variable is 0 (zero). So the index
of last variable is 4 (according to our example). To assign value in any particular variable of
an array we have to follow the syntax:
a[index]=value;
For example:
a[0]=34;
a[1]=21;
It is worth mentioning here that the value written in square bracket is size of array during
declaration and it is index afterwards.
Example: Program to calculate average of 10 marks
#include<stdio.h>
#include<conio.h>
main()
{
int i, marks[10], sum=0;
float avg;
clrscr();
printf(“Enter 10 numbers”);
for(i=0;i<=9;i++)
scanf(“%d”,&marks[i]);
for(i=0;i<=9;i++)
sum=sum+marks[i];
avg=sum/10.0;
printf(“Average is %f”,avg);
getch();
}
Explanation:
1) Total numbers of variables in this program are 13. Their names are i, sum, avg,
marks[0], marks[1],…marks[9].
2) Notice the input statement, scanf() is repeated 10 times, this is possible as we can
access array index with the help of variable. Observe &marks[i] in scanf(), here i is
used for indexing. As the loop proceed value of i changes from 0 to 9. In this way wee
need not to write scanf() 10 times.
3) Data manipulation becomes also easy, we added all 10 values stored in an array
putting statement sum=sum+marks[i] in the loop.
4) Since we have an array of size 10 and each of these blocks are of type int, total
memory consumed for this array is 20 bytes (2 bytes for each).
7.4 Memory Allocation in an array
Whatever the size of an array, it always consumes memory in contiguous manner.
• int a[4];
In the above declaration, array size is 4 which mean an array is a collection of 4 int type
variables. Thus the total memory occupied is 8 bytes.
7.5 Two Dimensional and Multidimensional Arrays
C programming language allows multidimensional arrays. Here is the general form of a
multidimensional array declaration:
<data type> arrayName[size1][size2]...[sizeN];
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays
Example:
int a[3][4];
The above declaration says, we have an array of 3 arrays of 4 int blocks.
Array will always get memory in contiguous manner. For an ease of understanding,
conceptually 2 dimensional arrays can be viewed as row column fashion. As we have three
arrays each of containing four elements, we can say we have three rows (arrays) each
containing 4 columns.
Example:Program to add two matrix of order 3 x 3.
#include<conio.h>
#include<stdio.h>
main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf(“Enter 9 numbers for first matrix\n”);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&a[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
Explanation:
1) Notice the declaration of arrays. We have declared three two dimensional arrays.
2) Observe the style of input, scanf() is repeated with nested loop.
3) Lastly sum of corresponding elements of two matrices are added and stored in third
array.
4) Finally sum is displayed on the screen
Last two styles are invalid and lead to compile time error.
Note: It is important to remember that while initializing an array it is necessary to mention
the second(column) dimension, whereas the first dimension(row) is optional.
Check Yourself:
Objective Questions:
1) What is the output of the following code?
#include<stdio.h>
main()
{
int x,k,a[ ]={1,2,3};
for(x=1;x<5;x++)
{ k=x%3; a[k]++; }
printf(“%d %d %d”, a[0],a[1],a[2]);
}
a. 3 4 5 b. 244
c. 2 3 4 d. 245
Chapter 8: Strings
Content
8.1 Strings and Null character
8.2 About format specifier %s
8.3 User Input
8.4 String manipulation through predefined functions
Example:
main()
{
char city[7] = “Bhopal”;
int i=0;
while(city[i]!=’\0’)
{
printf(“%c”,city[i]);
i++;
}
}
Explanation:
Notice the way of initializing array. Instead of writing each character in single quotes and
separating with commas, this convention is convenient to use.
Another important point to note is- there is no need to write null character at the end in this
convention, compiler automatically appends null character at the end
The printf() is repeated till city[i] would not become ‘\0’ character. In each iteration it prints
one character of the string.
Example:
/*Program to calculate length of string*/
main()
{
char text[20];
int len=0;
printf(“Enter a string “);
scanf(“%s”,&text[0]);
while(text[len]!=’\0’)
len++;
printf(“Length of string: %s is %d”,&text[0],len);
}
Explanation:
If you input Sachin length will be 6. If you input Saurabh length will be 7.
To calculate length of a given string, we take a variable len. len is initialized with 0. len is
now incremented till text[len] becomes nul. Since len is now containing index of that block
which contains nul. The value of len is length of the string excluding nul character.
No need to decrease len by 1 to show length at last, as indexing starts from 0.
8.4 String manipulation through predefined functions
There are several predefined functions to manipulate strings. These functions are declared in
string.h. We are discussing few of them:
1) Function name: strlen()
Usage:
main()
{
int len;
char str[20];
printf(“Enter a string”);
gets(str);
len=strlen(str);
printf(“Length is %d”,len);
}
for(i=0;i<5;i++)
gets(str[i]);
for(i=0;i<5;i++)
printf(“\nString %d = %s “,i+1,str[i]);
}
Explanation:
A two dimensional character array can store multiple strings. According to our example we
can store 5 strings each can contain 10 characters.
Notice function gets() we passed str[i] which is equivalent to &str[i][0]. Same is the case in
printf().
Check Yourself:
Objective Questions:
1) What is the output of the following code?
#include<stdio.h>
main()
{
char s[ ]=”COMPUTER”;
printf(“%s”,&s[1]);
}
a. COMPUTER b. OMPUTER. c. O d. Error
2) What is the output of the following program?
#include<stdio.h>
main()
{
printf(“%c”, “dennis”[1]);
}
a. ennis b. dennis c. Error d. e
3) Find the output of the following program
#include<stdio.h>
main()
{
int l;
char s[ ] =”Sachin”;
char t[ ] =”Saurabh”;
l=strcmp(s,t);
printf(“%d”,l);}
a. 18 b. -18 c. 17 d. -19
4) Find the output of the following program
#include<stdio.h>
#include<string.h>
main()
{
char str1[20]=”Hello”, str2[20]=” World”;
printf(“%s\n”,strcpy(str2,strcat(str1,str2)));
}
a. Hello b. Hello World
c. World d. WorldHello
5) Point out the error in the following code
#include<stdio.h>
main ()
{
char str[ ] =”Bhopal”;
char s[20];
s=str;
puts(s);
}
a. Array declaration of str missing size in square brackets
b. Syntax error in call of function puts
c. LValue error in the line s=str
d. No error
6) Find the output of the following program
#include<stdio.h>
main()
{
char p[ ]=”%d\n”;
p[1]=’c’;
printf(p,65);
}
a. A b. Ac c. 65 d. 65c
7) Find the output of the following program
#include<stdio.h>
main()
{
printf(5+”Good Morning\n”);
}
a. Good Morning b. Morning
c. M d. Good
8) Find the output of the following program
#include<stdio.h>
main()
{
char str[4][20]={ “Sharma”, “Computer”, “Academy”};
printf(“%d %d %d”, sizeof(str), sizeof(str[0]), sizeof(str[1][2]));
}
a. 100 20 1 b. 222
c. 2 2 1 d. None of these
9) Find the output of the following program
#include<stdio.h>
main()
{
char str[3][20]={ “Sharma”, “Computer”, “Academy”};
printf(“%c %c %c”, str[2][3],*(str[1]+2), *(*(str+1)) );
}
a. d m C b. Error
c. d m o d. doC
10) Find the output of the following program
#include<stdio.h>
main()
{
void fun(void);
fun();
printf(“\n”);
}
void fun()
{
char c;
if((c=getchar())!=’\n’)
fun();
printf(“%c”,c);
}
a. abc abc b. Infinite Loop
c. bca d. cba
Chapter 9: Pointers
Content
9.1 Pointers
9.1 Pointers
A pointer in C is a special variable used to hold the address of other variables.In single word
we can say that we can say that we cant hold address of a other variable into ordinary
variables
i.e. int a=10;
int b=&a
doing this is wrong .
So we need a special type of variable known as pointer.
int x=5;
The above declaration statement tells compiler about the name of memory block
(variable x), amount of memory occupied by the block (2 bytes) and type of content
(integer constant 5).
Every byte has a logical reference number known as address of variable. In the above
example address of x is 65524. Though this address number could be anything and
unpredictable to us, it is always in the range 0 to 65535.
Whatever would be the address of our variable following things are important:
You are already use to of address of operator as you have been using it in scanf()
function. Now let us examine its characteristics:
Example
main()
{
int x=5;
printf(“x=%d”, x);
printf(“\nAddress of x =%u”, &x);
}
Output
x=5
Address of x =65524
Explanation:
We can print address of a variable by using address of operator. First printf() is a usual
statement printing value of the variable. Second printf() is used to print address of
variable x. Since %d can print integers comes in the range -32768 to 32767, so we are
using %u to match the range. %u can display integers in the range from 0 to 65535.
Example
main()
{
int x=5;
printf(“x=%d”, x);
printf(“\nAddress of x =%u”, &x);
printf(“\nValue at address of x = %d”,*&x);
}
Output
x=5
Address of x =65524
Value at address of x = 5
Explanation:
In the last printf() value at 65524 gets printed. Since &x represents address of x that is
65524, so the operand of indirection operator (*) is 65524. As a result *&x represents
block x.
We cannot assign anything to block by just writing address to the left of assignment
operator.
&x=25; //Error
However we cannot assign anything to &x, we can assign address of x (&x) into some
other variable. Let’s say variable is j then we can write
This is the correct way as variable is in the left side of assignment operator.
Syntax:
<data type> *<ptr_name>;
int *j;
Asterisk (*) symbol before j in the declaration statement tells the compiler that this is a
special variable meant only to store address of another variable. This special variable is
called pointer.
Example
main()
{
int i = 5, *j;
j= &i;
printf(“\n%u”, &i); //Address of i
printf(“\n%u”, j); // content of j
printf(“\n%u”, &j); // Address of j
printf(“\n%d”, *&j); //Value at address of j
printf(“\n%d”, i); //content of i
printf(“\n%d”, *(&i)); //Value at address of i
printf(“\n%d”, *j); // Value at address in j
}
Output:
65524
65524
3276
65524
5
5
5
Since pointer contains only address of another variable, they consume 2 bytes in
memory. Whatever is the type of pointer, it consumes 2 bytes in memory.
Wild pointer
When pointer is declared without initialization, it contains garbage value. This garbage is
interpreted as address because it is stored in pointer variable. Obviously this garbage
represents invalid address as we haven’t made any reservation to that memory location.
Such pointers are called un-initialized pointers or wild pointers.
float *s;
Above declaration does not mean that ‘s’ is going to occupy 4 bytes and would store floating
point value. It actually means ‘s’ is going to contain address of floating point value.
‘s’ will store an address of some float block which contains floating point value.
Address of the first byte of any memory block is known as base address. Size of variable
depends on its type. Each byte will get address. It is possible to have multiple address of
a variable, as variable can be of multiple bytes.
int *p, a;
float *s, k;
char *m, ch;
double *d, b;
p=&a;
s=&k;
m=&ch;
d=&b;
Now we have four pointers, each of different type. Each of the pointers consumes 2
bytes in memory. p contains address of int block ‘a’, s contains address of float block ‘k,
m contains address of char block ‘ch’ and d contains address of double block ‘b’.
It is important to note that operating system allocates address to every byte. In our example
‘a’ is a variable of type int whose address is 1000 (assume), but this is the address of first
byte of int block. 1001 is the address of the next byte. Similarly 2000 is the address of first
byte of float block. Since float block is of 4 bytes, each byte has different address in a
sequential manner.
Address of the first byte of the block of any type is known as base address of that block.
Pointer variable can store one address at a time and it is always base address. To access any
block through pointer requires address of remaining bytes of the block. This is possible
because of two reasons. First, addresses of bytes of a block are always in a sequence.
Second, type of pointer that stores base address.
If the pointer is declared as float pointer (consider ‘s’ in above example), it is aware of 3
more addresses to be accessed along with base address. Similarly, if the pointer is declared
as double pointer (consider ‘d’ in above example), it is aware of 7 more addresses to be
accessed along with base address.
Pointers declared with keyword void are void pointers or generic pointers. Since type of pointer is
void, pointer can not access block, whose address it holds, by just de-referencing pointer. As we
studied in the above section, pointers only hold base address and type of pointer decides how many
more bytes need to be accessed. If the type of pointer is void then we can not know how many more
bytes need to be accessed. Every time when we access block through pointer, typecasting is needful.
Example:
main()
{
void *p;
int x=3;
float k=3.14;
p=&x;
printf(“%d”, *((int *)p));
p=&k;
printf(“%f”, *((float *)p));
}
Pointer is a variable which contains address of another variable. Now this variable itself could be
another pointer. Thus we now have a pointer, which contains another pointer address
main()
{
int i = 3, *j, **k;
j=&i;
k=&j;
printf(“%u %u %u\n”, &i, j,*k);
printf(“%u %u %u”, &j, k, &k);
printf(“\n%d %d %d”, i, *j, **k);
}
Output is:
333
9.9 Pointer jargons
int i; // i is an int
Although C language is not very strict about compatibility issues between various type of data, but
programmer has to take special care about type conversions. It is also needful in forthcoming
programming languages.
Example
main()
{
int i=3;
char *j;
j = &i; //Error as incompatible assignment
printf(“%d %u”, i, &i);
}
(Error message depends on compiler most of the C compilers do not show any error)
Example
main()
{
long int i=3;
int *j;
j = &i; //Error as incompatible assignment
printf(“%d %u”, i, &i);
}
Example
main()
{
int k, i=3, *j;
j = &i;
k = j; //Error as incompatible assignment
printf(“%u”, k);
}
Example
main()
{
int k, i=3, *j;
j = &i;
k = *j;
printf(“%d”, k);
}
The output is
Example
main()
{
int k, i=3, *j;
j = &i;
k = *j + *j;
printf(“%d”, k);
}
The output is
6
In this program *j would means ‘value at address contained in j’ and it is 3.
Example
main()
{
int *k, i=3, *j;
j = &i;
k = j + j;
printf(“%d”, k);
}
Error: Invalid pointer addition.
Rule 3: We cannot multiply scalar value to an address. Similarly we cannot divide an address
with scalar value
Rule 4: Adding 1 to the pointer gives address of the immediately next block of the same
type. Similarly subtracting 1 from the pointer gives address of the previous block of the
same type.
Pointers are very useful concept as it does miraculous things that we can never imagine
without pointers. Pointers are memory references and capable to make changes in the
memory location.
Recall the concept of functions where one function cannot access variables of the calling
function. Though, we can pass values of the variables of ‘calling function’ to the ‘called
function’ and called function now can use values received in formal arguments but
cannot make any change in actual arguments.
If we pass address of the variables of calling functions in place of values of the variables,
then called function can receive variable addresses in pointers and can access actual
arguments via pointers.
Another concept was, we cannot return more than one value from a function.
When we have addresses of variables of calling function, we can assign any value (or
result of some calculation) to actual arguments via pointers, which resolves the need to
returning multiple values.
Function can only access its own memory and cannot access variables of other functions but if
we pass address of variables during function call, we actually give power to the ‘called function’
to access variables of ‘calling function’ via addresses of variables
Example:
#include<stdio.h>
#include<conio.h>
void swap(int *, int*);
main()
{
int a,b;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d%d”,&a,&b);
swap(&a,&b);
printf(“”a=%d b=%d”,a,b);
getch();
}
void swap(int *x, int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
Output:
10
20
a=20 b=10
Explanation:
⚫ In the above program, two variables (a and b) are declared in main() function. They can be
accessed from main() function only by their names.
⚫ Let us assume user enter values 10 and 20, which get stored in variable a and b.
⚫ Observe the function call swap(). Instead of passing values of variable a and b, addresses of a
and b are passed.
⚫ Since addresses are always stored in pointer variables, we create two pointer variables in
function swap() as formal argument.
⚫ Pointer variables x and y received addresses of variable a and b.
⚫ In function swap(), variable a and b of main() function can be accessed with the help of
pointers x and y.
⚫ *x represent variable a and *y represent variable b.
⚫ Notice that values need not to be returned as changes made in actual locations only.
⚫ Also notice the declaration of function swap(). As two addresses of int block would be passed
during function call, it is specified as void swap(int*, int*);
Example:
#include<stdio.h>
#include<conio.h>
void input(int *);
void display(int *);
main()
{
int a[5];
clrscr();
input(&a[0]);
display(&a[0]);
getch();
}
void input(int *p)
{
int i;
printf(“Enter five numbers”);
for(i=0; i<=4; i++)
scanf(“%d”, p+i );
}
void display(int *p)
{
int i;
printf(“Five numbers are: ”);
for(i=0; i<=4; i++)
printf(“%d ”, *(p+i));
}
Explanation
⚫ Address of very first block of array that is address of a[0] is passed during function call of
input() and display()
⚫ Address is received in pointer variable p.
⚫ We need not to create as many pointer variables as we have array blocks. We need to store
address of first block only (a[0]). Rest of the addresses can be obtained by simple pointers
arithmetic. By adding 1 to p we get address of a[1], similarly by adding 2 to p, we get address
of a[2] and so on.
⚫ In the function input(), see scanf(), we wrote p+i in it. As the value of i increases in every
iteration of for loop, p+i represents address of successive blocks of array.
⚫ In function display(), see printf(), we wrote *(p+i), as we need to pass values of array blocks in
function printf().
There are two ways to create pointers that will be used to store address of two dimensional
arrays. First is simply create a pointer and second is pointer to an array
main()
{
int i;
int a[2][3]={3,5,1,6,7,8};
int *p;
p=&a[0][0];
for(i=0;i<=6;i++)
printf(“%d”,*(p+i));
}
Array of any dimension, always consumes memory in contiguous manner. In our example we
made an array of six blocks. Address of the first block gets stored in pointer p. Now by
incrementing address contained in p by one each time, we can point to next block in array
main()
{
int i,j;
int a[2][3]={3,5,1,6,7,8};
int (*p)[3];
p=a;
for(i=0;i<=1;i++)
{
for(j=0;j<=2;j++)
printf(“%d “,*( *(p+i)+j));
printf(“\n”);
}
}
Explanation:
⚫ Notice the way we declare pointer. This is not a simple pointer but it is a pointer to an array of
3 int blocks.
⚫ In the line p=a, address of array gets stored in pointer p.
⚫ Consider the above diagram, let us assume the address of array is 1000 and it is stored in
pointer p.
⚫ p+1 represent address of second array that is 1006. This happens because p is not a simple
pointer to an int, rather it is a pointer to an int array of size 3. Thus every time when pointer is
incremented, it points to next array.
⚫ *(p+1) represent address of first block of first address and if we add 1 to it that is *(p+1)+1, it
means address of next block of the first array.
Chart below gives you a clear picture of pointer jargons and their meaning
Just like an int array, char array can also be managed with pointers. We can store address of char
array in char pointer. Now this pointer can be used for any string manipulation
main()
{
char str[ ]=”Welcome”;
char *p;
p=str;
printf(“%s”,p);
}
Output:
Welcome
There is a difference between p and str. Pointer p is used to store address of char array. We can
change value of p at any instant as it is merely a variable. On the other hand str is not a variable.
Name of array like str is always used to represent address of first byte of array. Since str is not a
variable operations attempting to change value of str leads to compilation error.
Array of pointers is a group of pointers. We create many pointers to point similar lists; we can
store addresses of these lists in an array of pointers.
Example
main()
{
int a=3,b=4,c=5,i;
int *p[3];
p[0]=&a;
p[1]=&b;
p[2]=&c;
for(i=0;i<=2;i++)
printf(“%d ”,*p[i]);
}
Output:
345
In the above example we have three pointers, p[0], p[1] and p[2]. These pointers are used to contain
addresses of a, b and c. Thus pointer array means sequence of pointers.
On the other hand dangling pointers are initialized perfectly but due to programmers carelessness it
is still pointing to the memory area which was released.
main()
{
int *p;
{
int x=4;
p=&x;
}
*p=5;
}
See the scope of variable x is limited to the inner block. Pointer p is containing address of
variable x. As soon as control comes out from inner block, memory of variable x is released, but
the pointer p still contains address of x. Here p becomes dangling
Pointer to a const is a pointer that stores an address of const variable thus we cannot modify
variable data using pointer.
const int x = 4;
const int *p; //or int const *p;
p=&x;
The above code tells that the pointer p is a pointer to a const. This means we cannot modify variable
x using pointer p.
For example:
Another example:
int x=4;
const int *p; //or int const *p;
p=&x;
x++; //valid
*p=6;//error: cannot modify const variable
p++; //valid
Another example
int x=5;
int *const p=&x;
p++; //error: cannot modify const variable p
x++; //valid
*p=7; //valid
Another example:
int x=5;
int *const p;
p=&x; //error cannot modify const variable p.
Remember that const variables must be initialized during declaration.
Check Yourself:
Objective Questions
1) Are the expression *ptr++ and ++*ptr are same?
a. Statement is true
b. Statement is false
c. True only when ptr is an int pointer
d. True only when ptr is pointer to an array
2) Which of the following statements correct about k used in the below statement?
char ****k;
a. k is a pointer to a pointer to a pointer to a char
b. k is a pointer to a pointer to a pointer to a pointer to a char
c. k is a pointer to a char pointer
d. k is a pointer to a pointer to a char
6) What would be the equivalent pointer expression for referring the array element
a[i][j][k][l]
a. ((((a+i)+j)+k)+l) b. *(*(*(*(a+i)+j)+k)+l)
c. (((a+i)+j)+k+l) d. ((a+i)+j+k+l)
main()
{
void input(int*);
void display(int *);
void sort(int*);
int arr[10];
input(arr);
display(arr);
sort(arr);
display(arr);
getch();
}
The job of function input() is to take data from user for the array. Function display() use to
display the content of array. Function sort() is to sort array data in ascending order.
6) Write a function to compare two strings and returns 0 if they are same else return
ASCII difference. Prototype of function is:
int strmatch(char * ,char *);
7) Write a function to reverse a string and returns address of first block of reversed
string.
8) Write a function to add two matrices of order 3x 3. Use pointer as a formal argument
to receive address of an array.
9) Write a program to handle three variables of different types with single void pointer
10) Write a function to perform case insensitive comparison of two strings.
Content
10.1 Structure
10.2 Defining Structure
10.3 Using structure
10.4 Accessing members of structure
10.5 Structure and function
10.6 Structure and pointer
10.7 DMA
10.8 Function malloc()
10.9 Function calloc()
10.10 Function free()
10.11 Link List program
10.1 Structure
Comparing structures with arrays, both are collection of memory blocks used to store
multiple data. Array variables do not have names but have indexes, here in structure
member variables do have names and can be of different data types.
Syntax
struct <tag>
{
Type variableName;
Type variableName;
...
};
• struct is a keyword.
• <tag> is any name of your choice. It becomes the name of user defined data type.
• Type is any data type
• Variables declaring inside structure body are called member variables.
• Remember to put semicolon at the end of structure body.
Using structure means using new data type defined with the help of struct keyword.
Just like we declare variables of primitive types(int, char, float, etc), we can declare
variables of user defined data type.
Example
#include<stdio.h>
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student s1;
...
}
• Once you have defined the structure you can use it as a data type in your program.
• Every time you use data type which is defined with the help of struct keyword, must
be preceded by struct keyword. Observe the statement in main(), student is prefixed
with struct.
• Student is a non primitive or user defined data type
• s1 is a variable of type student.
• S1 occupies 22 bytes in the memory; first 2 bytes for ‘rollno’ and next 20 bytes are
for char array ‘name’.
• You can define a structure either inside a function or outside a function. When
defined inside a function, it is known as local definition and can only be used by that
function only. If the definition resides outside the function, it is known as global
definition and can be used anywhere in the program. In the above example we have
use the later one.
• You can also declare variables during defining a structure as follows
struct student
{
int rollno;
char name[20];
}s1,s2;
Example
#include<stdio.h>
struct student
{
int rollno;
char name[20];
};
void main()
{
struct student s1;
printf(“Enter rollno of student\n”);
scanf(“%d”,&s1.rollno);
printf(“Enter name of student\n”);
gets(s1.name);
printf(“You have entered:”);
printf(“Roll no: %d”,s1.rollno);
printf(“Name : %s”,s1.name);
}
We can pass a structure variable in a function just like we pass values of primitive types.
Example
#include<stdio.h>
struct student
{
int rollno;
char name[20];
};
struct student input(void);
void display(struct student);
void main()
{
struct student s1;
s1=input();
printf(“You have entered:”);
display(s1);
}
struct student s;
printf(“Enter rollno of student\n”);
scanf(“%d”,&s.rollno);
printf(“Enter name of student\n”);
gets(s.name);
return(s);
}
void display(struct student s)
{
printf(“Roll no: %d”,s.rollno);
printf(“Name : %s”,s.name);
}
As we know from previous chapters, the type of pointer should be the same as the type
of block whose address is contained by that pointer. Thus to contain address of
structure variable, the type of the pointer should also be of same type.
In the above code, p is a pointer of type student, so it can point to any student block. S1
is a variable of type student, hence we can assign address of s1 in p.
Accessing members of structure s1 through p need a different operator called member
access operator (->), popularly known as arrow operator.
Complete example
#include<stdio.h>
struct student
{
int rollno;
char name[20];
};
void input(struct student);
void display(struct student);
void main()
{
struct student s1;
input(&s1);
printf(“You have entered:”);
display(s1);
}
To store data we create variables in our program. This can be done by using data types.
In all our previous programs we wrote data type declaration instruction to specify variables to
the compiler. Compiler resolve declaration statements at compile time and maintain variable
related information in symbol table.
The amount of memory allocated for variables depend upon the information created by
compiler at compile time by looking at declaration statements. This is called static memory
allocation.
The benefit of static memory allocation is its cost effectiveness in terms of time. Since decision
about amount of memory needed for variables are already done at compile time, no extra time
would be consumed for this purpose at the time of execution
There are scenarios where programmer is not sure about the amount of data to be handled by
the program. Static memory allocation is definitely a bad choice in such case. Solution to this
problem is dynamic memory allocation.
Decision of allocating memory to store data has taken at run time gives flexibility to the
programmer to make program efficient and cost effective in terms of memory consumption
Allocating memory at run time can be done by using either of two predefined functions:
1) malloc()
2) calloc()
We can also de-allocate memory using a predefined function free(). This function can release
memory that has been allocated previously by either malloc() or calloc() function
There are subtle differences between static memory allocation and dynamic memory allocation.
Memory blocks created by malloc() or calloc() has no name but can only be access using their
addresses
The malloc() function allocates a block of memory in bytes. The malloc() function is like a
request to the RAM of the system to allocate memory, if the request is granted, returns a
pointer to the first block. However if it fails to allocate memory returns NULL.
The malloc() function reserves a block of memory of specified size and returns a pointer of type
void.
This statement allocates contiguous space for n blocks each of size element size bytes. All bytes
are initialized to zero and pointer to the first byte of the allocated region is returned. If not
enough space NULL is returned
The free function is used to de-allocate the previously allocated memory using malloc or calloc
functions.
free(ptr);
Write a program to prepare a list of integers and manage basic operations on it like adding
new data to the list and deleting old data from the list.
#include<conio.h>
#include<stdio.h>
#include<alloc.h>
#include<stdlib.h>
struct node
{
int x;
struct node *p;
};
struct node *START=NULL;
void adddata();
void viewlist();
void deletedata();
void main()
{
int ch;
while(1)
{
clrscr();
printf(“\n1. Add data to list”);
printf(“\n2. View list”);
printf(“\n3. Delete data from list”);
printf(“\n4. Exit”);
printf(“\n\nEnter your choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
adddata();
break;
case 2:
viewlist();
break;
case 3:
deletedata();
break;
case 4:
exit(0);
default:
printf(“Invalid Choice”);
}
getch();
}
}
void adddata()
{
struct node *n,*t;
n=(struct node*)malloc(sizeof(struct node));
printf(“Enter a number: “);
scanf(“%d”,&n->x);
n->p=NULL;
if(START==NULL)
START=n;
else
{
t=START;
while(t->p!=NULL)
t=t->p;
t->p=n;
}
}
void viewlist()
{
struct node *t;
if(START==NULL)
printf(“List is empty”);
else
{
t=START;
while(t!=NULL)
{
printf(“ %d “,t->x);
t=t->p;
}
}
}
void deletedata()
{
struct node *r;
r=START;
if(START==NULL)
printf(“List is empty”);
else
{
START=r->p;
free(r);
}
}
main()
{
char ch,*p,*temp=0;
int i=0,size=0;
clrscr();
printf("Enter a string:\n");
p=(char*)calloc(size+1,sizeof(char));
while(1)
{
ch=getch();
if(ch==13)
break;
if(ch==8)
continue;
printf("%c",ch);
*(p+i)=ch;
free(temp);
temp=(char*)calloc(size+2,sizeof(char));
for(i=0;i<=size;i++)
{
*(temp+i)=*(p+i);
}
*(temp+i)='\0';
free(p);
size++;
p=(char*)calloc(size+1,sizeof(char));
i=0;
while(*(temp+i)!='\0')
{
*(p+i)=*(temp+i);
i++;
}
}
clrscr();
Check Yourself:
Objective Questions:
5) #include <stdio.h>
struct student
{
int no;
char name[20];
};
void main()
{
student s;
s.no = 8;
printf(“hello”);
}
a. Nothing b. hello
c. Compile time error d. Varies
6) #include <stdio.h>
struct p
{
int k;
char c;
float f;
};
int main()
{
struct p x = {.c = 97, .f = 3, .k = 1};
printf(“%f\n”, x.f);
}
a. Yes b. No
c. Depends on the standard d. Depends on the platform
8) Which header file should be included to use functions like malloc() and calloc()?
a. memory.h b. stdlib.h
c. string.h d. dos.h
9) What function should be used to free the memory allocated by calloc() ?
a. dealloc(); b. malloc(variable_name, 0)
c. free(); d. memalloc(variable_name, 0)
10) How will you free the memory allocated by the following program?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4
int main()
{
int **p, i, j;
p = (int **) malloc(MAXROW * sizeof(int*));
return 0;
}
a. memfree(int p); b. dealloc(p);
c. malloc(p, 0); d. free(p);