Python Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2129

TAVACOMPLETE

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

Basic ConCepts in Java


Data tupes
Type Conuer&ions
Command line arguments
classe s
Woappe
Cantxo 3tatements
ii-else nesked ik
SudtchTexnay Operatos
koopSSxucture s
xayS-
upe of
Classe3 and obiects
Lnikializing ohjectss
Canstructors
Key lMoxds
Static methads _and blocks
Lnhexitanc e
ONerxiding and Ovexlaa.ding
Base clads and Dexiveddass
Palymaxphism
THedoace
PacKaaes
Path and classpath
Exceptian Handling
yand Cate
Hierarchylhxou
Checkedond Onchecked
Shing Hanldling
Collectio ns.
Puthan ulorld in
JAVA COMPLETE
HCES
PyTHONWORIDIN
JAVA

An Taoductian to TAVA
rerequisties ofLearning Java
Necessity ok Psag1amming
tha is TAVA
WhaE is Platfoym adependenCe
Xlhexe JavaStandsloday

Pre Reauisites eaxning Java


To Staxt \eaxningJava, yau sould be
tamiliax wikh baSics Programming
And Since_ Java itselthas been build
up usia9 C/c+t languoage So just basic
Knaaledge in clctt is maze than Suilicient

Why wle Oeed Prcgramming


Caramunicate i th_digital machines
and makethem work accardinqly
loday in hepro9xamminqLOasld , We_ have
Moxe hon 0oanuage available
Aod Eyexylongcaaqeè desiane.d to talE:L
Opasticalax kind of yequixemnt
Baie History a Proaromamingan
langua gewas pimarily, designee0
develop "Sustem Solluaase slike Opera fing-
SustemsDeviceDzivers etc.
00ve deSigo broblems oih "" lao9
ttlonquage wa deSigned
S Ii an _dbjectOxiented Language wbich
Pavides data Secusiy_and Can be sed to
SalueXeal LAaldpxablems
ManiypaulaSthsares re S like Adabe
Acabatuinamp media playerintexne E Explare,
Mozilla ixe fosetc exe de Signed in c ++

What is JAVA 222


JAVA is a Technolaau (nat only a pragrammin
la.ngLage)to_develo p Obied aieated o.nd platfo
indepeodent applicatian
Plafoxm ndepend ence
Technole9u

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)

windaOS Mac Linux

window mac windouas


SC3 bit C6u bit)

Housmanyplatfoxms ore thee in the fiqu


AAser Only u

Windows Ma LinUx iadaus


bit)bit)L
LDindowS Mac LiaOx
C64 bit)

siodlaws| Mac Sindow inUX


Lt3 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

pes TAVA ApplicatiansS


Web-based Applications
Cloud-hased Appli.catians
Dishibuited Appli.cations
MabileAppli.cations
X aanaing and Animotion
Diaitaland Electonic Devices
Desklap Applications
Busine &3 Appli.catians

Impotant features_o JAVA


Platfoxm independent_
Autamatic Memosymonagement
Secu
Pabust
Simple
obiect oxiented
Multithreaded
Pythan-Jalosld in
*Platform Independent
A plat-orm i3 the _enviranment in which
Anapplication uns.
Lo otheY alordg it is the Canmbination of
An OS aada CPU.
P Eample

Windou 8+ latel -Coxe i5 (is ea_didiplatfa1m


Linux t AMD - AL (is_ana ther dif plat-foxm)
Mac tlntel-Caxe ialis qet Anather dii platfoxm

NaLa bein9 Platfaxm. indepe.adentDaeans


that anapplicatiao developed and Campiled
OvexOne plattorm Can be executed Ovex any
anyclhangein the
othe PlatfoxnaLaithoutany
Code
And Java has this_Capahility USing Hae
Cencept of byteCode and TVM",_
WheAevey e Compile 0Java program, he_
Compilex neyex aenexate3 macbine Code
Rathex it_generateS a mochine indepeadent
Cade Called he byle Cade"
hishytecade is nat directy under.sand-
able by the platform Los and CPU).
Lable
S o another3peciallayey of Soktuware is
xe quirec to Canvert the se byte.cade inshuchans
to mochine dependent dom
Tkis 3pecial lauer is the JVM, that Conveas
he layteCode to Ondexlying raachine inst==
Yuction Set and uaS t
@Python-wlarld-in
NAVA pxagram to print Hello wlaxld
class Hellohlaxld
publi.c Static Void oainstaing argsD
Sqstem.Out. Println (" Hello alorldL")

Outpu Hella wlaxldlL


Thus_anany Such platfarm rom which a
JVAM is available Can be Used to eyeCude
jauo application irespective of Ldhexe it_
h a s been_Compiled

iava make.s itse Platfosm.


Lndepeade nt_and italsouly justifie
ava's Slagan o"lORA (losite Once Run
anyLabere ).

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

ExpliciHy Cyeate poiatexs


2Java prnqram aluaays unS1 Java
Suntime enixonment with_almosknull intey-
actioooith Sustem OS,hence itis maxe
Secuxee

Robust
has Vexy Stsict Kules which evexy
Java
Program muSE Compulsaxilyfollouo and if
theseXules are Violated en JVM kills/
teminaBes theCode b 9enexatingException

To Understrand java s xabustnes3guess the


OutpuE o the olloiainq Cl++ Code
int ax1 l51
int ii
o CisajiL itt)_

asli=it1
lanpredictable, a-fter iis 5

Puthon-Jlorld-in
The Previas Code might shouo Uncextain

behaviaur in Clc++i.cif memoxy 1


available aftex an f4l, heo the Code uill
Bun,othexudiSeit will aenerate exxox at
Xuntine
On the othey band ii inJava this Cade is
executedthe JVM will kill the appli.cation
aS Saan as l finds the Statement axs[5]=...
>Reasan isthat ia Javawe are nat
allase.d to occe 3 ony asray beyond it's_
uppe ouserindey

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

lo Onderstand is feature Considey the.


Code_qivea oelous
Main

clscx
lactosial(5);_
Prime la)_
evenedd (D;_

In he Pxesi.ous Sample Code all yfunction.s.


clrscr(O,factoxial ( ), Prime ( and evencdd ()_
axe inalepe.ndent ot each othe but still they
Lill uo Sequentially i.e One atex the othex
This Can be improNed in Jayao4 USiog
multi thxeadinqeouae So tho all o ese
Python- nlarld-io
unctionS Cao un togethe
Benefits: Reduced execution timetull_
utili zation o CPU
SomePractical examples here multi-

hreading is used are


leCan Ope multiple tabs in the Same
brouwsex dindouo.
Whenwe USe a media ployex to listen to
aSangen thexe axe nultiple oactiuities
hich toke place paxallely like
0 Maving oo slider
O elapsed timebeing 8hauon,
0 Volume adjustment.
0 ability ta add ox emove Songs trom
tro.m
the playlista
Playin theSang etc..
HistouTAVA
o Develeped Bu James Gasling
O Oxigina Coapanu NomeSun miczasystems
O Cureat (arapan Oxacle Cxop
O Orgna Name Oak hut due to Capyaight
issueS,changed to JAVA
ofirstxele ase 23Januay 99
o fixstVexsion JOKJava developmentkiD1.0
o Ladest VeasionJDK (E.Dxeleased co L Sep
2021.

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

J2SE J2EE T2ME


Noa Knaion TSE) (Na KnaLAn TEE Naus JME)
aya Standard Java éatexptise ava Micxa
Edition Edtiona Edition
BoSics o Java LlehEnter- Applicationg
Langua ge of piise Kun oa mobile
0,
fundamental Application PhonePagera&
Desktop Appli=- etc
Cation
TSE (Java StandardEditian)
Ois is hemo3tbasic Vexsion of lava
oPytaon-dorld-in
Qnd it PxavideS US Coxe ConCeptsof
dava
languag
Longa like thedatatypes,Operators
aXrays,methads,OoP, GaUL Caraahical USer
Latexkace)etc.
OSince it teaches OS Caxe Cancepts
ot Java that is shnany peaple Call it
CORE JAVA althrough SON neex gavethis
name

O Dsed o developing de3ktop applications


ike Calculators, mediaplayex, IDE etc
OO ihe Java EE which Stands for ava
Eaterpxise Ediinn) is built on top o the
Sava SE platfaxm and is a Callection o
ibxaxie usedo building Cnteypxise
applications" ((Usually laleb applicatians)
O TSimple texm ue Can SayJEE S
used nx developing applications ahich un
on Se xverS.
O Same papulax application3 developed Using
JEE axe Amazon.in , alihaba.ComixcteCaina
deacellulor. Conm, aistel.in etc.

TME CJava Mic1o Edition)


O Java ME 18 the Slimomex Version o Java
torgetedA tonaxds Somalll device Such as_
Mobile phoneS
0 Genexally Peaple tend to think o he
Mico edition a8 he mobile edition,ahile
in ealitythe micro editionis USednot
@ Python-Jaloxld-in
ust fo mo bile phone, but fox all Kind
o devices,Such as elevision Seks,printexs
Sraast Caxds and more
OO But as Smax tphone rechnologaived
the USe o TME has Yealuced as ndxbid
has Supexseded it

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

toslshich is used ox Campilatioo.

) LAhich Component is Used to Compile, de bug


and ezecutejava pxagxaml
a)JVM1 b)JDk SIT JRE
Caxzect AnSLaex B
Pthan-World-in
Whickh Component isUsed to Convest
byte code tomachine Specifie Cade 2
JVM bJDk OJII dTRE
Canrec t anSlaex A

) lkich Componentis Used to_pxo vide_a


9
Platfoxom to un aiaya pro qram
JIL d)JRE
a JVM 5JDk
Cexect anSuoes D2

DoLnloading JDk
1. Goto
https://www.oracle.Carojava/technalagiesdasnnads/

2. Chck on the tab ot you OS aed click on


X-6 in&Ballez
3.You Lill be _asked o logia. So login a
ouxOxacle acCouat

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 )

LTS And STS


he_last u qeais have Seen Some Tapid
ChangeS in the a y dew Vexsians ofthe
Java Developrnent Kit is deployed andd
Maintained.

Taditanallgneuo jara Versiaas exe


alusays xeleased in a 2 to 4 yeax life Cgcle.
Eve 4geaxS a ne TOkLAauld be
elea sed, CantainingSome neuaeathures

JDk 1elease Timeliae


IDKlaunchedin Dec 2oo
TDklalanched in July 2l1
D launched in Mar 20l4
JDk launched ia Sep 2ol1

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

USing latepad USing an IDE like


Netbeans/ EclipSe
Tatellii tOFA te
gpingthe Cade io hisappraach shotuld
notepadand xuaningbesed aftex we have
i t thzaugh Cacama.adUndexstood he basic
Pronapt- Llosking o ava
Kis_appxaach is goadENot xeComme neled ox-
toí beginnerstox be ginnes because
leaxniog eochStep IDE hides all the basic
Steps which are e x
important to Dndexstand.
T is Vexy help-*I i3 also helpiul
SLLfo betkex unde and e have Unders hood
Y3tandthe 3teps Le basic aloxking oB_
cleasly lava

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)

Understandinq The proqramn


first ok all we Must_xemembey_ that
hat-
ava s o higkly Case Sensitive language
meon3 that lde have_ be Vexy
Coxe ulL abeut wppex CaseAnd lowesCase
e Hera hile pintheCode
tor éxample,
in preyious Code thxee letters
axe CampulsorilyinuppexCase and they are
T TeE
"_S o "
stsing and
System

This is because ioiava class nameS


begha i uppey Co3e
The
The ist Slatemeat a Oux Code is

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

Prposeothe method main)_

Why main) is public 2


Public" is an access madifiexand
in obiect Oxieated rograamiaqany method
o Naiable bich is declared PubliëCaa
be acesgiblerom outsidee _o the class.
Since mainl) method is Pablio in JoaYa
So VM Can_easily- occe and egecate it

wlhy Main is static


2Eery class Can be have wa kinds a
methad s non Static and stadic
A nnethod ieh _isnonstatic Con only
be Called sing obitct aftha classskile
@ Puthan-lalovldn
3totic method Can beCalled
without a n okjecl, Simply sing closs namt
henWhen JVM makega Call o he
maia methodHhexe is no object existing-
fax that here-ere it hasto have static
methad o alloo iaiaCation rom Outide
Hhe class.

Why Mainl) hAS Tetun ype aid -


Keyooxd Voidis Called xetuxo
pe Lshich indi.catesthet na Value aillL
returned b the method to i's Callez
Since mainl ) aethad in Savais natt
Siupposed x exetuxo Any- Naluetoohe
JVM_its ma.de Void dhich Simply means
maLaU is not retuxodag onythlag

Can e change /emave the Keuuard


USeddith main9
NoNot at all
Thisisis because mainl ) i called by
JVM and oto 0lloo TVM to Success-tally
Calll maial ) these Keyaaxds dxe mpaatant.
S f we tozgetdo Loxite theee Keqods
Hhenalthoug eCode wsil Copile
bu lail to un
Atoe Con do i3 change the oxder a
Dublicand stadic hud LeCaatdxop themn
Puthon wlorld.in
What is sthinq L1arqs
Shingi3predefiaed class inJava
S otNe statement staing LIaxgsis
declaxiag 0x c b e a n anay oB Staing
T Hia_Called Commandline arqument
and we wilL discuss t latex
Fox noLo, just xemBmbex that the
Statecaeat saing Iargs ha3 to b e preSeat
uoithmaial othexuise Cade Lill not xuo

Can changedrop shinaLlargs


O Noiust like ke4maxds Osed with
mainC) aaeCacapulsaxq, Similaaly stiag L
a i 3 alsa Campulsox
OA_we Can dais change he nam
om axgso Somehina else.
O Alsa eCan iotexchaage the aay
name ond 1
O fos_efample Sting a LIshing Jore
ShingIsh Sting_sbLi all ase Yalid._

Undexstaneling Susem.out Println)


O Now let'sunderstand Code in Hhe badu
hemainL metkadshich will pint
me ssa9e oo the_Cansole
Sunta
System.out-pxiatlo ("mesSage");
o System is oa predefined class
O Outis anobject xeeace Cnot obiect)
o Printla) 1s o methad
a Puthaa.wlarld-ln
Ologetkey aIL hee are USed f
_displaying tet Con3ale.

O ewill discusg s_paxt in_de tail


OnCe we have Covxed basics of JAVA

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

QLoill a iavo pragzam ompile_witbout


maint)2
Ves No
VeSPecause_maio) i3 nat neededfoy
Campi lation. But is_sed_foxex ecution o
he Cade. SoLoe Cao Campile a Java
Progrom ithaut maial) but we Canaat

(Pthon-ulorld-in.
Savinq the Souxce Code
Qnce e havew1ttea he Cade
Hhe next gtep_is to Save ond Campile

We Con Save Our Cade in tuoo locationS


withio hin Subdirectoxy ofjdk
OR
A_any locatisn in Our mackine
This xequire8 setting "PATH Laaiable
also)
ule oill 8kort usith irs appraac
Ond thea miorate toSecond appx0a Lh
hileLeaxnng abeut packages
l o save the Cade in "hinusE chaase
jdk's hio as thelecotian to Save in
ote pad
Tahe fle name Option proNide.
you like but with a ava
eyten.gion.

Paenernlly te Pxefex qiio 4he Same


the Same
Name Oux Code Suace Code a3 the
name ak Ous Class(Remember t is a
genexal choice not a xule )
>Also 1emermbex to qive the lename in
double quate os Otheudise notepad might_
add he eyteaioa
NoL Since Oux dloas nameis Test-
So Loe LOould Save Ous Kle by the na.me
Test, java
Pathoa-lorld-n
Campiling the SourceCade
lo_Compi le Our Code we ha veHo do

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

Whathappensalhen wle Campile ou


Lade
lhenever we Compile Our ava Code
he Compilerdoe3 he lollouoing
Itche cks tor Suntax eyror (like_
missinq Semicalons xang class or
method names e:te
TH aoy Suntax emor is found he
Cenapilatiaa gto ps.
Python- world-in
Othexise no Syntaz ero 01e
thexehe Campiler genesates the "bylecode
a OusSourCp Code

Paints To Remember_abaut "byte codes


Bute cade 3 re aenera ted a3 Sepera te iles.
The
h 3e
e seileshove he exten ionclaSS and
their nameiS Some s the hame ok the
Class_deiaed by the me
toxeyample i dlass_name islexE
the t e cade_name Oill_also be"Test.class.
Number o bytecade iles generatedis-.
Sam as numbes ofproqrammedefined
clossesSo il Qur progra.mCantaia8 three.
closs Calledcollege" , " Eaculky"_and "Student_
he three byteCode les dould be
genera ted Called:
Callege clas
Satultyclass
Studeat cloes
Executinq The Code
The general Sntay to un OL ode ig
Java Nane othe class Cantaiaiagmaio
method>
java is he sava iaBerpxeBex shich
Hakes.class le araument (nate: do
nat ite the eteasian class).
_closs e shauld Cantaia main)
Methodthat is _erecuted by- the ava
@Pthon_world-io
Laterpxe tex
eyample j i_class"Test has the mainl
methadthe ou Cocacn.a.nd lould be
AU1z
6) Hauo manycloss iles alauld be qenexa.
the ollooig Cade
class A_

Class PB

clo3sC

Ansioey 3.

) lkat 3hauld be thenacme al he


Progxam
ClassA_

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.

)lhatshauld he he name o the proqxam


class Indoxe
Dubli Static Noid main Shing 10393)

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

Q Tn he previou Code Wlhtch mala )


aethedaill ke Lalles bq VMit oe
Vua _Ous Cade 7
Pthon-woxldio
AnsweaILdepends on hou we sun the Codel
w e u it as
iava Bhopal
hen output _Oould be

And iweun tas


Java lndoxe_
Then Out put would be
l Indloxe

Supose we wite he llousing Code


ClassTest

Pulblic Static Vaid raaioshiog CJargs)

Suste m-Out. Priatln" Hello Use ")_


Suslem.Out.Priotla "wlelcameTo Java

3
*Nouo when we lailll xua it
laya Tes
The Output Laill be
Hello OSeY_
elcoaetoJava_

*Did ou notice Some thiog 1L


The iaeWelcornp lo Jaua autaa.atically gak
disployed on Recond lineWhy
Because the methad pxiatln icaplicity adds
0_neuO line at theend altex displaying he
Mes30qe.
puthan larld-in
e dn nst oont he neusline
elect henwe Can Oseanathezmthod
Calle d
So LaeLOite
Sytem.Out print("Hello USes")
stem.Out print(" Wlelome lo Java"-
Ihea he Output oould be2
HelloUSex kielcome o la

wauld be the ou pul al the follauaiog Code


S ske m-aut print (" Hello USer)
Sem.outpcotlo(" WelLome lo Tava )
Output
Hello ser wlelcanoe o Java
Tkis is because the me thad pin tlnl) method
pute a aealine alterthe message no
puts
be foxe

Lalhat Lanuld be the Output at ollaoing Cade


Suskem.out.pxiat ln (" Hello Usex ")y_
SugtemautPint (Welcome Tlo 1lava")_
Outputt
Hello OSey_
lelcome loava_

Qoha_auld ae the autput ol the Cade


Sushem.oulpint (Heilo Usey ")
Sustem OuPaiotla)
Suste m.aut.print Ce lcomelo Tavd)
Output Hello User
Ialelcanae lo JaNa
Pytkon _uorld-In
Thsis because the methad pintO aliaya
equiesarsumeaSa. Oe Cannot Call it uolthouf
Orquments_

Some omman ExrorS


*lheXe are Some ex4 Comman Mistakes
ohicha Poqxamme migktmaKe in his
Code due to ski ch exxorSaxise
Ihese are
rgebing ta match number _af opening ond.
clasing hxaceS
SOMeMore Concepts
|FA Ves Cemmondaubt Lobich might arise.
in Our mind dhile_leaxnin9 ava i3 that
am uOhere e Q r e 9ettina aCCesS_o
Sing" and Sustem"clasaes
*le kania that tey axeprede fined classes
but Le bavenlt included ony precleti.acdle_
in Oux Code ike header ilebat stll oe
Oe nle to usesting" and "System" class
KIn_LJava ae dont bave heo dey les,_
Tatheroe have Da ckage
A pockage iusta foldexskich Cantaiclng
i a a classes anda_ ava 14 Lere
e 224packagesondaining 456 clasRes.
* mang.e.stSthesepakages haxeis a
packaqe Calleaava.lanq LdichpxoVdes
elass e thataxe ndacmental oto the detion
the Nova proa mminq angtua9e
SiaCe hese la stes are sa easeatial the
Ptan-world-io-
Package iaalang isimplicity added
Oux Piaqam by the v
ova
a
Compi le ttsel._
he classes xinq,Suskem,Math and mony mose
Camerom tiS pockageonly
6ut we want to add ispackage
Oxsel then oe Can do So bysitin9-
mpot t" KeyuoOxd
InJavao o oddhe Suppoxt oi a
pakagelelass io Dus CodeLDe use the
Keuord impat ohose aenexal Suntax is-
impey tpackage-name >Ldas=name 2
OR
impexE Zpackage =name, *
orexample
impasjava lang tsing
imporjava langSustem
OR
impaitjavalang.

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

Numexic Non-Numexic class


intex face
Indegex Real char eaumo

bcclean
byte float
Shoxb double
int

Non PsimttiveData 1pes


Called
*Non pximitivNe data tupes are also
AS Reiexencedata ypes
KA Nan primitive Data ype ig Used to
yefer to anGbject
*Ia java, Vaiables at tpe_Class axa 48
numsand iatexfa.ceaxe xepxe.Sented a
obiects.
We oildis.cuss i s in later chapkers_
ike Araug and closSesand abied

Piraitive Data Tupes


heae a tally elglt pirniBive data types
in Tavahey Can be Categoxized asuen
be lo Pthorn-Wovd-n
ntege tyaes (Oocs nat allaio decimalplaces)
o Byte
o Shax
oint
o loog
Rationa Numnexs(Numbers wiHh decimal plates

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 **

languages Cannat he acCommadatedin 1 byt **

Spa Cee me.cmoxy So javaakes2uts


o r ChaxacBerS.
*java Suppors UNlCoDE buclanquage Souppoxts
ASCIL Code ln Asciu Cade oe Can epreLent-
choracheasal nglish languaseor storingall.
English latlex ndumhals1byte i
Suilicieat
But ONLCODE charaeker Se t is Supex.set
oAscl ia ohich all the chonchexs hich
xe available in 1 intexnationalanquagess
axe Suppaxed andit Cantains 6553
Chaxacters yanging xom O to 65535
T assign ONICoDE Values e have 2 options
OSe the AumexicValue lor)
Ouse Hheoma xxxy kahere xXXX
heradecima om a the alue
Fox exanaple
echor ch:652
o) char chr luoa':

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

Foxms_ ot Type ConVersian


TovaIava upeCoaveasioo îsa uoa tpes
Iype CanVersian

Loplicit Conyexsion Ezplicit Canvexsion


Cautamatically done Spe cioally_dane h
b Compilex) Proana mmex, also
Called Type Casting
Rthon-wWorld-in
Rules For Implicit ConVerSion
Ear impli.cit Conversion there are 2
Conditions lbieh caus he u e
O lhe values must heCompatble Canvertible.
AND
he value an RHS a a3Siqnmentmust be
Smallex thon Vaxible on_LHS
bath bath these xules Qre fallouoed theo
lava uill implicity Conver the value other=
oiRe Conversion_has to do done b the
Ysogxammey.
Rule 1Convertible
SConvextihle raeansit must be possihle-
Sox iava to Canvert a Value o m one toxm.
o anatkex
Fox exampleIH is po3sible ar java to
CanyexEa chaxacter tan integerUsing ita
UNICODE/AScl Value
So heollosinsailL Campile
int x= A';
Butit ie not possible far java to CanVext
he boalean Value "ue" to integer o8 the
Values 4ue and "lalse"_have no othey_
Repxeseatatian.
So he folloaing statement ull noE Carepile:_
int x=rue
Role 2i Sanaller
Smallex he sange o o Vaxiable's
means
data tupe must bea Smallex than other
Naxia Hels xange NoT THE SIZE
@Pthon wlorld-la
orexample a shaxt data typt Vaiable
has aYange o -32168 to 22767 lhich
i sSmaller Cmper Subse t)o the xan9e 0+
an int Vaxiable whoSe xang9e i 3
4433648to 214143364, Sa "Shoxt
i s CanSidexedL to be Saallexthan an iat"
Anather example, an int o bytes aod
hS a xange_o - -21444 8 3648 to 24448.3641
wWkilea loat i3_also o bytes but hos
xaoae e o-3.4 l3 to 3.4*lo shich is
reae than theangak int, Sa iat is
Smalle than loat
Tupe ConVeYSion. In
ype Expxesslon_
hyte a=lobe 20
bte c
C =a b i
Pas3ible loss_o Precsian
because both oand b aebutesjava
Conueyts them o int
Sal:1
C-Cbute )Cath
nat eliohle os bteis Zint So thexe_mayke
da tion o yolue.
Sol 2
hute a=lo he 20
int C
Ceath Moxe xeliable
QUIZ
Which o these is necesSaxy Candi tion tax
autamatic type Convexsian in Java ?
@Puthon-Ward-lo
|a lhe destiaotion type i3Smallex than
Saurcetype
bIhe desinatian tupe is loarger than Source

CThe dlestinatiaa upe Can be larger_0


Smallex than Source pe
8 )None of the mentioned.
Ansuoex-B

hat i3 the eroria this_Cade


bte be 50
bb* 50
b_Con nat Contaia Value2500, limted by
its range
b)*_opexatox has Canvexted b* 50 iato int.
akich Can nat be Converted to bgte uaithou
Casia4
bcan nat Contain Value 50o
No enor in this_Code
Ansoe

I f on expreSsian Caatoins dauble int; laat,_


lonqten dhole expreSSion Dill pramated into
shica- these dota tupeS?
A long-
at
Odauble
)laat
Ansie

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.

Tis is ohexe the argument3_omethoad main)


ome in actisn.
Le os takean evample to Undexsta nd. this...
CaSe 1
class Test
L

LPulbli static Vaid maio Sbin flara3


Sustem.out. Pintlo(" Hello "+ ar9s lo):

bin>lovalestSachia

Case llL
claSs esE

Public static Vai.d main(Sting Jangs


Pythan ulodd.in
Sstem.Out paintla (" Hell " +axg3 Lol)
Systemout.
s
Println C" Hello"argLiD

b lavaTes Sachia Amit


CASE-l
class Test

Puhlicstatic Void main Lstaing Largs)


Sustem.Out. pxiallnl" Hello" tar93fol);
Sustem.out Println (" Hella4 aras[1D:

3
bin > lava TesE Sachin
CASE-V
class Test

Public satia Naid maial staing Jarg)


Sustem.cout.println(" Hello"+axgs [o);
Sustem.Out hintln " Hella"+a« 1);_
SusBem.aut.Println{"ye1);

bin Java est Sachin Amit Sumit


CASF- y
closs Test

Public stalic Naid main Cstsinq LIaxgs)


pythanwarld-In
Syslem.ut println ("Hells"axgs Lo
Sqstemout Piatlo C Bye
0
")
2

bindova Tes Sackin Amit"


CASE-VLL (passin Inteqars)
ClassAdd Nos

Public siadic vaid raaio Shinglags.


Sustem.out Pxintlo First numbex is "+args[olD
SusteaOut. Pxintin "Se Cond aumbex is "+ar93 11
Syalem.Out. Priatla "iheik Sum is taxq3Ialtarg«1

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

USeS of Wapper classeS


Wraepexppex cla3ses e paainlyUsed for
too purpose S
o TrepreSent Peioitive data pes aS
_obiechs
OTaConvert shing m of a pimitive
Nalue o itS Oiginal homfor ex:lo'"to lo

Repre Senting pimitivesaS abiacts


*Cansidez hefallewingstate.mernt
int a =os/Naxiable a
Hexe a"is a Vaiable initiallzed to la
But ifwe _want we Can Coanvert it into
an obect by USing the ampper class lnteger-
A houon beloua
lntegex_obj oa /Naxiable a Converted to object
Canvexting Shing To_pimitive
*Anathex importance of wrapper cla ses is&
hat they Contain Special methads skich peafaam-
@python World-in
Canuexsianaomstiag to_peimiive datatype
datatype.
hese aethods have heix_nameasparse XXX_
dhexe Xxx isthe name a pimitive pe
KAlsa the are 3tatic in natue, Sa theg-
Can be directly Called by their dass nami
tox example integerparsalnt.s"
LisE of wraneey classes
Methad
Data type alrappe clas
int_ Lateger paxselat)-

Shaxt Shax Paxse shostC)_


byte Byte ParseByte)
long- Lon9 Pare Long)
Plaa Ploat Parse floatC)
_dauble Double Paxse Dauble )
Chax choracter No aNailable
booleaa Boslean Parse BasleanC)

Addition a NumbexUsina wlrapper clas3es


class ss Addnlos
Pablic 3tatic Vaidmain Cstaing s

int a,b, c_
ae lnteges. Paxselnt Carg3 [o])
b= lategex. Parselnt largs 1]):
Ceatb

Syetem.outpithtn ("Eirsk numaeris"+o);_


Sye tea.autaprintn (Secand qumhtr is"+h
Sgetem.out. Piiatlnl Their Sum is "+c
Python-wlarld-in
auess Hhe Qutput
classAdddos
Public shtic Vaid mainsting ags[)-
int a,b, C
a loteqer. Paxeelnt (ax93 [o)
b Inteqex Parselat LargsL 13)
C atb
Suelem. Out pxintln ( Fixst oumbes 1s "ta);
yetem. outpriatlaLSetond Numbe is " +b)
SueBena.out.Pxintla(" Theh Sum is " +d
3
3
Runoing
bia>ava Adddos lo Bhopal.
whdid Exteptianoccu?
EK Becouse he method parRelntO Can only
oxk_Oith Stsing Cantainio9 dgits
EKL any &hog Lontoins non integer Valves
hen the method paxselntO) kil Aa Exceptian.
KErea if Loe poas 20.5, then alsa i t will
thora
Numbex FoxoootException
Ho do accept decimal Values?
So i f we a n t o accep decimal Values,_
hen e au st Usethe melhad pax3 flaatC
o Paxse Dauble
hey acCept decirablinteg.er both kinds ol Values.
and thDA xeption oalu the qiuen Nalues is
Non-numeric Ike Bhopa,loa"_etc
Python_Warld- In
Decision Conto Statement
Decision Making i s e Mast (Iucia
Poxt0 nYpIo9Tom-
P
oExampleE Decding hether a qiven
numbex i Eyen ox_odd-
ETa Such Case Java Supports NasiaS
Decisioa CaazoStatements ike_pthex
TOgramming laaquoges theyAxe
elkenested if
Soltdh
Tenax -Operatoy
Syatax
ftest-Candition) 1 stattmen
rue false

*In Case thereisoaly a Sinale 3tat.ment.


in dhe bady of if-statemeat thenCuly
brace& Can be_dxspped.

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

Puble etatie voidmaial stsiagaqs)


int aainkegerparselntlagaLol);
System.outpiintin (" Numbex is _even")_
ele
Syutem.Out. pintln("Number ie_odd" );

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

Case T-clubbing CaseS


Sitch Vaxiable name

Case Value 1 Cose Value 2 Case Value 3

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

WAP hichshould accept 3 axgumeois


Nia Caomand line ol typ« opezand,operater
aod opexandand hould display the result
bpexas paingappropiate Calculation
Solulion
a a Calcalatox lotu_
Sam iS 4
ava Calculator 3-8
DiEFexence is-
leinarY Opexator
The ernaryopexatoY Can be USed as
an allexnative to the java'sil-else and
Suaitch statemeats.
But it goes beyond that and Can evea
be Used on the xight hand Side af_
iava 8tatemeots
Suntax
lasiable =test Candition)9chue Cose
LosleCaSe
PythonWonld-in
E2Ranaple
int a = u
Staing Sh
Sh=la 7.2 ==o)?"Evea";"odd"i
Sustecm.outPrintnCstr)
Ixy this
PWAP to accept the inteaex Via Command
ine axgumeatand pxint its obsalute Value
O User entes-1 Hen reSult Sbauld be 1).-
Salutino
elass PsintAbsalute

Public_static ysid nata shing arasL)


int ab
a integer parSelat (aro3 [ol
b Cad2)2 a i a i
Sustem.outpxintln (" AbSolute Value is"+b);_

>AP_to 0.ccept aninteges Via ommand


iae axqument and check shethey it is a
eapyear or not
NoteNo eve yeoxdivisible b u is a_
leap eos For Éxample Hoowas_not Yeax_
is leap But l6os iesa leap 4eorSimilosl
en 200s is aleap ueax but 2loo iwitL_
not be a leap yeax
Sothe Canditian ox leap eaa is that i
1.eox mugt be_diuisible by and notdisisihk
loo
2.Yeas must be divisible by 4oo.
Pthon-World- in
Loop Staucture Types
Loaps in java_alsa_are Contxo state-
meats OSed otor epeatinq a Set_of 3taBe
ments multiple ime S
Iheyaxe broadly Cateqoxized to be of
2tupS
Entay Cantaollecd-Candition is checked
sbea- the_ Conttol entess lop bddyEample
b i l eand ox loop.
Exit Cantalled -Condition is checked
afkerthe los entersloop bada.Example
do-wkile loop
While lap
Falseyntáy -

Lalile (1est Condition)

The loop Continues usill until the Candifion


is trueas Soon as the Candition aaes flasse
la exits the lsap bady
txercise -1
WAPto accept an inteqei Ton he uSe
ond pint ttsactosial. Make Sue that qaus
Prosyam 3haiuld paiat 1 1 o is entered?
import java.util, * ;
class Eactorial

public static Voidmainlshing aqs)


Pthon_Wosld- in
Scannex kb= ne w
Scanne(Systemin)
n t a,i=l
Sustem.out Priatln( Enter a no").
D: kh- nextIotOi
Lohile (n>=1)

n -

Su3temout println" tactorial is + ) .


3

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

displaying themessage ThanK you


Solution Ex 2
class Addtlos

Public sBatic Void aain Shing ags).


lava.til.ScannezKb=ne
jova.utl. Scanaer (susBemiia
0
int ahbi
Sthingchaice
do

Sustem0ut.println ("£nter tuoa inteqers")y


akhnextlnt
b=kbNextlatO
System.out.PaintlnC" Sum is+ Ca+)_
System.out.Pintln C" Taaaain (Y/N")
clhoice =kb.nextC
Swhile (choice.eguals lanoxe Cose (y ) ;
System-0ut. pxintln Thank yau"2

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

avaOtil Scanae Kb Ene u


javautil.ScannexCSustem.in)_
int o,b
Sbino choice
do

Sustem.aut.pxintln "£nter uo inteqes)


a= kbnexEItOL
b= kh. nextIntO
Sustemsdut pxintln Sum is "+(athD:
Suatem OutpaintlalTy aaaia V ;
nextline O
Choice : kbinextliae (
shile Lcheice.equals IanaxeCose Cy);
Syatem.aut printlnl" thank ynu );_
3
for and labeledor loap
Syntax
fo Ciniti.alization ,test Conditionj3tatemeat)

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

PablicStartic Vaid coainlshiog LJaras)


Scanner Kb=neu SCanner Sustemin
Sustem.out. pxintla " Entex a ng");
int ae kb.nextlatÓ:
int i
xie2i4-a-1iitt)_

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)

foxlinit Conditkion stmt)

AterCampleting the innex loop,the Cantral


maves back to he etatement partof Outer lop
Pathon-Wovld-in
kabeledbreak and Continue
Since, the break_Condttion bingsus out
o the loop hod hut in Caie o nestedlaap
lE uewantto Camplete lyCome out a the
loo phea we wil 03e labeled bxeak
Statemeat
Suntax
Label Name
a iniki Conditioni stmt)
ox (ini1 Canditlon ; stmtD

break abel name

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

*Lohenevex neu is used iojava, it gives


delault value o o the object foxmed

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

Public Static Naid main sthinq arqs[)


SCannex Kbene SCannes System.in)
int Jar
t n, Sum 0
System .0utpxintln Entex Size ak aay)
n kb.nextlnt)
arY=nes intLn];
Sustem.0ut:
U
printlalEnes oumbex3 in asxayoiSize tn
Cint isoien jitt)_
@Rthon-Wosld in
a n Li=kh.nextlatC)i
Sum Sum + axs LiJ

Sste.m-0utprintla" Sum is"+ Sum)


SysBe.mouta Pcintlal"hvexage is"+Ctloat)SumZn)

De allocatian o Dynamic Blocks


T ndexstand de allocation ef d namic
block s in java,we irst have t o Under3tand
the ConCepto qazbaqeblocks.
Daarbage black injava axe hoe.dgnamie
black3Ohich are no moxe xeteixed bu any-
seiexence, Fox,exomple let us Considex tuo

inttiA =ilo, 20 30, 4o, SoX


intt1BE6o,to,80,90 loo
A=8 harbage Block
looo
A
lo 20 3e o 50
looo

loooB 6o 7o o1 loo
2

PNonat His poiat the arayoi addre33


loodi3 nomoxepinfedbu onuxeferenCe.
Henceit is aa gar bage hldk.
_Lnaxba9ge Collectar
To Calle these9axbage blockSam
Be roaia- memary anddeposit fhem hack ino
ee poaJavaatexnall oses o oftusare_
Chuild into JVM)aamed oxba9e hlock.s_
"Pthan-ulorld.ina
Ihe9axboge Callectox pexiadically SCans
pnasmemazyaxea identifies qaxbage
blocke and Submits themoack into ree
Poal_

hepoqammex is Completely unuooaxe a


his activaiian process ak gabaae Callectox
Soia javadgnamic blocks ox objecs have
Ode.texmined te ime,as e y are Ceated
Onpmgm.mmers Yequest ond de allo.catiaa is
eclusive ly handled by JVM
Usin lengthpropeyty
Dopesties axe Specia methbd 1hich Can
e Calted uithout using paxeathesis
Pzogmmmers Cannat develap pmpeitie8in
Hhetr class.
By_ Using this paopex we Con easily qet
he ize ofan OXKa
he_lenqth pepety Can be Used an any
pmpexty
pe o aray Qad itis a ead only
Lan be assigned alengt
nothing-
haonpleintIJan = 2 l0,20,30,10,50,bo,1o,80
Suslem.autpriotln(" Size o amy is+au.lenqt
Exercise_
Some inteqerS OSing
WAPLOhich accepts
line argumentSand diaplaustheix
LCommand
Sum.A Case numbers Qa3Sed
aie le3s Thea
pro9ram Shauld Aisplauthe mezSaq
hoo tthe
please pasS atleakt 2 numbers
Salutioan' Class LengthBopextyOemd

Pablic static yoidmain(sttn Tlaxqs)


Pthonworldin
into,Sum =o
nE ayg3lenqthi
Co=1)

us lem.out println"please_ener atleast 2_numberii


gtem. exit (o)

ox int izojiLn;itt)
Sum =Sum +inteqer. pax Se lntCargs Li]
System.out.pxintlo C"Sum is "Sum)i

Enhanced for Laap


Enhanced ox Loop oa3 intoduced in Java
lin itg Version 5.0.
Suntax
Ldata type >L Naxia ble name LaTrau rehevene>)_

Vasiable's_data pe hauld beSame hat of aay


*1kis loap is mainlyOSed to pertornead
Lonly bpexationS We Cannak_Changeo1 manipulate
asaqValcae3 Osing this loop
Les adess.tandLis thaugh aa exomple
Erample
Lclass Eskancedfax Demo
public skatic Vaid mainlsthing Llars)
RthonWorld-in
atLJs = llo,20,30,4o, 50{
orCint x ia)

tem.out.pxintlnld

Dvaw backs of Enhanced for laop


Sam
trray Cannot be raos) aversed
Ayay
m e first
the endit wil alway3 St
elemeat.
They array wit betaversed Cmpletely,it
coil dat exit the loop at ony intemediate
Paiot
h e Naaioblehas to be declared in the loop
braceit is_o paxt o o Sqntax
2WeCao anly pextom read only Opexations
ie,taV eyse the arayno Change 0 manipul
ations Can be mode in the aray.
l w o DimenSional r a y s

Kectongular 2D hrau Jaaaed 2D trrau


Evex y TOLO Can bave_
Evesy 3OL ha& Same
namber o
P
Columns _dibereat ounmbey3
o Celumn
Rectanqular 2D tmay
Cyeating axxay etexenCe_

Ldatatype > L ULaay ve fexeoce >j(OR)


LdatatyPe>2aayrefeence L L J
Ezample =int(Itjan

Python-World-in
Creating auay bject
aayreferen object
Teterence = neuudatatee[Sze][Sizel)
ample -a Ene int[311
"a"is_a Yeference toan Arrayo Reteren=-

Ces Qn Yra yo inteqer


Let S_andexstand his ine thrnugh diagmm
matic e presentation.
ax is a retexence
LReereaces to an oroy ot inteaer

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

Public tatic Void main Cstaing LIargs).

SCanne kb=neus Scanner Syatem.in.


int L]f1arsi_

System.out pxintlnEnter numbe o£ Rauas Lcolumna


int y=kb.next.Int
i a tc= kb.nextlntO:
OsX ne intELYf c]
Toy lint ieojiLesrlenqthji++)

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+");

Systemout Pintln (" \n");

Sys ttm.aut Pxinlal" \n \n Sum a? a numbers


"Sam+In tverage is +(-laaDsunr*
@Rthon-World-io-
Jagged2D Amays=
Syntax
data tpe L]L1 auO4 relerence
LaouYee nCe =new Ldata -ene [Size L .
ample
intCIJaxr
3 E neuo int 3JL1
ex oJ=neco aas C61
0xYLJ£oeuo axslu
OXs J=neoaxz L5]1 2
loo0 2000

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

Sax lintieo iéaxi.lbcgthiit+)

Int Sum =0j


foxint j=oijLoxlillnqh )
Sum :Sumtom LLiI
Systemautpxint lan [i1L;3+'_);
Sustem.aut.printn ("Sum is "+Sum+";:
3
Yhon Word- in
ObiecOviented Prngyammind
A Ap0gYAmming payadiom hich is baked
ceal ooxla model ofobiscts 0x eatitiea.
xathe
PH is_Organized a1aund_objects
thaaactians"
Hhaa and data iather thaalogic
obtert-Csiented pragzamming takesth
Nie ohod hat we eally_Caye about are
the obiects e udant to manipulate athex
thanthe daqic sequired to paanipulote them
apiaxacomin onyTeal aexldentity_hich
ha8 Specikic oatkihutea ea tue sCan be
Can be
NepaeSeaked os an obiect.
>Along okathibute & each obiec Con
toke Aae ockioa also ohich_Are Called-
s e houiox
l n progam.ming osld, the se attihutes ae
Cale d datd memberg ond be havinuYS Loc tiang
axe Called unctions ox_method3"
He yo nobject
SYeSae humonS 0e Objectsbetause
e oeathibuteso.3 Aame iahdsaeeh.
oe alea an ghou be havioxs lkke isalkin9
nlkiog Yunain eoting etc.
Classes
Noto Create/sepreseat sbjectsoe fist
nave to orte all theix attatbute3 andex a
Singlecnup
his qmupi8 Called a lass.
A claas is used to Specify. the basi<
Shuctuse oan obiect_ond Cocabines
attibutes and method to be sed by
an object.
Pthon Wosld-in
Thus e Can Sa4 hat o class epies
eata tion the dota Pe and dhie ct
sepaeSents a kind_a Nastable afthat
doto He
ox example £achpexson Callectiuely Come
lundera clas3 Called Huma.n Peln
BeingS
e bels.ngto he_clos sHumanBeing

euel), aetfuell uel


Selspeed), satspeedL mazspeed

dlass
/CAR
MethadsAthib1 Pthon
-
Pillarso OOP
world
in.

> h e biec+ paradiorm


Aiented_rog ro mminq QarAdigm_
3 mainpillar3 ohich_are
LStande On
1.Abhation and nCapsulation
2.Poynamiphisma-
3. Lakexitance
Absbaction and Encapsulatian
Absroction Focus an the meoning ie
Suppxess inelevantinmplementation dehatls._
9EnCap8ulatian i3 a_proleg8 o binding or
opping hedata ond the Codes ha
opexate s on the data iato a Single entits
A bshaction and EnCapSulatiaa 90 hand in-
hand Cncap sulation
PreCedure Dota
Polymorphism
Paly= Many Morph-oxmS.
palymophism etex3 to a painciple io
biolat-
biologu ioudhi ch
Can baye Many
an oxgont3m
m_Ox3peciesS
onm or Stages
diflexe at J

HaNe yol_Seda mo you pexfeim poly


Moxphism in dayo day- fe
InhexitanCe
A_procass by Akichone class Can
Ocqire pxoPextie s o 0-nothercloss._
P
kELample e inhexit ehaxnctexistics an
OuxPaxen ts
Alvantages o Taheritence
. Reusability
2Extensikiliky
0
3.1ntox matiao is DMade pmano.qeable in a
ieraschica oxdex
Cxeating- a class_and ik obiec
Suntar
clas3 2claSS name>

Loccese madilier 2Ldatatype > Naviable name> =


Nalue

acce8madiex >2cturn tpe >Loaethad aome>


Carguments)

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

Public Void shosDda )

S.o.PC Roll,gxade ond pexcentage i3txall, qrade.pea)

class Use student

Public Static yai.d moia (stainq L orqs

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)_

So.P C Roll is" ol)


S.a P( Gxadeis'+ qrode);
S.o.P( Pexceataqe is tpes

classUsestudent

Plbltcakalic void pnoin3ttingf 1 axgs)


Student8= neuw 3tudendt
S.Se tDato O;_
SshoaDato

Intilalizin obiects lea) Data memnber


TJova do a obiect ae have 3 options
initialize
OSing methods have
i3alsoone of the m, udkich have
Studied la e previous notes.
Explicit initialization
2. Using Conshuctors
3.Vsin initializer blocks.
bplicit Iiialization
osto initialize_membeS of the
Java
KJava_ pexmits
class o the pointo teix declaxationAnd Such
Laay iniialization i s Knouon as bxpticik
inttializadion ( thon-W orld-in
C t Considers this oay asexos,but ia
dava
tkis isCon3idexed the `axtest_woy f Iniliolizolitoa.
*kis is pxeiexxed when allobietsShouldhave
he Some Value at initializatiea.
Conshuctors
KCansdtuctors Qe Speciol aethods st a class
i t h tollouoinq_choracexistics.
The nave the- Some name os hatof the class
T don't hove any retuxna typee
They oxe Automaticall CalledaS Soon 03 an
objecti3 xeated .e.Via neu. Reqsord
the proga nnex doesnot povide aoy Cansruct
4Len Jova ho
hen osn defoultConstuctox in eveu
closs aith an emphy bbdy.
The xeoxe aaCapu
lkexeoxe Consuctrs paovidedb lava.
hay Caane oade byprngampaerS.
Srerchse
WAP which Cansists s i a class Aomed
Cixcle,sith a data member adius.Accept xadius 0s
an input mm the Osex and initialize he data
membex Hhrough parameteaized CanstructarTaclude
Hoo more method3_oxeal)Ond Cixcumtere nce C) kich
Calculates axeo ond Cxcumierence and prias tham.
Initializey Block
*InJova lostoaceinitializek blacks ae sed tos
initalize iastonce data member OX- Say objects
hon-Wavin
TIuAS each timeohea on akiect ok a class
is Cxeated.
The whole block is Copied inside each Canstxucta
o he class.
Suntar
cla38 clo<SnAme2

2 dota rmembey
/initializex block

lintializx bady

Benifits 1Sincetheokole black qets Copied in


Canstauctei, So il there are multiple ConStuctors
thexe is no_need to i t e the Rome initialization
goinQOnd 0gain
2. Thexe are closee which do nat have Canstuuctors
TheyOxe Knoaa a3 AnonumoLS cla Sse Such closses
Con use theSe blocksto initialize obiects
Drausback-
.Tailalizer blocks Cannat passOsauments and
neiher Can- theu e tum any Value._
MethodOverloacinq
Methad overlaading meaa.S haying multiple Veisians
ot Same thing
for exomple Psintln) method in java Can be
Pathon-nlerld-in
3edtopint integerS staings,baalean, dauble etc-
just bchlling the Same method.
Somne Special
Special Yules to be yemembexed tox ovey-
loading
1.Ihey diflein Texmsotheixaxqumenß.
2.The axquaent& Con Vax nnumber, data tupe
and OYden
3. Ove loading- Cannat be dane _On the basis asetun-
type ot e oetbed.
Selection o Ovelaaded methad
The CasopilexSearche the methad Similar
data qpe ox wkich e OxQument _ua pogsed
n o t ound thea
.TSelecs the ovexloadedmethod ith_next hiahey
datoupe ina texmgof xa.ng
2 no bigherangedata
J
ape i3 availeble then
Sunto v exxDY OCCCurs.
yeatea closs name EigAxea, Laith an oNexlooded
methad 6 Calcalote _axea a Circle andClindexThese
oethads_sheuld tetura the Nalue of axea Calcalated
and piated in the main me thod. he paqam shauld
the 3ex abeut the choi Ce af kiqtxe ond
dime nsions
Constuctor Overlo.adinq
Same0S method oyexloading e Cad ovexlaada
Constuctox o a cloass.
The
Kerules reaain he Same hexe alto ie each
eoch
Pathoaorldin
LConStxuctor mush be unioue with 1espect to orqumzat.
Tsmain benefit i3 tox the person CaestiogH
ceatia
obiecks the class get a Vaxietyof option to
initialize he abiec he class
Arqument Passin
Jovaonly alla w Das3 by ualuethexe is noposs
by elexen Ce But yesc¥exence3 0xe pased but
Same as passbyValue
So we Can Sayhot in Java LAOe Can poss
axquuments as
1Passing \oxiahle ds Araumen
22 Passing evenCp os Oaumeat
Passina VaniahleaS gument
In iava also on paSSing Vosiables OS_asaument,
9ee generatea ohidh is terooed_cos
AraLumeat
*The method pexfoxnasall opexatian on thesedormal
Oxquments ond henCe no ckangeCan be aade an
actualOxquments.
Exercise

WAP to Suop to integex data members of a


class. aBex you Can modifit to acCeph input
omthe Usex
Sample output
Elo
=20

lo Pthon-Narld-in
PaSsin Amay Reference
class Demo

Pablic Vaid cdoubler lint bn


for Cint iea ieba.length
J
jiA+)
bulil =blil*2S
3
closs Test

Pulblte Static Veidmainlkthing [lags)

int Lax =ito,20,30,46, so


Demo d Eneo Dem.a_
ddaublex la;
int izoija3lengthjitt)
SO P Casn LD

Retuxning foay Refexence


Closs Decmo

Public intLI Create Array iat o


intLJbrr =neua int Lol
eturn bx
hon-Woxld- in
class Test

|Pablie Static Vaid maia Csaing LIarg


Dema d=neuo DemoO;
int Iax =di Cxeate Axxay C5)
Sugtem.out pxintin C"Lengthof orxay istan.ength

Pxactice Design anothex methad in the Same class


Called CauntC"skich shauld xetuxn tota humbe a
elemene ia the axxay ohi.ch are than the
seatey than the
numbexpassedSnaaller than. e numbey possed and
equal to Hhe Aumbey_ PassedA
The his keyMaxd
The is"_ keuoord ia Java is a Prede-fined obiact
TeexenCe availa ble inside evexnonStatic method
oacloss.
Oncalling amethod the avaCompile tsans eys
he address of theobject to the Calle method
Tkis addess i s Copied inside the C isgetersnle
Ia sbsrt His" xefexence points tn he abkiect
skich is Cuxently being Used Calt a methad.
Tuso
o majarbene-te o Using his" etexence
1we Carn Use the local Voxiable. by usin the
Some name asthat af the _data membexdafclass.
@RthonWorld-in
2.e n pexlorm intex Constxuctor- Call UsingBi
ReSalvin he isSue of lacal Variable and
data member names.
yample
class Box

Pixate int Lhh


Public Bay (int 1, int bint L)_
his.l= 1
thish=b
hish:hi
Rublic Noid 3ho )

S.o. p lenglhe"+ is.lD:


S.sP u Byeadth +thiz.h
S.0.PC Heiaht ="+his.b)

OsingStatic " keyuuord


o The keusexd3tatic Can be sedat thre e
Stution ie
1 Static data noerabess
2. Static metaads
3. Staio blocks
8tatic classes (Can be used onl oith ested class o
innex cosg and not the Outey clase) CPHhon-korld in
"Static" Data members
O Osing Bually a noa 3toatic data membez3 i3
Cseated.
LallacaEJ
In RAM saly shen an object is
are
O3totic members aye Saved_in RAM oacecthey
indepenclent ohe objechs
o Adata me.mbex iS made Static uwhen t should
displaySame umbex change ox alLobiects
OFoz example,
class Dota
Bath a and b_uill getSpace in
Data
inta Memoxy oheo 0bject of class
intb qets Cxeateds
Lahat if bismade static ?p2
class Docta
Staticmembe
int aj
Stadic iat bi claSS membex

Close useDatto Shased membex

Publicstatic Vaid ooin (shing 2largs


Data ci =neo Datal)
Data d2=peuo DatalL
dlo lo
d.aE20-
Syste m.outt.pxintla Cdi.a "\n"+ d.a)
Ahan-enldin
Featuxes ot "static " Data member
Gele_allacated in RAM os Soon ag_Progam is
executed nespective othe obiect
Only OingleCapuis made
Since the y areobject independent hey shauld he
aCceSSed USing Classname
Data
Datab= yos
Static_member.s axe kept in Pexmaneat enexatiana-
Oreao RAM
SLcal Naxioble3 Cannot be made Static ie, not
inside methad
Gnaxbage Callectoy
we willonderstand his ConCept hrnugh
through
practice program
AP o xeate o closs Calted Employee having
e tollausinq dako Membexs.

1-hJD x 3toriog vnique 1d allocated oeYeru


Employe
2.nome o employe.ee
3. 0 employee
0

Ako provide ollaainq methods-


| . A parametexizedCanstxuctor to initialize name and
aqeID shauld dlsa be initialized in
this Cans
a.Amethod3hou ) to displayID, name oad aqe
3. A Methad ShaLa NextI) ° display ID_a next
n ext

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

hot U3ing any data L oember o the class.


3. hen we have to Cxeate a actoxu method.
clas3 Mymath
Public static iat max (int aintL)

i Ca
Xetuxn a j
else
setusa b
Phen -ovld in
3 Teacher's Signature.....
classTesE

Public static Vaid main (shin laras


int noy MyMa th.may (io, 20)
Sustem.Out.hnEla Mar ig="+max
StemOut rintlo Maximum numbes is "+ MMath . mar
lo 20))

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

Rivate iot oge i


RivateStciog-Aame
riuate Person Cint a,staiog s)

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

Pesson P=neu pex3on(o.g)


Tetuyn_P

class Test

Public 3tatic Naid oain ShsinLlara


Pexson P1P2
P1= PexSon. Cxeate PexsAa 25, "Amit");
P2- PexSon.Create Pex.Sonl29,"Sumtt");
Pi.shoa)
P2.Sho)}

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 ()

Scannex Sc anewSiaonerCSyste m.in


Sustem.out.Piotln"Eatex accaunt id,name and balance
accid E kb.neytIat ()
name E nex tC);
balance nextDauble UL

Public Vaid 3haal)

ystem.0ut.Pxintln(name an'taccid+ "\n"+halance)

Rblie Static Vaid shauaRate)_


Suste m.Out pxintln"Rate ointexest is etate-ainucs
3
Class Tes

Pablic static Noid main(stzing LJaqs)


ethan_Woldin
Hecaunt Ai AeAAecauntL
ACLoaE A2=nes ACcouet
Accauat A3 e neud Accauat O
ALshaul\
A2 Show
A3.sha.l -
Accomat: ShouaRate (

3
Lnberitance
Lahexitanceis one o he mainpillarao

obiect Oxieaked Praqammi.ng


laheritance i s acquiriog pxapexties o othex class
SIhe cass shich inhexits is the desived/sub.class.
The clas3 abich is inkezited 6x eztended i3 the-
base upes cla3s
2Majosbene Inhexitance isCode Reusability
2ahexitance Shouldbe OSed Lhexe thexeis "i3_a
Jelattanship. ike manaqex isan_£nplayee, Mango is a
Auit e te.
Syntax tor Iaheritance
Class LBse Class name

class Dexived class nameextend sLBase class name

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

2.To sesalue methad ovessiding


som the peviousexample,ifaetlocam.e meths
o anagex wa3 also naned ge Sall) thea i
uoR_3ruck in aa iafinite e Cuxgion.
Consructor Callinq inTaheritance
*Constuctorsolloa- o VerySpecial xule in Case
on inhexitance Ondthe ule iathatohene vex the
ohit o dexived class will be Created,the
Constetox o baseclas.s_ ecte 3 s
(RHhan ovld-in
|*Fallowed by the Can stauchor of dezive.d clo33
Tis i3bue onluin Cose ofnon Pasometerized
Conshructos
T oase
clossConsuctor i parometeaizedHeo
Yrogammer ho3 to explicit Callhe baseclass-
Conszuetnx bam he Canstuctor mm the
Cen3ts uctor o deived elas
*fos daing tkie he has touse he keuaoxd Super
Calling. Paxameterized Canshucta1
class A
Public AO.

SeO.P (In Canstuctor ot A*);_

class bextends A

Public BO

S.o.P CIn Canshuctan of B'i

Closs est

Public static Void Main Stziaq 1ors)


B sb Ene B CRthon-Josld-in_
Teacher's Signature..
Calling Parameterized Constructor
T Case o Calling Pazametesiz e d Cansh-
uctox the dexivedclass Canstxucdax i3 invoked.
The 09amme has to explici ty Call the
baSe class Constuttox hom the dexived class
Constru tor 03ing
Exercse _ sin the keyord upes-
Madity the_emplayee Manager pogramin
Sucha way h a t h e method SetData) is_
xeploced ith a paxametexized Canstuctor
Method Oversiding.
A MechanisoUSed by dexivad classto Change
unconalitie O the Same raethod preSeot in base
class
STos neceSSities ar ovexxidinga methad
1. IabexiHonce
2. Pratauee Csa.me VISIbilitIcturn -tpe and nome)
IHis qenerally done hen the de xived d_class
ontsto have moxeSpecialized ox Specific
P
NeySion of the ethad inbesited mthe base closs.
Ovexloading N/s OveYnidinq.
Althaug Ovexlaading and Ovexriding SoundSimilax
bat axe Complekly-
OuesidingCan oaly
Rent
OCCurin Case o inhexi once
obere as OVexladingig dane withio. the Came class
0 e ll as- aCroR3 ohesitance
Ovexxiding Occu hen Pxato tupe (retarn typenome,
ePuthon-orld-in
aruments) o_a methadi3 Same in bath base
and dexived_cla
_clas3ohile, Over lo ading occurS wheo
na me a methed ig Same but He heyiflex in
texm8s ot Oyquments.
Relationship blw Base class reterence
Dexived classobject
Pln Caseoinheritancehee isa Special
Tule eqardin9 Supexclassyefexence and clexived_
class Tetexence
Rule thatthe base_classxeference Can
Pointo1 hold dexivedd clos_obiectbzample
the
J

the mployee clas xefexence Can point to


Manager's obie.ck
Employe e e =neo Mona.qex(O
But the e lVexSe i3 not paRsible the _clerived
class re fexence Cannot paint to base class object
Athough relexenceek Superclas3 CanP
2oiot
oint

to anobiect_o deivedclassbut we Can only


acceSS hoSe hove been inhexied
membes ohich
oma the Super closs.Natthose shich are added
by dexived clos
Slanaple We Can accessna.me and Salaxy but
not bonusahich isSpecifice to Mana gey class
and iS not a part0 Lmployee elaaS.
Employa eEneo Manaqex(
e Sal =120 o0.0
e- name ="Amit Pathan.-orld-in
ebanu3 = looa.o.0 XX
PalymoxphiSm Dynamic Method Dispatch.
The oord palymorphis.cm means Hhe ahili ty to
Lbehavedifferently tn difPerent situation&
palu maa MoTDhS-FormS
We have Seea- polumorphis.m in methad3 throuqgh
J
method s_OVexloadingOnd Oveniding
Noa,oe 8hall See hoowe Can ackieye polumarphic
bekaviar Osing Bingle bage classxetexeaCeaad
Aad

Call diLfeveatmethadso dexived elassshich is


Called.Dnamic ethod dispatch.
*Before ie Can Undexs tond polymorphi.S.o,we need
to Undexsta.nd a Vexu texm in pogramming i.e, Binding

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

private int dim1 Pathaa-Jlarld-io


Psivate int dim 2
LPklie Shape lint dim 1,int dim 2
Lthis.dim1 =dim 1
this.dia = dina 2
|Pablic double oxeaC

etuio O.0

Public Stinq name l)

retuxnOaknoa

Public int getDimiC)


retuxn dimi

Public ink getDim 2.


Tetuxndim2i
33
Lcloss Rectangle_extends shape

Publi Rectangle (int 1,int b)


SupexLb): Pthon-rld-in
Public dauble area)

Tebuxn getDim1(*qet pim 2.:-


Publi c Stainq nameO

return Rectangle "_

class Tsiangleextends Shape


ablic Iiangle Cintb.int h)
Super Cb, h):

Publicdouble axea)

return (o.s getDimi getDim2D


3
Public staing nome2

return Tiangle "

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

the dexived cloa.ss itselfshould Le made ahstrach


and thus derived class obectsCannat be Created..
inal Data_memberS
FAoy data membes whoie Value mustxemain
Onchona.ed thxoughout he proamm and Cannat be
_altered Once initializedthenin this we Can Prei
Such data menaberg oith Keqoord inal
xanmple =
classCircle

Private int adius


Psivate Static ina double_pie =3.l159 i

(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

Publie iaal Vei d displaut)

closs B etends A

Public void display) X


3 3
class AA
Public ina Void display)
3 3 Pathon-arldio
class B ezkends_A-
| PublicVoid pxint( )_

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 >

Ldata type LVasiable> =Value


Zvetun. pe Lmelhadna.me Carqumeat
3
Class A implements Zintes face name

AA class Can ioberit only o Single closs at


atime but a classCan implementmultiple
interfaces
PEaple
ater face Painat

inter face Shope

Puthon-world-io
classCircle implements Paint ,Shape

What's new io interface 22222


Jova8 Onuard3 Special
a eature is added
in interface_Lohich allaus praqammers fo detine
methods in_an intexface.
i an intexface_
Such methads kich axe deined
ase Krowa
o shere a clas h i c h
helps
helps Situatian
implements an iate1ace miohtnot have any logic
to vey side m emethad but hos to orceully
oVexide it sth a blank bady j u s t
defaultvalue
I his Caßeany classwhich implements o n -
interface 1s exempted -om- overriding de fault _methode
Intertace ith Runtime Palsmorphism.
J u s t like_uwe Can use oa obstxactcla33 o
achieye dunamic method dispatch, Similazlywe Can
Se intexface ols.o to achieve palmoxphic
heha vios
Thexefexence ot on intevta ce Can paintto he
obiectS of iisimple mentation Classand Can falL
ho
Hhose metheds ohichLoere_declaxed io_the interfacce
and have been evexliddeaby the closs.
*let us ry the shape example with which we
did using abehact closSeg Q Pythan-world-in
Intexface ith Runtime Palymmphism.
intexface 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

Public _Saing getdame


Teturn Rectanqle"_

Ioheritin Oneinterace into another


Jusike e inhexi a
c lage iato anather Simil
oslyue Con inhezit_an intexface into anather
hros a clas3 Cannot_extend maxe then one
hrough
Puthon-orld io
Lclasso t a timebut on intexface Can
Lextend mas interiaces at o tme
An intexface LannatE implemeat any other
intex face
A clags fileis Created after Compilation
evexu indexface
Erample -
iotexfa ce Shape

dauble Qrea
3 (RtLon-LJorld-io.
intesface Eraure
Strinqname O

iatex face My3hape inpleme.as Shape,iqure

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

Cannot impox it.


manage OULappli-
T became.s easiex for us
Cation oeoe Keep theminside Packa ge3 The
LProgrom in m muh_Oxgaaißed_
uch ond Symmetric.

Stucture of aStandard Java Program


Package Lpackaqe name>i
impoxtt
impoit
ClasS 2clasS =name

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

Publi hatic Vaid roain saing Llars)


System.out.Println Tkis is a message ommyjava Cade)
eate a feldes in bin Dth Same name a3 thato
yaux package_and then Save he le in thealder
Campile Ccl-Abin2jauac mujaua.cade.sTest.java
Erecution C:-\bin>jaa myiavaCodes
CadesTesk:-
Creating twa java iles is the Same Package
Numjaua
Package myjavacades
class Nam

Piuate int a
Bivateint b
Private int c
Void Set (int iintj)_

a i
|bzi
void add)

Catb
aPython-ovld-in
N.aidshoo)

S o PLNumbe13 _are "+a" " L


S.o. P (" Sum is"+C)

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

Publtestatie Vold maiastaing [1axgs


Susem.dut.Pntln"Goad eyening USex ")z2

*Save the abave pngram in the moaio Cdive of


Ou Computer wih name "Gxeetings.java", auo
Campi le the rogram.
Settinq PATH
Sincejavac ison eyeCuta ble fleC.exe) So,
Cxecate it the Dos opexatingSyste.m loaks ax
i nin he Cueat ive Droldar T mt aund,
Do.s look3 or i in t s PATH directory o
tbory+
PATH is Called ao environment Varioable dhieh.
is an
is ano- 03 Naxiable sitbin dhichwe Can
Can Set lacati
on3 of all_those progom3 Shich oe ugant aun-
hom anyuohee in Our Sq3tem.
I n 3hort oe CaaSay hat any pmgrom shose
locaionisadded to Le PATHVoxiable becames
loballyacce SSiblein Out Sugtea
@ Pthon-warld-in.
To Set
To PATH have 2- options
. Tenmposar4 Se Ptingi s done. Via Doswindoua
ond Temains Ontilthe uoindos i 3 opea aenexal
Sunta io Seting PATH is
Set Path =2pathto the clesired lacatian>iZ path Z
Setpath= c:lprsgramfiles\.Javajdk ta.a-abin,poth2
2 esmanet Setting is_donein olloning Seps
Pexmaner Sieps=
a)RigE elick Computex Propexties >
dvanced Sstem SeHing3 nvixonment Vaxiables
neus>

laiable name Path


Nariable Valueclposramfiles Javajdk 13 o-72\
bin path 2
click ok
Creating Package Qutside "bin
lets Create thePreviaus Progam in main drive
Nous instead o Cxeatiogalders' manually,Java's
Campilex is pamextal enonghto Ceate packageS
Tkis Can be done throuqk hefallasing Ammoand
Cijavacd {le name java

Create
Sust tch
a dikctoay
On Cusvent location

The above Commanddoestuo thingS


|Builds a ne la package i package cloesnat ezistJ
Cveate a byte Cadele and adds it e
Package PuHhandorld-io
In ploce o ,"_ e Specil any athey
location Ox drive then_ the- CampBle Creates
Packaa in that particular dsive.
AccesSin classesOutside theirPackage
SIn_odexoaccessaclassOtside ik package
oe haye +o olloLo Cextain Steps
1 We haveto imaxt-
2. T impaata class that class
e ust prh
wihthe keyLsard Puablic In Simple texas Lse Can
Say hat a class Cannat be iopoxted Outside
thepockoge Unlessit is declared utth Hhe ke
the keu=
word publicC.
2On
SOnly
to_access
ymaking
it utside
class a3 publie we aet iakt
he Package and Geate it
Lobject Butto be alle s Call ik aethadsouside
the fackage he mustalsa be declaaed Publhe-
Publc
SOnlyubiemembers o he classCan be accessed
Outsid the Package
I o clas3 ispublic hen thereis anothex
ule uskich progsammer3 have llouo-
hename n ame l j a v a l e hauld be Same a3 the
e
nonm Publie_class
11 oe have lo cla3seSand allo the.m shauld
be occessible outsi.dethe Packase theaall
allHhese
clo sse3 ghauld be Savedia thei a n _Spective
Java les and each java leshauld baye Same
Na me p u b l i c cla 33.
( Pthen= iaorld-in-
Setting CLASSPATH
*OASSPATHus like-PATHianatheieniu
acCe3S
nment Vasiable h i c h 3Set tobe able
Thirdpaxty pnckaqe i.e. thase package3 hich aue
not available in Cuent lo.cation orjavas
java's

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

MethadOveridinq n dVisibilit Mades


When oe Oveide methads o boseclass i n
the desived class , then acceS3 modifiersplay an
impoxtant oleond Java forces proqzamexs
ollou o posiculas Bule.
Rule i that okile ovemiding omethado hoSe
class in itdexived cla.ss eithex uoe Can Keep the
Samedcce.ss madifiex ox 0e Can Use_ less e3hi-|
chve OCCeS S madiffes..
Fos examplei t a ne thod is in default visibilit
in bage class hen akile oveiding itwe Con moke
protected_o ox public but we_Connot moke it
Pivale
Pthon-udorldin
Sin Staticimpaut
This eatu e_ uoas added om Dava 5.
IisLeatuxesocilhtates Joa proqamme to
to
Use 3latic membey3_alixectly ithout Using i s
clas3 nome
T t s conly_advantage s lese Cading i3 requiied
to acceS Hhe stadic membeY3 a the class
Let DSSee oo eYampleto ndexstandndthisaa.
impaxtStatic ava.langSystem.
class Test

Pubke Static Void mainLstting LJargs)

Out psintln (" Hello Usex)

Using Static impast


Only available fox StaticMembex o the class
We Conno Use iE fox nonStaticmenmbe1S of
he clas
T oa laca membes g_preSent ith_he Same
name
n a m e as that othe stotic membexthenthe
local membexDvexlaps the 3tatie membex
t w o we too static meobers o diflerent_cloass
hove he Same name then in Ks CaSe USing themthem
divectly will Ceate Suntax esxoxL

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

Exception Handling Hou java handles it 222line_


T immediately kills the p0gram an the
ohere the exCeption OCCuxS

It_dehoes eS theeason fos exception but is


highly techai.cal and ie not iendly- to an OSeT
he above ocHions ae not ser tiendly
becauge
KI exception Occurs atleasE_thaseincs
Should Cantinue to untokich oxe noteated with with
the excepton
I E toould be muth bettex it Qur progra.m
displaus an eaSy to Understand messaqe aegardinq
J
Teqarding

the eCeptian So Hhot h aex on beConaeadase


@Aplhon-waxldio
about his mistokes.
Exception Handling Keyocs
*Taxo proviade.s s keyuaatd.swhish Can be
Osed totO%ite handle exeptions 1n ro9xammers

Oo waydhich uwIL be_much moxe ien dly


2.Catcb
13. thaoLo
4. thxos
5.inall4
Syntaxntax - y and Cateh

CatchCLException class name Lobiect reBerenee)

Theye Cannot be any ohex ine beuneen trY


Ond a Cotchblockthey shouldbe Cantinuaus
A block Con haveroultiple Cateh blocks
blacks.
AU ceptian.s axepre elefinedclasses in java
Cotch block atches he exception object
then áava 3kou d e fault behaviaax

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.

Pthon orld -io


Java'S suleon multiple Catch
dava hos a
multiple Catch
yera stict
Very
T
u l e while O3in
block.
Thes ulei3 thato Posent_ classof exce
ptionhierarchy Cannot Come betoreik child
class.
This is be Cau3e o Je terenCe o _pasnt class|
LCan easily paint to he child lass obiect ond
hence the ckild class Cateh blockusill nevey uod
rample -
try

CatchTO Cepion e)_ Catch (le Nat iound


Exception )

Catch(Ele Not icund Srephicn)_


CatchCToEception e)

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).

Sustemaout Paiatlo e,get Message () 2


Pythan-woxld-io
Public stzing oshing)
Ihis method is present in the object. clasa
henceio all closses.
TEis is invoked i n Situations
1.In method Piintln).
2.Cantatenatienol objectand Staing
Overxiding the toshing( )" Methad
Example-
Class Person

Psivatea t oge
Pivate Staingname
Public Pexsonlint age staing name)

this ag e age-
thisna me Ename

Class U3e Pexson

Pablic statie yoid moio (Stsinq I args2


PesSon pene o Pexsan(21, Amit ");
System.Outa println (p)

PeySon Ql5dh9442 This is Called Hashcode


oPthbon-arld-io
AA hashCadeis an unique numbex gene yated
hom Qny object lhis is whot allouos objects to
|be stoxed/eieved 9uickly
But it is of no ose t o pro9y om Me3 Ox Oser.
On passing okjectxeieeoce tO PintloO
ethod, tosthing)is invoked. Since we have nat
Cvesnidden itSa the base class Nexsion geta
Called and hence e qet hoshcade in etun
Sobyovessidiog+ he tostaing() method we
Can iniomatio elatedto a Speciki.c classs
Ond not hashcode.
Using Hhros"_keuord
Using
ava exception& OCcux on JVM?s choice
- e anythin9 0gainstt Hava's How.Example it
deno.minatoxi3 O then avaitself geneyate s
Ahemetic xception
But , in Sonme Situotian oprosannaers may ant
o genexate x_deine exceptians_on their choice
do thiS, jovaprovides Oshe key d throul
IHs Syntax is
thra io Same exCeptian class object efexence >;
anple
AP to acCept tuwo integes aom UBes H
the denominoatox entexed is o hen Shawava's
ezCeption mes.sage annd i the numexatos enter-
ed is o then qenexatee o Ouon exteption
disployed Numbexactor Must be posittve"_
Putaon-sorld-io
classificatian o Eeceptions
Checked Exceptians Unchecked Exceptians
Exce ption3 ox which rceptions or ich
ava tor Ce s the pmgram=java nevex Compels the
mer handle E
to eithex handle Programmex to hand le it._
y-Cateh a the Tkeprogsa.mme oould
Osing
ProgammeX must_intoxm o be Compiled and execu-
oazn he Calles Hhe ted by aua
aethod that_his Cade is Ësample 4he class
hot handling the checked Runtime bzception ànd
exeption all its derived classes
The ing iven is fallia thsCatego1
through he keqsord thxaLas.|
J USed inHe method's
proto type along with excep
ton class name
Checked Erception
Thi3 in javaisCalled handle eleclare xule.
Te Calleyalso has2 optionseithey s e t
Catch o the keqwosd throus
Hevexy
eyex methad use thxowsthen oltimately
he esponsibility gpesto the JVM ahich ill_
Solla Le stondaxd naechanismo handliog
e eception
All exCeptionsLskich axe notdeived classes o
Runtime Bxception all in this CadeqmuLike.
SOL Bcetion,LoEzception,Intemupted Exception etc
Puthon-s0ld -io
Programmex cdeined Customized Ex.ceptions
SMany time3 in Some Situation3 a pragxa.mme
migkt not find any Pre.deiined ezception eloss
be USed whthoo
Dfox eample, in Cose o a baaking 0pplication
the methad uithdrau hos Same Minimum limit
tke 500 e3e an eCeptionoill generate J o this
Co se theye o predellaed jiavalsexleptian
Class
2SojoaVo oduise s_ to design Our own ezCep
classesSuch classes ae Called Cudtonized
exception elass.
T o Cxeate an exception classiaour oon
exception class
L1.Provide a paxameterized CanstuctorSa that
exception oe3Sage_Con he Set nd POSSed
passedon to
paxentclass's Constsuctor.
2 . Lohesit O x _ e y t e n d Ony thepxede iined
exeption class inOua SsoesCeptioo class.
Te Castamized exceptions be Came checked
ezfeption inbeit_the base closs EXCeptioo
Since, Only Kuntime bxceptioo and is_chila
classes are onchecked innatue So pxogammex
has toSpeciiicaly inhexit anyane o a3e
to Cyea te ond Onchecked ex cepton Class.

CPuthan-world-in
Using
Thexe
the keqhord finall
axe Cextain stodeoe.cds in Oux proam
Lohosee2eccution Cucia
So that before Ous

am gets texminated these statme.ats must


be Cyecuded.
Sample, if e have ape.ne.d a file ar ony
dada base Lonnection Cnd betex the Bagram.
Campletes e ecutioa the
i le Ox donta base
Cannection shatld be Closed.
La Such Case java Suggests Us_ to Loxite
Sach 3tatement in ablack hose eecution_ is
Qua ranteed and ach blo.cks are
Created Osing- the keyooxdinally
H no exception Accux3 inal block i
excecuted.
T aa exception Occuxsinside black
he z
ond its Catch has definedin SuchCose
also inallyise executed
en i no Cateh block is Osed theo alsa
he ioally block executed.

Moxeoves, oxy black ie xequixed osan inal


olock. 1 an uside q
eiception block
OcCux3
in Hhat Case finallyblockis not Cxecute o _acd
also shen 4he method Sstem-exit0 is Used
Syntax
Catchl---)
@Pythanord
Multi Catchfeature
oOe
e Caa
Can Sea Single Catch to handle

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

>DEHeyence n- iaitialization looo


Stinq S1 eneu Shing ( s k ) ; S|looo
SingS2=ne stiin' (Sk") S, )2.o0o 2000

shiog S3 ="sk looo loo


S3
Shing. S="Sk
looo
S4
Conshuctors shing
To check Hhe memoa diagram we Can ampo
4he object e exeneeS
ShingS1e0eud Stsinq CSky)
Sting S2ane Stxin(sky")
shing S3 ='Sk
Shing S ="sky"
System.out. Piintln St==s2);|
stem.out.fxintln ( S3==S)
shing Cchax [1)= anveyts o chara.ctex ara to
to
shing object.
Sting Cchax LJI,int1,iaB )
int1-starting indez @Puthon- old-in
int -lumbex ol chaxactexs o e Canuextedioto
Sthiog
cha asC]:2 H','e' 1,1,o'
Dshingsnewshing laxn,o,4
System.out. Printlnl) HellL
ja anyini n (deuble quates) is Can
Sidexed t shing Stag-
Shing to he Pye cise aStsiag-
obiect
Syample Bhopallangth -
Methads ot Shing class
Pullic hasleanequals (abiect)
Dexived hom object
Class t Coopaxe obiect eievenceS Lhen dbject
o anu othex class is paSSedBat itCoapaxes the
Shing ohen a gtsi09 iS pasSed. So, evey- class Can
Oveyiide equa in_ik onLiay
Public boaleanequalsTqnaxe Caseshing
Method belongs to Shing class andinoes
Case Sensitivity
Pulblicint Campare lo (Shioq) Methad belongs to
and Cempaxes hing and etuxos_o4
stingelse differenCe o theiy AsIls
Staing class
ue
Public int Corapaye Tålgnae.cCase (stinq)
Similosts above method but ignoes Cose Sensitivik
Publi int indezof int)-
Returns indeo Hhechaxacte preseat in the staing
shich is pasSed in the arqume
J
nt,TH not ound retua
not

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

fubli c int lastIndesallsthing:Retuns the index


Loith in this Shing thesiqhtaaSt aceurenCe
oo he Specificd Subshing.
PuLt shig Subshing.(iniint) Retuxns a neus
sting that is a Substhing sE t i s Sthing The
g_and
i s t argumeat is 3taatingidexor Substain9
azqument_i3 end inde x -1_o the
the Substaiog.
Sacand
Pythen-uaxdin
Publi Staing Substainglint)Retxns the sBaing.
iepre Sentationo ot thepasSed data pe axqumeni
9Public statc Stsioq Value of anypzimitive dadatypel
Retuans the Shing peSentatian o the passed
data ype Qrgumeat.
Public shinqSubshing Ciat): Retuins he Rubstsing
o m _ n d e PosSe.d as argument: ttL e last
inde the Stsing
Publtessng touppex Casel)= Canvexts all he-
Charactey3 the shing- ppexCose

Yubli c ShingtoonexCose ( Convext e


alll he
claxacess o He he sting ts losoex Case
CLASS Sting Btler
The objects_of closs Stai.ngBuex inJaya are
imutable i.e Cantent ao obectCan be (hanged
without Ce oting a ne object.
StingBute is QSed wben data o a class
moy Change in futuxe fzample, Salaxy a an
mployee
Stinq Butle also has Some methodsos that
Shinq that
o
stin
theclass
Stiag ezcept Sone o
StaiagBuler is alsoo pre sent io e
te m
pac kage-
java lang
Constructovs o shinqButler.
PbliShingBufler( Caeates an object_ith
Size initalized si t
ic shing Butfes (int) Cseateso skio9 hutle
@ thon-wold-in
with Speciied Capacity in the asqument and
with nullchaiactex S.
initalized
Pablc Sting BuiieshiogD-Ik obiect is Cxeated\
and inidialized with theStiing pa.sse.d in the
aqument and is appended with 16_null charoacters
o2.
Public nt CapacituO-Iis methad xetuxn3 the
| Cayent CapacityOsin this me thadwe Can Contim
t h e exba G 3eVed by java
Chasar ters
ublic Void enSuxe Caparity (int)- Locreas eg
Copacitq to ax qume nt Pa33ed.
Pulblic sbiegBuffe Dppend Lshio9)An ovexlooded
anction and ppend anydata lype
StingBuftes S new Stin Butlez ('India");_
S.aPpend
S. appenaC i s my Couotry)
Sqstem.out Pintlel s)D
Yublic Stsiog Buke yeveySe () As_the name

Sugge 3s_i t the- Caiginal Sing


eveySe 3
blic icshiogBulles xeplace CiaYint.sthind
1is ae thod KeplaCes h e chara cterS
in a
Substins a Hhis Sequence with ckazactexs in
e Speiiied 3hing
Staing Buf iea S=ne 3tinqBuBier (" Bella aosld');
S.eplace 6 , 1 ,"India");
Sustem.out Paintlo l )i Hella Ladia

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

So once W e have Cxeated|by natue 3o oftex_Ge-


ation weCan inCyeaSe
the aviay_se Can not
incre oSe ox decre ase it's or deCrease their size .
Size
Aroy Caa. hold PrimitivesCalle.ctians dant oork
ag welL aS objects. wth primitives they only
Can hald obiects
Anay3 Can hold only- Colle ctioo3 Can hald
homogeneoo> data both_homa 9eneald3 aS wel
aS heterogeneaOs_data

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

Sets -Cannot _Cantain_duplicateg and Povide


xandom totheix element
Maps Connect Oniue keys otth Values,
Phovide 1ando.m aceess toit3 keys
Imprtant Method ss af Callectians
1be Callectiorn interface is oe_at the xoat
inter face3_a the ava Colle ctian classes. The
enexal methads list al the Cllection interiace is
. baaleaa add Labiect obi)
2 Void dleay)_
3. boalean Cantains (okiect obi
boalean equals abject ob)
5. nt hash CadeC)
6. baalean is3Empty
teatok iteratar
8 boole.an remave Cobject abi)
nt Size
@ Puythan-warld-in
Collection V/s Callectionas
*fox beqianey 3 thexe
is a paint
paint a Conusioa
xe Qoroling e texm 3 Collection and
the Collection s
Callection ia aua is an iatexiaceauailable
inthe Packag jaNauti and i t acts_as
the Supes otexHace Yox al Callectiao Closses
Eke Amolistiakedlist Hoshset etc
Callecans is class in he Package
jaya. Util ahich Contains Nasiaus Static methadS
pesfoxmin9 utility OPe xatons on allec tion
LClas3e3
Same o t s populosme thad3axe Sostc
Capy) binarySeaxchO etc.
Tke List ioterface
Klhejaua.ukLLisk iatioce is a Subtype
ofthe jayabl.Collection 1inteaface _ànd xepresents
o n Odered Collection CSometimes Calleda
Sequence)
meons ue Can access the ele ments o a
sE in a Specific ode Qnd bs an inde y_oo
alloas duphcate okiects.
KEachelemeat isinSexted ond aCCesSed in
the lis USing fs index
lomplenentatian classes_of "List"_
we Can chaose betuieen thehllasin List
imple.mentatiansin thejavo Collectians API
9Java.util fAxosList
PAthon-Noxd in
Java.util kakedList
Java t i l , Vectox
Javautil stackk
The "hraylist"class
Amoy List imple mcnts the List iodeitace
Array i s t is Cyeated oith an iniHal Size

hray List Capacitq axo.s automak.cal


TLallons dupli.cateelemets
Tsertioa Ordes pxe Sex Ved in the faraylist
Creating The "Anayist" Object
Arauist. Can be CaeatedL in 2 ays
upeDnsaie
AND
ype Safe
Tgpe Unsate AvrayList
pe Onsale Anayist Can beCreateda
Shouan belao
Aroyist obi=neuo AmaylistO
Athougathe Oxe eagies to Ceate but oe
Caonat check ohat kind f data we axe
addino i n theAxxaylistL
obi add "Amit")_
obi.add (25);_
obi add ue)
All He above lines aill SucceseitullyCampile
and ua-
Pythoniarld=in
GPe Safe Anaylist
Ppe Safe Arnaylist Can be Created as Shaaa
belouoa
Axxoylist 2staiog obj =nes AnaylisLshinga0
SThe is clleddiamend Operato inava Ova

Ond Uas Lataduced rom Aava 7_nuoasdS


IH tells theCampilex o only allan pxo9ammex-
to add Shing Valuea in the AaybiSt
othe-upe of Value Cannot o added
in he AnayLigt Ond i we t y t o do So, the
Campiles oilL qenexate natax

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

Checking Size ot thraslist


S1zeoon
a_anAraykist meanstotal number at
elements Cumeatly present in it.
T xehiere SIze of an aylistwe have a
methodCalledS1ze ( whose pratatype i s
public int Size()
Yoi e j n t ne citieS.Size Python-orld-in
Exerctse1WAPto Stoxe names offist fous
manths inthe Hxayist ond them pint them back

Retrievinq itemErom Amaylist Using Enhanced


DweCan save1Se O nraylisE _alsa 0sing-
enhanced ox Loop
(sing EnhonCed
os (shing itemctica) i
System.out Psintn ("iehieved element: "+tem):

Seaxching An Element in ArayList


Sometimes we need to check_ahethexao element
exists Anaykist or not_
r this puxpa3e eCan 0Se
For Cantains) mne thad o
java antainsO_method takes tpe abiect deined
Ra the ArayList eatioo ond yetuxas ue i
Ahe isE Contoins the Specified elemeat

boolean atund =Citie&. Contains (("Bhopal?);

Removin an itemrom ArayList


There axetuwo usayso
Theye emaye Qnuelement a m
Anay List in Java
The method o be Calledisemove )
This oethadhos 2Vexsions
Python ovld-io
rototype
Publi c boaleaa emove Cobiect)
Public Obiect remave(int)
Can eithex rem.ave anelement based oo
t iadex OX Providing ohiect itse
t e S e moVe (o)
Cikes, XemoNe ndose

Ihaductian To Custam Amaylist


ohat is a Castom AnxayList2
2A_Castom rayist is an rayList Lohich
Con hald
Can obie.cts ào pagnaeapnex_detined closseS
Eor example Suppo8e haveo class dled
Emp
Emp and lae Want to Stoxe Eap_Obiects in
the -Araylist
henSuch aa Araslist aill be Clled
CoLstom AnreylisE
Cxeating- A Custam rayist
Hoo do Ae aeate o Costam araylist2
To Create_a Custom maylist,de ise he
llaLing
Shyntax
nayLisE2name o ou Class 2 aeEName=0eo hay iste
ox e
ray List Emp>empListenea Axroylist e>):

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.

What is Natural Ordex-


NatuTal odey oeans the deiault 3ax ting odex
hich lloros
he ist Consists a shing elemente 1t oi
e axted ato alpha betical orde
tCoatains inteqess uil be 3axted in
numexi c Oxdex.
Puthan-warld-in
Iit Consists_o Data elements iwill be
Sosted into
Chranalagical Order.
Ho TSort Custam frayList 2
But hen Ae Ca he
Callections class and pass
Sort)methadot
it ou Emp a
then i l generate an eixo
Loao Cao a ues.3 why
This be CaSe e haye nat defined any
Soatin9Oxdex o Oui Emp obiects |
Solution
T Salue thispoblem ue Dill have Supplu
Hhe intosmaton to Collecti.an3 ClassabouthaLa
to Soxtthe Emp ist
This dooe by implementin9 n intexfa.ce_Called
Compasable andoVeuiding i t method Called
Compase Tol)which hasi the llaising pototupe
Public int Lampaxe lo Cobiect)

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

SoMeErba methads of Tree Set


Since eeSetimple.cme.ats Navigable Set and
Soxtedset intexfoce.sit hos_Some _more methods
a3 Compaxed to Hashse b Some t s lex
important me thods Qxe
Publi.c obiect lasEC+Retuxns the last Chiahest)
element Cuxxentlyin. this Set.
Pahieobiect ixtC) Retuans the dirst (launest)
@Python-Aorld-io-
elemenf
Cuxenty in this Set.
Publi. obiect locser Cobiect) Ketusas h e qreatest
element in his et Rictlyles3 haa theaiven
elemeat Oz oull i thexe no Such ellement
the least
EPabliccbject higkex Cobiect): Retuxns
element in thi Set akichy grea tey than the given
elemeat ox_nulll iP there i3 noSuch element

Hashset Vs ree Set


HashSet 18 much astey than Tree Set aS h a s
Constant-tm maSE_ opexatians ike add
toy
emoV e and Cantoing but oHexes no oxdeing
uaxonteeg like see Set.
Iree Se oters a tea ha.ndy methodsto deal
Lsith_he Ordexed e t ike FixsHO last(2, etc
LdhichOxenot present i n Rashget

PyTHON-IAORLD-IN-
FREE NOTES FOR
BEGINNER

PYTHON
LECTURE 1-INTRODUCTION
Today’sAgenda

• Prerequisites Of LearningPython

• Necessity OfProgramming

• What Is Python ?

• WhyAnd Who Created It ?

• What Python Can Do?

• Why Should ILearn Python In 2020?

• Important Features

• Course Outline
WhatYou Should Know ?

To start learning Python , there is no strict pre-requisite

No specific programming language knowledge is needed.

Just basic knowledge in C/C++ is more than sufficient


Why Do We Need Programming ?

• To communicate with digital machines and make them


work accordingly

• Today in the programming world , we have more than 900


programming languages available.

• And every language is designed to fulfill a particular kind


of requirement
Brief History Of Prog. Lang

Clanguage was primarily designed to develop “System


Softwares” like Operating Systems, Device Drivers etc .

To remove security problems with “C” language , C++


language was designed.

It is an Object Oriented Language which provides data


security and can be used to solve real world problems.

Many popularsoftwares like Adobe Acrobat , Winamp


Media Player,Internet Explorer,MS Office etc were
designed inC++
Courtsey:http://www.stroustrup.com/applications.html
What is Python ?

Python is a general purpose and powerful programming


language.

Python is considered as one of the most versatile


programming language as it can be used to develop almost
any kind of application including :
 desktop applications
 web applications
 IoT applications
 AI , MLand Data Science applications
 and many more . . .
Who created Python?

Developed by Guido van


Rossum , a Dutch scientist

Created at Center For


Mathematics and Research ,
Netherland

It is inspired by another
programming language called
ABC
Why was Python created ?

Guido started Python


development as a hobby in 1989

But since then it has grown to


become one of the most
polished languages of the
computing world.
How Python gotit’s name?

The name Python is inspired


from Guido’s favorite Comedy
TV show called “Monty
Python’s FlyingCircus”

Guido wanted a name that was


short, unique, and slightly
mysterious, so he decided to call
the language Python.
Who manages Python today ?

From version 2.1 onwards ,


Python is managed by Python
Software Foundation situated
in Delaware , USA

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

Python is used for GUI


apps all the time.

It has famous libraries like


PyQT , Tkinter to build
desktop apps.
Web Application InPython

We can use Python to


create web applications
on many levels of
complexity
Famous Websites Developed Using Python

There are numerous examples of popular, high-load


websites/webapps that have been developed using Python.

Here are some of the most popularof them:


 NASA
 Instagram
 Udemy
 Spotify
 Mozilla
 Dropbox
And above allYouTube
Web Application InPython

There are many excellent


Python frameworks like
Django, Flask for web
application development
Data Science In Python

Data Science is about


making predictions with
data
Some Examples

How do you think Super


Market stores decide
what are the items they
should club together to
make a combo?

How it happens ?

Answer: Data Science


Some Examples

Have you noticed that


every time you log on to
Google, Facebook and
see ads, they are based
on your preferences

How it happens ?

Answer: Data Science


Data Science In Python

Python is the leading


languageof choice for
many data scientists

It has grown in popularity


due to it’s excellent
libraries like Numpy ,
Pandas etc
AI &MLInPython

Machine learning is a
field of AI (Artificial
Intelligence) by using
which software
applications can
predict more accurate
outcomes based on
historical data.

It is heavily used in Face


recognition , music
recommendation ,
medical data etc
Use Of MLInCOVID-19
AI &MLInPython

Python has many


wonderful libraries to
implement ML algos like
SciKit-Learn , Tensorflow
etc
IoT In Python

The Internet of Things, or


IoT, refers to the billions
of physical devices
around the world that are
now connected to the
internet, all collecting
and sharingdata.
Forexample:
 Alightbulb that can be
switched on using a
smartphone app is an IoT
device
IoT In Python

We can build Home


Automation System and
even robots using IoT

The coding on an IoT


platform like Raspberry
Pi can be performed
using Python
Hacking InPython

Python has gained


popularity as preferred
language for hacking.

Hackers generally
develop small scripts and
Python provides amazing
performance for small
programs
Why should Ilearn Python ?

3rd most popular programming

Fastest growing language

Opens lots of doors

Big corporates prefer Python

Means , PYTHON IS THE FUTURE


Who uses Python today ?
Features OfPython

Simple

DynamicallyTyped

Robust

Supports multiple programmingparadigms

Compiled as well as Interpreted

Cross Platform

Extensible

Huge Library
Simple

Python is verysimple

As compared to other popular languages like Java and C++, it is


easier to code in Python.

Python code is comparatively 3 to 5 times smaller than


C/C++/Javacode
Print Hello Bhopal!

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

Python has very strict rules which every program must


compulsorily follow and if these rules are violated then
Python terminates the code by generating “Exception”

To understand Python’s robustness , guess the output of the


following C/C++code:

int arr[5];
int i;
for(i=0;i<=9;i++)
{
arr[i]=i+1;
}
Robust

In Python if we write the same code then it will generate


Exception terminating the code

Due to this other runningprograms on the computer do not


get affected and the system remains safe and secure
Supports Multiple
Programming Paradigms

Python supports both procedure-oriented and object-


oriented programming which is one of the key features.

In procedure-oriented languages, the program is built around


procedures or functions which are nothing but reusable pieces
of programs.

In object-oriented languages, the program is built around


objects which combine data and functionality
Compiled
AsWell As Interpreted

Python uses both a compiler as well as interpreter for


converting our source and running it

However , the compilation part is hidden from the


programmer ,so mostly people say it is an interpreted
language
Cross Platform

Let’s assume we’ve written a Python code for our Windows


machine.

Now, if we want to run it on a Mac, we don’t need to make


changes to it for the same.

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.

This makes Python a cross platform language


Extensible

Python allows us to call C/C++/Javacode from a Python code


and thus we say it is an extensible language

We generally use this feature when we need a critical piece of


code to run very fast .

So we can code that part of our program in Cor C++ and then
use it from our Python program.
Huge Library

The Python Standard Libraryis huge indeed.

Click to add text

It can help you do various things like Database Programming ,


E-mailing ,GUI Programming etc
PYTHON
LECTURE 2
Today’sAgenda

Version History , Downloading and Installing


Python

• Version History

• Python 2 v/s Python 3

• Different Python Implementations

• Downloading And Installing Python

• Testing Python Installation


Python VersionHistory

• First released on Feb-20th -1991 ( ver 0.9.0)

• Python 1.0 launched in Jan-1994

• Python 2.0 launched in Oct-2000

• Python 3.0launched in Dec-2008

• Python 2.7 launched in July 2010

• Python 3.6.5 launched on March-28th-2018

• Python 3.7 launched onJune-27th -2018

• Python 3.8.0 lunched 0n Oct-14th -2019

• Current latest (as of now) is Python 3.8.5 launched on Jul-20th -2020


TheTwo Versions Of Python

• As you can observe from the previous slide , there are 2


major versions of Python , called Python 2 and Python 3

• Python 3 came in 2008 and it is not backward compatible


with Python 2

• This means that a project which uses Python 2 will not run
on Python 3.

• This means that we have to rewrite the entire project to


migrate it from Python 2 to Python 3
Some Important Differences

• 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

• So to prevent this overhead of programmers , PSF decided


to support Python 2 also.

• But this support was only till Jan-1-2020

• You can visit https://pythonclock.org/ to see exactly how


much time before Python 2 has retired.
WhichVersion Should IUse ?

• For beginners , it is a point of confusion as to which Python


version they should learn ?

• The obvious answer is Python 3


Why Python 3?

• We should go with Python 3 as it brings lot of new features


and new tricks compared to Python 2

• Moreoveras per PSF, Python 2.x is legacy, Python 3.x is


the present and future of thelanguage

• All major future upgrades will be to Python 3 and , Python


2.7 will never move ahead to even Python 2.8
Various Implementations Of Python

The Python language has many popular implementations

The word implementation means the tools/software which


are used for the execution of programs written in the Python
language.

As of now Python has around 26 implementations , but the


most common are: Cpython , Jython , IronPython and PyPy
Difference Between Machine Code
And ByteCode
Benefits AndDrawbacks
Of MachineCode

The benefit of machine code is that it runs very fast because


it is in the native form i.e a form which is directly
understandable to the CPU.

However the drawback is that it cannot run on another


platform which is different than the platform on which the
code was compiled.

In simple words , the .exe file of a C program compiled in


Windows cannot run on Linux or Mac because every platform
(OS+CPU) has it’s own machine code instruction set.
Benefits AndDrawbacks
Of MachineCode

C/C++
Source Code

Turbo
Compiler

Machine
Code Windows Linux
Difference Between Machine Code
And ByteCode

Bytecode

Bytecode is an intermediate code but it is different than machine


code because it cannot be directly executed by the CPU .

So whenever the compiler of a language which supports bytecode


compiles a program , the compiler never generates machine code.

Rather it generates a machine independent code called the


“bytecode”.
Difference Between Machine Code
And ByteCode

Now since this bytecode is not directly understandable to


the platform(OS & CPU) , so another special layer of
software is required to convert these bytecode instructions
to machine dependent form .

This special layer is called VM or Virtual Machine.


Difference Between Machine Code
And ByteCode

Python is one of the languages which works on the concept


of VM.

Thus any such platform for which a VM (called PVMin


Python ) is available can be used to execute a Python
program irrespective of where it has been compiled.
Program Execution
in Python

Source Code

Compiler

Byte Code
PVM PVM PVM
MacOS
Windows Ubuntu
Benefits AndDrawbacks
Of ByteCode

The benefit of bytecode is that it makes our program


platform independent i.e. we only have to write the program
once and we can run it any platform provided there is a VM
available on that platform

However the drawback is that it runs at a slower pace


because the interpreter inside the VMhas to translate each
bytecode instruction to native form and then send it for
execution to the CPU.
CPython

The default implementation of the Python programming


language is CPython which is written in Clanguage.

CPython is the original Python implementation and it is the


implementation we will download from Python.org.

People call it CPython to distinguish it from other Python


implementations

Also we must understand that Python is the language and


CPython is it’s compiler/interpreter written in Clanguage to
run the Python code.
CPython

CPython compiles the python source code into intermediate


bytecode, which is executed by the CPython virtual machine
also called as the PVM.
Jython

The Jython system (originally known as JPython) is an


alternative implementation of the Python language, targeted
for integration with the Java programming language.

Jython compiles Python source code to Java bytecode and


then sends this bytecode to the Java Virtual Machine (JVM).

Because Python code is translated to Java byte code, it looks


and feels like a true Java program at runtime.
Jython
IronPython

Athird implementation of Python, and newer than both


CPython and Jython is IronPython

IronPython is designed to allow Python programs to


integrate with applications coded to work with Microsoft’s
.NET Framework for Windows.

Similar to Jython, it uses .Net Virtual Machine which is called


as Common Language Runtime
PyPy

PyPy is an implementation of the Python programming


language written inPython.

It uses a special compiler called JITC (just-in-time


compilation).

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

Python’s downloading and installation is fairly easy and is


almost same as any other software.

We can download everything we need to get started with


Python from the Python website called
http://www.python.org/downloads

The website should automatically detect that we’re using


Windows and present the links to the Windows installer.
Downloading And
Installing Python
If you have Windows 32 bit then download the installer by clicking
on the button Download Python 3.8.3
Downloading And
Installing Python
But if you have windows 64 bit then scroll down and select python
3.8.3 from the list
Downloading And
Installing Python
Now go to the Files section and select windows x86-64
executable installer
This will download the installer
Downloading And
Installing Python
Open the downloads folder and run the file python-3.8.3.exe (if you are on
32 bit) or python-3.8.3-amd64 (if you are on 64bit) by right clicking it and
selecting run as administrator
Downloading And
Installing Python

Once the installation is over you will get SETUPWAS


SUCCESSFUL message
Testing Python Installation

To verify that Python is installed and working correctly, do the


following:

 Open the command prompt

 Type the command python --version

In the output we should see the Python version number as


shown in the next slide
Testing Python Installation

To verify that Python is installed and working correctly,


do the following:

 Open the command prompt

 Type the command Python –version

In the output we should see the python version


number
PYTHON
LECTURE 3
QUIZ-TestYourSkills

1. What is the correct syntax of print statement in Python


2.x ?

A. print
B. print()
C. Print()
D. Print

Correct Answer:A
QUIZ-TestYourSkills

2. What is the correct syntax of print function in Python 3.x


?

A. print
B. print()
C. Print()
D. Print

Correct Answer:B
QUIZ-TestYourSkills

3. Python is case sensitive

A. False
B. True

Correct Answer: B
QUIZ-TestYourSkills

4. Python is a compiled language or interpreted language ?

A. Compiled Language
B. Interpreted Language
C. Both
D. None Of The Above

Correct Answer:C
QUIZ-TestYourSkills

5. APython code is normally smaller than the


corresponding Clanguagecode

A. True
B. False

Correct Answer:A
QUIZ-TestYourSkills

6. APython code runs faster than the corresponding C


language code

A. True
B. False

Correct Answer: B
QUIZ-TestYourSkills

7. What kind of code Python compiler produces ?

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

9. In CPython , the bytecode is converted to machine


instruction set by

A. PVM
B. VM
C. JVM
D. Bytecode Converter

Correct Answer:A
QUIZ-TestYourSkills

10. Python 3 is backward compatible with Python 2

A. True
B. False

Correct Answer:B
QUIZ-TestYourSkills

11. Support for Python 2 has ended on

A. 31-Jan-2019
B. 1-Jan-2020
C. 31-Dec-2018
D. 31-Dec-2019

Correct Answer:B
QUIZ-TestYourSkills

12. Arrange the following in descending orderof speed of


execution

A. CPython , PyPy, C
B. PyPy, C,CPython
C. CPython ,C, PyPy
D. C,PyPy,CPython

Correct Answer: D
QUIZ-TestYourSkills

13. Which implementation of Python contains JITC ?

A. CPython
B. PyPy
C. Jython
D. IronPython

Correct Answer:B
QUIZ-TestYourSkills

14. What is the output of 10/4 in Python 3?

A. 2.0
B. 2.5
C. 2
D. None Of The Above

Correct Answer: B
QUIZ-TestYourSkills

15. What is the output of print “Python Rocks” in Python 3?

A. Python Rocks
B. Python
C. Syntax Error
D. None OfThe Above

Correct Answer:C
QUIZ-TestYourSkills

16.Which of the following is not a Python IDE ?

A. PyCharm
B. Cutie Pie
C. Spyder
D. Visual Studio Code

Correct Answer: B
QUIZ-TestYourSkills

17. What is NumPy?

A. Alibrary of Python for working with large and


multidimensional arrays
B. Alibrary of Python for Artificial Intelligence
C. APython IDE
D. None of the above

Correct Answer:A
QUIZ-TestYourSkills

18. Python is a statically typed language

A. True
B. False

Correct Answer:B
Today’sAgenda

Developing First Python Code

• What Is Python Shell ?

• Using Python Shell

• Writing Python Script Using Notepad

• Running Python Script

• HowToViewThe Bytecode File ?


Two Ways Of Interacting
With Python

• In the last chapter, we have installed Python.

• Now let’s start using it

• We can use Python in two modes:

• Interactive Mode

• Script Mode
Two Ways Of Interacting
With Python

• In Interactive Mode, Python waits for us to enter


command.

• When we type the command, Python interpreter goes


ahead and executes the command, and then it waits again
for our next command.

• In Script mode, Python interpreter runs a program from


the source file.
The InteractiveMode

• Python interpreter in interactive mode is commonly


known as Python Shell.

• To start the Python Shell enter the following command in


the start menu search box:python

• Doing this will activate the Python Shell and now we can
use it for running python statements or commands
The InteractiveMode
The InteractiveMode

• What we have seen on the previous slide is called Python


Shell.

• >>> is known as python prompt or prompt string, and it


simply means that Python Shell is ready to accept our
commands.

• Python Shell allows us to type Python code and see the


result immediately.
The InteractiveMode

• In technical jargon this is also known as REPLwhich stands


for Read-Eval-Print-Loop.

• Whenever we hear REPLwe should think of an environment


which allows us to quickly test code snippets and see results
immediately, just like a Calculator.

• Some examples of commands / code snippets to be run on


shell are shown in the next slide
The InteractiveMode
The InteractiveMode

• Not only mathematical calculations , we also can run some


basic python commands on Python Shell

• For example: Type the following command:

• print(“HelloBhopal”)

• And you will get the text displayed on the Shell


The InteractiveMode

• We must remember that Python is also a case sensitive


language like Cor C++.

• So the function names must appear in lower case ,


otherwise Python generates Error , as shown below
Getting Help FromShell

• We can also use help on Shell for getting information on


Python topics.

• To do this we need to type help( ) on the prompt string on


the Shell
Getting Help FromShell

• Now we get help on various Python topics .

• For example to get a list of all the available keywords in


Python , we can write the command “keywords”
Quitting Help

• To come out of help mode , we just have to strike ENTER


key on the prompt
Quitting Shell

• To come out of Python Shell , we have to type the


command exit( ) or quit( ) on the prompt string
The Script Mode

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.

So if we want to execute same set of statements multiple times


we will have to write them multiple times which is a difficult
task.

In this case it is better to write the code in a File , Save it and


then Runit

This is called Script Mode


The Script Mode

In this mode we take following steps for developing and running a


Python code:

 Write the source code

 Compile it
( Generation of bytecode )

 Run it
( Interpretation/Execution of the bytecode )

As discussed previously , step 2 is hidden from the programmer and


is internally performed by Python itself , so we just have to perform
step 1 and step 3
The Script Mode

For this do the following:

 Create a directory by any name at any location . I am creating it by the


name of “My Python Codes” in D:\ drive .

 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

 Now open the command prompt , move to the folder My Python


Codes and type the following command:

python firstcode.py

 Here “python” is the name of Python’s interpreter which will run


the program firstcode.py
The Script Mode
What Happened
In Background?

• When a Python program executes, a bytecode compiler


translates source code into bytecode.

• This bytecode is stored in RAM and not visible to us.

• After the bytecode is produced, it is then processed by the


PVM (Python Virtual Machine a.k.a Python Runtime or
Python interpreter).

• So the Python compiler produces bytecode in bulk while


the Python interpreter inside PVM performs line-by-
line execution of the bytecode.
What Happened
In Background?

• So in our case the following sequence of events will take


place:
1. Programmer writes the source code by the name
firstcode.py
2. Then he/she runs the program using the command:
python firstcode.py
3. The Python compiler internally generates the bytecode
file called as firstcode.pyc
4. Then the Python interpreter gets invoked and it reads this
bytecode file and converts each bytecode instruction to
the underlying operating system’s instruction set and
sends it for execution to the CPU
5. Finally the programmer then sees the output
What Happened
In Background?
Can We See The Bytecode File ?

• Yes, we can force Python to save the bytecode file for us so


that weview it.

• To do this we need to write the following command


python –m py_compile firstcode.py

• In the above command , we are using the switch –m , which


is called Module.

• Module in Python are just like header files of C/C++


language as it contains functions ,classes and global
variables
Can We See The Bytecode File ?

• The module name in this command is py_compile and it


generates .pyc file for the .py file.

• Now the Python compiler creates a separate folder called


pycache for storing this bytecode file

• The name of the bytecode file is based on the Python


implementation we areusing

• Since we are using Cpython , so in our case the file name will
be firstcode.cpython-38.pyc
Can We See The Bytecode File ?

• After we have created the .pyc file , the next step is to


interpret it using Python interpreter

• The command for this will be:


python pycache \firstcode.cpython-36.pyc

• When we will run the above command the Python


interpreter inside PVM will be invoked and will run the
bytecode instructions inside the firstcode.cpython-36.pyc
file
Can We See The Bytecode File ?
PYTHON
LECTURE 4
Today’sAgenda

More About print() , IDLE, Error, Identifiers,


Reserved Words

• Introduction ToPredefined Functions And Modules

• How print() function works?

• How To Remove Newline From print( ) ?

• Introduction TOIDLE

• Types Of Errors InPython

• Rules ForIdentifiers

• Python ReservedWords
Types Of Predefined Function
Provided By Python

• Python has a very rich set of predefined functions and


they are broadly categorized to be of 2 types:

• Built In Functions

• Functions Defined InModules


Built InFunctions

• Built in functions are those functions which are always


available for use .

• For example , print() is a built-in function which prints the


given object to the standard output device (screen)

• As of version 3.8.5 , Python has 69 built-in function and


their list can be obtained on the following url :
https://docs.python.org/3/library/functions.html
What Is print( ) And
How It Is MadeAvailable
To Our Program ?
Functions Defined
In Modules

AModule in Python is collection of functions and other


Python elements which provide some extra functionality as
compared to built in functions.

We can assume it just like a header file of C/C++ language.

Python has 100s of built in Modules like math , sys , platform


etc which prove to be very useful for a programmer
Functions Defined
In Modules

For example , the module math contains a function called


factorial( ) which can calculate and return the factorial of any
number.

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

Then we can call any function of this module by prefixing it with


the module name

For example: math.factorial(5)


Functions Defined
In Modules
How To Remove
newline From print() ?

Let us revisit our firstcode.py file . The code was


print("Hello User")
print("Python Rocks")
How To Remove
newline From print()?

If we closely observe , we will see that the 2 messages are


getting displayed on separate lines , even though we have not
used anynewline character.

This is because the function print() automatically appends a


newline character after the message it is printing.
How To Remove
newline From print()?

If we do not want this then we can use the print() function as


shown below:
print(“HelloUser”,end=“”)
print(“Python Rocks”)
How To Remove
newline From print()?

The word end is called keyword argument in Python and it’s


default value is“\n”.

But we have changed it to empty string(“”) to tell Python not


to produce any newline.

Similarly we can set it to “\t” to generate tab or “\b” to erase


the previous character
Some Examples

1.
print("Hello User",end="\t")
print("Python Rocks")

2.
print("Hello User",end="\b")
print("Python Rocks")
Introducing IDLE

When we install CPython , along with other tools we also get


a lightweight Integrated Development Environment or IDLE
for short.

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.

Shell window is same as command shell and Editor window


is same as notepad but both have colorizing of code , input,
output, and error messages.
Introducing IDLE

To start IDLE on Windows click the Start Menu and search


"IDLE" or "idle".

Right Click IDLE as select Run as administrator and you will


see a window as shown in the next slide
Opening IDLE
Using IDLE

This is again Python Shell, but a much more colourful as


compared to the previous Shell window

Just type the commands, hit enter and it will display the
result.
Using IDLE
Using IDLE’s EditorWindow

IDLE also has a built-intext editor to write Python programs.

To create a new program go to File > New File.

Anew Untitled window will open. This window is a text editor


where we can write programs.
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

Save the file as sample.py and to run the program, Go to Run


> Run Module or HitF5.
Using IDLE’s EditorWindow

By doing this the editor window will move into the


background, Python Shell will become active and we will see
the output
Types OfErrors
In Python

• Just like any other programming language , Python also


has 2 kinds of errors:

• Syntax Error

• Runtime Error
Syntax Error

• Syntaxes are RULES OFALANGUAGE and when we break


these rules , the error which occurs is called Syntax Error.

• Examples of SyntaxErrors are:


• Misspelled keywords.
• Incorrect use of an operator.
• Omitting parentheses in a function call.
• Unterminated strings
And many other problems like this
Examples Of SyntaxError
RunTime Errors
(Exceptions)

• As the name says, Runtime Errors are errors which occur


while the program is running.

• As soon as Python interpreter encounters them it halts the


execution of the program and displays a message about
the probable cause of the problem.
RunTime Errors
(Exceptions)

• They usually occur when interpreter counters an operation


that is impossible to carry out and one such operation is
dividing a number by0.

• Since dividing a number by 0 is undefined , so ,when the


interpreter encounters this operation it
raises ZeroDivisionError as follows:
Example Of RunTimeError

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.

• Rules for identifiers:


• Identifiers can be a combination of letters in lowercase (a to z) or
uppercase (A to Z) or digits (0 to 9) or an underscore (_)

• No special character except underscore is allowed in the name of a


variable
Rules For Identifiers

• It must compulsorily begin with an underscore ( _ ) or a letter and


not with a digit . Although after the first letter we can have as many
digits as we want. So 1a is invalid , while a1 or _a or _1 is a valid
name for an identifier.
Rules For Identifiers

• Identifiers are case sensitive , so pi and Pi are two


different identifiers.
Rules For Identifiers

• Keywords cannot be used as identifiers

• Identifier can be of any length.


Rules For Reserved Words

• What is a Reserved Word?


• Aword in a programminglanguage which has a fixed meaning and
cannot be redefined by the programmer or used as identifiers

• How many reserved words are there in Python ?

• Python contains 35 reserved words or keywords

• The list is mentioned on the next slide

• We can get this list by using help() in Python Shell


Rules For ReservedWords

These 35 keywords are: Some ImportantObservations:


False , True , None ,def,
del ,import ,return, 1. Except False , Trueand None all the
and , or , not , other keywords are in lowercase
if, else , elif ,
for , while , break ,continue, 2. We don’t have else if in Python , rather
is , as , in , it iselif
global , nonlocal ,yield ,
try ,except , finally, raise, 3. There are no switch and do-while
lambda ,with ,assert , statements inPython
class ,from , pass ,
async,await
PYTHON
LECTURE 5
Today’s Agenda

Data Types

• Basic Data Types In Python

• Some Very Important Points To Remember

• Numeric Types

• DifferentTypes Of Integers

• Converting Between Int Types


Basic Data Types In Python

• Although a programmer is not allowed to mention the


data type while creating variables in his program in
Python , but Python internally allots different data types
to variables depending on their declaration style and
values.

• Overall Python has 14 data types and these are classified


into 6 categories.
Basic Data Types In Python

• These categories are:

• 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

Numeric Boolean Sequence Set Mapping None Type


Type Type Type Type Type

int bool str set dict NoneType

float list frozenset

complex bytes

bytearray

tuple

range
SomeVery Important Points

• Before we explore more about these data types , let us


understand following important points regarding Python’s
data types:

1. DATA TYPES IN PYTHON ARE DYNAMIC

2. SIZE OF THE DATA TYPE IS ALSO DYNAMICALLY


MANAGED

3. DATA TYPES ARE UNBOUNDED


SomeVery Important Points

1. DATATYPES IN PYTHON ARE DYNAMIC

• The term dynamic means that we can assign different


values to the same variable at different points of time.

• Python will dynamically change the type of variable as per


the value given.
SomeVery Important Points

type() is a built –in


function and it returns
the data type of the
variable

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

2. SIZE OFTHE DATA TYPE IS ALSO DYNAMICALLY


MANAGED

• In Python the size of data types is dynamically managed

• Like C/C++/Java language , variables in Python are not of fixed


size.

• Python makes them as big as required on demand

• There is no question of how much memory a variable uses in


Python because this memory increases as per the value being
assigned
SomeVery Important Points

• Python starts with initial size for a variable and then


increases its size as needed up to the RAM limit

• This initial size for int is 24 bytes and then increases as the
value is increased

• If we want to check the size of a variable , then Python


provides us a function called getsizeof() .

• This function is available in a module called sys


SomeVery Important Points
SomeVery Important Points

3. DATA TYPES ARE UNBOUNDED

• Third important rule to remember is that , in Python data


types like integers don’t have any range i.e. they are
unbounded

• Like C /C++ /Java they don’t have max or min value

• So an int variable can store as many digits as we want.


Numeric Types In Python

 As previously mentioned , Python supports 3 numeric


types:

 int: Used for storing integer numbers without any fractional


part

 float: Used for storing fractional numbers

 complex: Used for storing complex numbers


Numeric Types In Python

 EXAMPLES OF int TYPE:

a=10
b=256
c=-4
print(a)
print(b)
print(c)
Output:
10
256
-4
Numeric Types In Python

 DIFFERENT WAYS OF REPRESENTING int IN PYTHON:

1. As decimal number( base 10)

2. As binary number( base 2)

3. As octal number(base 8)

4. As hexadecimal number( base 16)


Numeric Types In Python

 REPRESENTING int AS DECIMAL( base 10) :

1. This is the default way of representing integers

2. The term base 10 means , 10 digits from 0 to 9 are allowed

3. Example:
a=25
Numeric Types In Python

 REPRESENTING int AS BINARY( base 2) :

1. We can represent numeric values as binary values also

2. The term base 2 means , only 2 digits from 0 and 1 are


allowed

3. But we need to prefix the number with 0b or 0B , otherwise


Python will take it to be a decimal number
Numeric Types In Python
SomeVery Important
Observation

1. For representing binary value it is compulsory to prefix


the number with 0b or 0B.

2. Although we can assign binary value to the variable but


when we display it we always get output in decimal number
system form.
SomeVery Important
Observation

3. We cannot provide any other digit except 0 and 1 while


giving binary value , otherwise Python will generate
syntax error.
SomeVery Important
Observation

4. We can provide negative values in binary number system


also by prefixing 0b with - .

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

 REPRESENTING int AS OCTAL( base 8) :

1. We can represent numeric values as octal values also

2. The term base 8 means , only 8 digits from 0 to 7 are


allowed

3. But we need to prefix the number with zero followed by


small o or capital O i.e. either 0o or 0O , otherwise Python
will take it to be a decimal number
Numeric Types In Python

4. We cannot provide any other digit except 0 , 1 , 2 , 3 , 4 , 5


, 6 and 7 while giving octal value , otherwise Python will
generate syntax error.
Numeric Types In Python

5. Just like binary number system , we can provide negative


values in octal number system also by prefixing 0O with -
Numeric Types In Python

 REPRESENTING int AS HEXADECIMAL( base 16) :

1. We can represent numeric values as hexadecimal values


also

2. The term base 16 means , only 16 digits from 0 to 9 , a to f


and A to F are allowed

3. But we need to prefix the number with zero followed by


small x or capital X i.e. either 0x or 0X , otherwise Python
will take it to be a decimal number
Numeric Types In Python

4. We cannot provide any other value except the digits and


characters from A to F while giving hexadecimal value ,
otherwise Python will generate syntax error.
Numeric Types In Python

5. Just like other number systems , we can provide negative


values in hexadecimal number system also by prefixing 0x
with -
Base Conversion Functions

 We know that Python allows us to represent integer values


in 4 different forms like int , binary , octal and hexadecimal

 Moreover it also allows us to convert one base type to


another base type with the help of certain functions.

 These functions are:


 bin()
 oct()
 hex()
The bin( ) Function

 The bin() function converts and returns the binary


equivalent of a given integer.

 Syntax : bin(a)

 Parameters : a : an integer to convert . This value can be of


type decimal , octal or hexadecimal

 Return Value : A string representing binary value


The bin( ) Function

 Some Examples:
1. Converting decimal base to binary

2. Converting octal base to binary


The bin( ) Function

 Some Examples:

3. Converting hexadecimal base to binary

4. Error if the value passed is not an integer


The oct( ) Function

 The oct() function converts and returns the octal equivalent


of a given integer.

 Syntax : oct(a)

 Parameters : a : an integer to convert . This value can be of


type decimal , binary or hexadecimal

 Return Value : A string representing octal value


The oct( ) Function

 Some Examples:
1. Converting decimal base to octal

2. Converting binary base to octal


The oct( ) Function

 Some Examples:

3. Converting hexadecimal base to octal

4. Error if the value passed is not an integer


The hex( ) Function

 The hex() function converts and returns the hexadecimal


equivalent of a given integer.

 Syntax : hex(a)

 Parameters : a : an integer to convert . This value can be of


type decimal , octal or bin

 Return Value : A string representing hexadecimal value


The hex( ) Function

 Some Examples:
1. Converting decimal base to hexadecimal

2. Converting binary base to hexadecimal


The hex ( ) Function

 Some Examples:

3. Converting octal base to hexadecimal

4. Error if the value passed is not an integer


PYTHON
LECTURE 6
Today’s Agenda

More On Data Types

• The float Type

• The complex Type

• The boolType

• The str Type


The float Data Type

• Python also supports floating-point real values.

• Float values are specified with a decimal point

• So 2.5 , 3.14 , 6.9 etc are all examples of float data type

• Just like double data type of other languages like Java/C ,


float in Python has a precision of 16 digits
Some Examples
Some Important Points
About float

• For float , we can only assign values in decimal number


system and not in binary , octal or hexadecimal number
system.
Some Important Points
About float

• Float values can also be represented as exponential values

• Exponential notation is a scientific notation which is


represented using e or E followed by an integer and it
means to the power of 10
The complex Data Type

• Complex numbers are written in the form, x + yj, where x is


the real part and y is the imaginary part.

• For example: 4+3j , 12+1j etc

• The letter j is called unit imaginary number.

• It denotes the value of √-1 , i.e j² denotes -1


An Example
Some Important Points
About complex Data Type

• For representing the unit imaginary number we are only


allowed to use the letter j (both upper and lower case are
allowed).

• Any other letter if used will generate error


Some Important Points
About complex Data Type

• The letter j , should only appear in suffix , not in prefix


Some Important Points
About complex Data Type

• The real and imaginary parts are allowed to be integers as


well as floats
Some Important Points
About complex 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

• We can display real and imaginary part separately by using


the attributes of complex types called “real” and “imag”.

• Don’t think real and imag are functions , rather they are
attributes/properties of complex data type
The bool Data Type

• In Python , to represent boolean values we have bool data


type.

• The bool data type can be one of two values,


either True or False.

• We use Booleans in programming to make comparisons


and to control the flow of the program.
Some Examples
Some Important Points
About bool

• True and False are keywords , so case sensitivity must be


remembered while assigning them otherwise Python will
give error
Some Important Points
About bool

• All test conditions in Python return the result as bool


which could be either True or False
Some Important Points
About bool

• To understand the next point , try to guess the output of the


following:
a=True a=True a=False
b=False b=True b=False
c=a+b c=a+b
c=a+b
print(c) print(c)
print(c) Output: Output:
Output: 2 0
1
The above outputs make it clear that internally Python stores
True and False as integers with the value 1 and 0 respectively
The str Data Type

• Just like any other language , in Python also a String is


sequence of characters.

• Python does not have a char data type, unlike C/C++ or


Java

• We can use single quotes or double quotes to represent


strings.

• However Python recommends to use single quotes


Some Examples

The data type used by Python internally for storing Strings is


str
Some Important Points
About Strings

• Unlike C language , Python does not uses ASCII number


system for characters . It uses UNICODE number system

• UNICODE is a number system which supports much wider


range of characters compared to ASCII

• As far as Python is concerned , it uses UNICODE to support


65536 characters with their numeric values ranging from 0
to 65535 which covers almost every spoken language in the
world like English , Greek , Spanish , Chinese , Japanese
etc
Some Important Points
About Strings
Some Important Points
About Strings

• Whenever we display a string value directly on Python’s


shell i.e. without using the function print(), Python’s shell
automatically encloses it in single quotes

• However this does not happen when we use print() function


to print a string value
Some Important Points
About Strings

• If a string starts with double quotes , it must end with


double quotes only .

• Similarly if it starts with single quotes , it must end with


single quotes only.

• Otherwise Python will generate error


Some Important Points
About Strings
Some Important Points
About Strings

• If the string contains single quotes in between then it must


be enclosed in double quotes and vice versa.

• For example:

• To print Sachin's Python Classes , we would write:


• msg= " Sachin's Python Classes "

• Similarly to print Capital of "MP" is "Bhopal" ,we would


write:

• msg='Capital of "MP" is "Bhopal" '


Some Important Points
About Strings
Some Important Points
About Strings

• How will you print Let's learn "Python" ?

A."Let's learn "Python" "

B.'Let's learn "Python" '

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

• Another important use of triple single quotes or triple


double quotes is that if our string extends up to more than
1 line then we need to enclose it in triple single quotes or
triple double quotes
Some Important Points
About Strings

• We also can do the same thing by using \n , so using triple


quotes or triple double quotes is just for improving
readability
Accessing Individual Characters
In String

 In Python, all Strings are stored as individual characters in a


contiguous memory location.

 Each character in this memory location is assigned an index


which begins from 0 and goes up to length -1
Accessing Individual Characters
In String

 For example, suppose we write


word=“Python”

 Then the internal representation of this will be


Accessing Individual Characters
In String

 Now to access individual character we can provide this index


number to the subscript operator [ ].
Accessing Individual Characters
In String

 However if we try to provide an index number beyond the given


limit then IndexError exception will arise
Accessing Individual Characters
In String

 Not only this , Python even allows negative indexing which


begins from the end of the string.

 So -1 is the index of last character , -2 is the index of second


last character and so on.
Accessing Individual Characters
In String

Click to add text


PYTHON
LECTURE 7
Today’sAgenda

• Concatenating Strings

• The Slice Operator In Strings

• Three Important String Functions

• Type Conversion
String Concatenation

• Concatenation means joining two or more strings together

• To concatenate strings, we use the + operator.

• Keep in mind that when we work with numbers, + will be an


operator for addition, but when used with strings it is a
joining operator.
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

• Slicing means pulling out a sequence of characters from a


string .

• For example , if we have a string “Industry” and we want to


extract the word “dust” from it , then in Python this is done
using slicing.

• To slice a string , we use the operator[ ] as follows:


• Syntax: s[x:y]
• x denotes the start index of slicing and y denotes the end index .
But Python ends slicing at y-1 index.
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

• String slicing can accept a third parameter also after the


two index numbers.

• The third parameter is called step value.


• So the complete syntax of slicing operator is:

s[begin:end:step]

• Step value indicates how many characters to move forward


after the first character is retrieved from the string and it’s
default value is 1 , but can be changed as per our choice.
The Slicing Operator
• For Example: s=“Industry”
s=“Industry” print(s[2:6:2])
print(s[2:6])

• 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

• Python provides us some very useful functions/methods


for performing various operations on String values.

• Following are these functions/methods:

• len()

• lower()

• upper()
Three Very Useful
Functions/Methods
Of String Data Type

• len() : Returns length of the String passed as argument


• Syntax: len(s)

• lower() : Returns a copy of calling String object with all


letters converted to lowercase
• Syntax: s.lower()
Three Very Useful
Functions/Methods
Of String Data Type

• upper() : Returns a copy of calling String object with all letters


converted to uppercase

• Syntax: s.upper()
Comparing Strings

 We can use ( > , < , <= , <= , == , != ) to compare two strings.

 Python compares string lexicographically i.e using UNICODE


value of the characters.
Comparing Strings
 Suppose we have str1 as " Indore " and str2 as " India" and we write
print(str1>str2) , then Python will print True. Following is the
explanation

 Now the first two characters from str1 and str2 ( I and I ) are compared.

 As they are equal, the second two characters 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 .

 Now because o has a greater UNICODEvalue than i so Indore is greater


than India and so the answer is True
Comparing Strings
Type Conversion

 The process of converting the value of one data type (integer,


string, float, etc.) to another data type is called Type
Conversion.

 Python has two types of type conversion.

 Implicit Type Conversion

 Explicit Type Conversion


Implicit Conversion

 In ImplicitType Conversion, Python automatically converts


one data type to another data type.

 This process doesn't need any programmer involvement.

 Let's see an example where Python promotes conversion of int


to float .
Example Of
Implicit Conversion

• If we observe the above operations , we will find that


Python has automatically assigned the data type of c to be
float .

• This is because Python always converts smaller data type


to larger data type to avoid the loss of data.
Another Example

• Here also Python is automatically upgrading bool to type


int so as to make the result sensible
Explicit Type Conversion

• There are some cases , where Python will not perform type
conversion automatically and we will have to explicitly
convert one type to another.

• Such Type Conversions are called ExplicitType Conversion

• Let's see an example of this


Explicit Type Conversion

Guess the output ?


a=10 Why did the code fail?
b=“6”
print(type(a)) The code failed because
print(type(b)) Python does not automatically convert
c=a+b String to int.
print( c )
print(type( c )) To handle such cases we need to
perform Explicit Type Conversion
Output:
<class ‘int’>
<class ‘str’>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ExplicitType Conversion
Functions In Python

• Python provides us 5 predefined functions for performing


Explicit Type Conversion for fundamental data types.

• These functions are :


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

• Syntax: int(value)

• This function converts value of any data type to integer ,


with some special cases

• It returns an integer object converted from the given value


int( ) Examples

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

Can you solve this error now ?

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)

• This function converts value of any data type to float ,


with some special cases

• It returns a float object converted from the given value


float( ) Examples

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)

• This function converts value of any data type to complex ,


with some special cases

• It returns an complex object converted from the given


value
complex ( ) Examples

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)

• This function converts value of any data type to bool ,


using the standard truth testing procedure.

• It returns an bool object converted from the given value


The bool ( ) Function

• What values are considered to be false and what values


are true ?

• The following values are considered false in Python:


 None
 False
 Zero of any numeric type. For example, 0, 0.0, 0+0j
 Empty sequence. For example: (), [], ''.
 Empty mapping. For example: {}

• All other values are true


bool( ) Examples

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)

• This function converts any data type to string , without any


special cases

• It returns a String object converted from the given value


str( ) Examples

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

• Variables And Memory Management


• How Variables In Python Are DifferentThan Other
Languages ?

• Immutable And Mutable

• Python’s Memory Management

• The id( ) Function

• The is Operator
Understanding Python
Variables

• A variable can be seen as a container to store certain


values.

• While the program is running, variables are accessed and


sometimes changed, i.e. a new value will be assigned to a
variable
HowVariables
Work In C ?

• In C language when we declare a variable and assign value


to it then some space is created in memory by the given
name and the given value is stored in it.

• Suppose we write the statement int a=42; , then the


following will be the memory diagram.
HowVariables
Work In C ?

• Now if we declare another variable , with the same value ,


then again the same process will take place.
• Suppose we write , int b=42;
HowVariables
Work In C ?

• Finally if we assign a new value to an existing variable ,


then it’s previous value gets overwritten
• Suppose we write , a=43;
HowVariables
Work In Python ?

• In Python when we assign value to a variable , then things


are different than C .

• Suppose we write a=42 in Python , then Python will create


2 things:

•An object in heap memory holding the value 42 ,


and
• A reference called a which will point to this object
HowVariables
Work In Python ?
HowVariables
Work In Python ?

• Now if we create another variable called b and assign it


the same value , then Python will do the following:

• Create a new reference by the name b

• Assign the address of the previously created object to the


reference b because the value is same

• So now both a and b are pointing to the same object


HowVariables
Work In Python ?
HowVariables
Work In Python ?

• Finally if we assign a new value to the variable a , then like C


, Python will not overwrite the value .

• Rather it will do the following:

• Create a new object initialized with the new value

• Assign the address of the newly created object to the


reference a

• However the reference b is still pointing to the same object


HowVariables
Work In Python ?
HowVariables
Work In Python ?

• This behaviour of objects in Python is called


“immutability”

• In other words when we cannot change the value of an


object , we say it is immutable , otherwise we say it is
mutable

• Objects of built-in types like (int, float, bool, str, complex ,


tuple) are immutable.

• Objects of built-in types like (list, set, dict) are mutable.


Strings Are Also Immutable
• String objects in Python are also immutable.

• That is , once we have created a String object , then we


cannot overwrite it’s value.

• Although we can change the value of the String reference


by assigning it new String.
Strings Are Also Immutable
ImmutableAnd Mutable
• Following data types in Python are immutable:
• int
• float
• bool
• str
• tuple
• complex
• range
• frozenset
• bytes
• Following data types in Python are mutable:
• list
• dict
• set
• bytearray
Two Very Important
Questions

• Keeping in mind the concept of immutability , 2 very


common questions arise :

• What is the benefit of making objects immutable ?


&
• If we have a single reference and we create multiple
objects , then wouldn’t there be memory wastage ?
Qn 1 : Benefit Of Immutability

• The main benefit of immutability is that , it prevents


unnecessary creation of new objects .

• This is because if we write , the following 2


statements: a=42
b=42

• Then Python will not create 2 objects . Rather it only creates 1


object and makes both the references a and b ,refer to the same
object.

• This saves memory and overhead of creating multiple objects


Qn 2 : What About Single ?
ReferenceAnd Multiple Objects

• Considerthe following3 lines :

a=10
a=20
a=30

• When theabove 3 lines will run , then Python will create 3


objects , one by one and finally the reference a will refer to
the last object with the value 30

• An obvious question arises , that what will happen to the


previous 2 objects with thevalue 10 and 20 ?
Three ImportantTerms
• Before understanding , what will happen to the previous 2
objects , we need to understand 3 important
terminologies:

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 .

• Garbage collection is a memory management feature in


many programminglanguages.
ReferenceCounting
• The process of memory management in Python is
straightforward.

• Python handles it’s objects by keeping a count of the


number of references each object has in the program.

• In simple words it means, each object stores how many


references are currently referring it.
ReferenceCounting
• This count is updated with the program runtime and when
it reaches 0, this means it is not reachable from the
program anymore.

• Hence, the memory for this object can be reclaimed and be


freed by the interpreter.
ReferenceCounting

a=10 // The object 10 has a reference count of 1


b=10 // Now 10 has reference count of 2
a=20 // Now reference count of 10 becomes 1
b=20 // Finally reference count of 10 becomes 0

• As soon as the reference count of 10 becomes 0 , Python


automatically removes the object 10 from memory
ReferenceCounting
• So in our example

a=10
a=20
a=30

• The objects 10 and 20 will be reclaimed by the Python


Garbage Collector as soon as their reference count
becomes 0
ReferenceCounting
• ADVANTAGE:

• The main advantage of such approach is that unused memory


is reclaimed and made available for use again.

• DISADVANTAGE:

• The drawback is that Python has to continuously watch the


reference count of objects in the background and free them
as soon as the reference count becomes 0.

• This is another important reason why Python is slow as


compared to other languages
Another ImportantQuestion
• Consider the following statements:

a=42
b=42

• Can you tell how many objects has Python created in the
above code ?

• Answer: Only 1

• But , what is the proof ?


Another ImportantQuestion
• We can prove this in 2 ways:

• By using id( ) function

• By using is operator
The id( ) Function
• id() is a built-in function in Python 3, which returns
the identity of an object.

• The identity is a unique integer for that object during it’s


lifetime.

• This is also the address of the object in memory.


PYTHON
LECTURE 9
Today’s Agenda

• Comments , Constants And More About print( )


Function

• How to write Comments in Python ?

• How to create constants in Python ?

• How to print a variables value using print( ) ?


Comments In Python

• Comments are statements in our program which are


ignored by the compiler or interpreter i.e they are not
executed by the language

• We generally create comments to let developers


understand our code’s logic.

• This is a necessary practice, and good developers make


heavy use of the comment system.

• Without it, things can get confusing


Types Of Comments
In Python

• Python provides 2 types of comments:

• Single Line Comment ( official way of comment)

• MultiLine Comment ( un offcial way)


Single Line Comments

• Single-line comments are created simply by beginning a


line with the hash (#) character, and they are automatically
terminated by the end of line.

• For example:

a=10 This line gets


commented out
#a=a+1 and is not executed
print(a)
Output:
10
Official Way Of
Multi Line Comments

• To create a Multi Line Comments , the only problem with


this style is we will have prefix each line with # , as shown
below:

#a=a+1
#b=b+5
#c=c+10

• But most Python projects follow this style and Python’s


PEP 8 style guide also favours repeated single-line
comments.
What Is PEP ?

• PEP stands for Python Enhancement Proposal.

• It is Python's style guide and is officially called PEP8

• In simple words it is a set of rules for how to format your


Python code to maximize its readability .

• We can find it at https://www.python.org/dev/peps/pep-


0008/
Why Is PEP Needed ?

• When you develop a program in a group of programmers,


it is really important to follow some standards.

• If all team members format the code in the same


prescribed format, then it is much easier to read the code.

• For the same purpose PEP8 is used to ensure Python


coding standards are met.
Un Official Way Of
Multi Line Comments

• If we want to simplify our efforts for writing Multi Line


Comments , then we can wrap these comments inside
triple quotes ( double or single ) as shown below

• 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 ?

• Triple quotes doesn’t create “true” comments.

• 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.

• Hence they are not ignored by the interpreter in the same


way that #a comment is.
What Is A Constant ?

• A constant is a type of variable whose value cannot be


changed.

• C++ provides the keyword const for declaring constant as


shown below:
const float pi=3.14;
pi=5.0; // Syntax Error

• Java provides the keyword final for declaring constant:


final double PI=3.14;
PI=5.0; // Syntax Error
How To Create A Constant
In Python?

• Unfortunately , there is no keyword in Python , like const


or final , to declare a variable as constant.

• This is because of dynamic nature of Python .

• However there is a convention in Python , that we can


follow to let other developer’s know that we are declaring a
variable as constant and we don’t want others to change
it’s value.

• The convention is to declare the variable in all upper case


How To Create A Constant
In Python?

• For example:
PI=3.14
MAX_MARKS=100

• But again , remember this is just a convention not a rule and


still the value of PI and MAX_MARKS can be changed
Some More About print( )
Function

• We know that print( ) function can be used to print


messages on the output screen.

• But we can also use print( ) to display single or multiple


variable values.

• We just have to separate them with comma :


• print( arg1 , arg2, arg3, . . .)
The print( ) Function

• 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

Note the space


occurred
automatically in
between
The print( ) Function

• 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)

Note , we have not provided any space at marked


positions but in the output we will automatically
get the space
• Output:
My name is Sachin and my age is 32
How Is Space
Getting Generated?

• Just like print() function has a keyword argument called


end , which generates newline automatically , similarly it
also has another keyword argument called sep

• This argument has the default value of “ “ and is used by


Python to separate values of 2 arguments on screen.
How Is Space
Getting Generated?

• So the statement :
• print(“Good”,”Morning”)

• Is actually converted by Python to


• print(“Good”,”Morning”,sep=“ “)

• And the output becomes


• Good Morning
Changing The
Default Value Of sep

• We can change the default value of sep to any value we like


.

• To do this , we just have to pass sep as the last argument to


the function print( )
• print(“Good”,”Morning”,sep=“,”)

• And the output becomes


• Good,Morning
Note that comma
has occurred instead
of space
The print( ) Function

• 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

1. What is the maximum possible length of an identifier in


Python?

A. 31 characters
B. 63 characters
C. 79 characters
D. none of the mentioned
Correct Answer: D
QUIZ 2- TestYour Skills

2. Which of these in not a core data type in Python?

A. Class
B. List
C. Str
D. Tuple

Correct Answer: A
QUIZ 2- TestYour Skills

3. Following set of commands are executed in shell, what will be the


output?
>>>str="hello"
>>>str[:2]

A. hel
B. he
C. Lo
D. olleh

Correct Answer: B
QUIZ-Test Your Skills

4. What is the return type of function id ?

A. int
B. float
C. bool
D. dict

Correct Answer: A
QUIZ-Test Your Skills

5. Which of the following results in a SyntaxError ?

A. ' ''Once upon a time…'', she said. '


B. ''He said, 'Yes!' ''
C. '3\'
D. '' That's okay ''

Correct Answer: C
QUIZ-Test Your Skills

6. Which of the following is not a complex number?

A. k = 2 + 3j
B. k = complex(2)
C. k = 2 + 3I
D. k = 2 + 3J

Correct Answer: C
QUIZ-Test Your Skills

7. Which of the following is incorrect?

A. k = 0b101
B. k= 0x4f5
C. k = 19023
D. k = 0o3964
Correct Answer: D
QUIZ-Test Your Skills

8. What is the output of the code:


print(bool('False'))

A. False
B. True
C. SyntaxError
D. 0

Correct Answer: B
QUIZ-Test Your Skills

9. Out of List and Tuple which is mutable ?

A. List
B. Tuple
C. Both
D. None

Correct Answer: A
QUIZ-Test Your Skills

10. Are string references mutable ?

A. Yes
B. No

Correct Answer: A
QUIZ-Test Your Skills

11. Are string objects mutable ?

A. Yes
B. No

Correct Answer: B
QUIZ-Test Your Skills

12. Is there a do – while loop in Python ?

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

13. In Python which is the correct method to load a module ?

A. include math
B. import math
C. #include<math.h>
D. using math

Correct Answer: B
QUIZ-Test Your Skills

14. What is the name of data type for character in Python ?

A. chr
B. char
C. str
D. None Of The Above

Correct Answer: D
QUIZ- Test Your Skills

15. Let a = "12345" then which of the following is correct ?

A. print(a[:]) will show 1234


B. print(a[0:]) will show 2345
C. print(a[:100]) will show 12345
D. print(a[1:]) will show 1

Correct Answer: C
Today’sAgenda

• Operators In Python
• Types Of Operators

• Arithmetic Operators

• Special points about + and *

• Difference between / and //


Operators

• Operators are special symbols in that carry out different


kinds of computation on values.

• For example : 2+3

• In the expression 2+3 , + is an operator which performs


addition of 2 and 3 , which are called operands
Types Of Operators
In Python

• Python provides us 6 popular types of operators:

• Arithmetic Operators

• Relational or Comparison Operators

• Logical Operators

• Assignment Operator

• Identity Operators

• Membership Operators
Arithmetic Operators
In Python

• In Python , we have 7 arithmetic operators and they are as below:

+
(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 **

• The operator // in Python is called as floor division.

• Means it returns the integer part and not the decimal part.

• For example: 5//2 will be 2 not 2.5


Two Special
Operators // and **

• But there are 3 very important points to understand about


this operator

• When used with positive numbers the result is only the


integer part of the actual answer i.e. , the decimal part is
truncated

• However if one of the operands is negative, the result is


floored.

• If both the operands are integers , result will also be integer


,otherwise result will be float
The Floor Division Operator

• Example: • Example:
a=10.0
a=10 b=4
b=4 print(a//b)
print(a//b)

• Output:
• Output: 2.0
2

If both the operands are integers , the result is also


an integer . But if any of the operands is float the result
is also float
The Floor Division Operator

• 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

• There is another very important point to remember about


the 3 operators / , // and %

• The point is that if the denominator in these operators is 0


or 0.0 , then Python will throw the exception called
ZeroDivisionError
Division By 0

• 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

• The power operator i.e. ** performs exponential (power)


calculation on operands.

• For example:
a=10
b=3
print(a**b)

• Output:
1000
Double Role Of The Operator +

• The operator + as discussed earlier also ,has 2 roles in


Python

• When used with numbers , it performs addition and when


used with strings it performs concatenation

• 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 *

• The operator * also has 2 roles in Python

• When used with numbers , it performs multiplication and


when used with one operand string and other operand int
it performs repetition

• 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

• Relational Operators With Strings

• Chaining Of Relational Operators

• Special Behavior Of == and !=


Relational Operators In Python

฀ Relational operators are used to compare values.

฀ They either return True or False according to the condition.

฀ These operators are:

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

฀ Relational Operators can also work with strings .

฀ When applied on string operands , they compare the unicode


of corresponding characters and return True or False based on
that comparison.

฀ As discussed previously , this type of comparison is called


lexicographical comparsion
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

฀ If we want to check the UNICODE value for a particular letter , then


we can call the function ord().

฀ It is a built in function which accepts only one character as argument


and it returns the UNICODE number of the argument passed

฀ 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 ?

a=True Yes , the code will successfully


b=False Run because True is 1 and False is 0
print("a=",a,"b=",b) Output:
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)
What about this code?

a=‘True’ Yes , this code will also successfully


b=‘False’ Run but ‘True’ and ‘False’ will be handled
as strings
print("a=",a,"b=",b)
Output:
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)
Special Behavior Of
Relational Operators

฀ Python allows us to chain multiple relational operators in one


single statement.

฀ For example the expression 1<2<3 is perfectly valid in Python

฀ However when Python evaluates the expression , it returns


True if all individual conditions are true , otherwise it returns
False
Cascading Of Relational Operators

• 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 !=

฀ == compares it’s operands for equality and if they are of


compatible types and have same value then it returns True
otherwise it returns False

฀ Similarly != compares it’s operands for inequality and if they


are of incompatible types or have different value then it
returns True otherwise it returns 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

• How Logical Operators Work With Boolean Types ?

• How Logical Operators Work With Non Boolean Types


?
Logical Operators In Python

฀ Logial operators are used to combine two or more conditions


and perform the logical operations using Logical and, Logical
or and Logical not.

Operator Meaning

and It will return true when both conditions


are true

or It will returns true when at-least one of


the condition is true

not If the condition is true, logical NOT


operator makes it false
Behavior Of Logical and Operator
Behavior Of Logical or Operator
Behavior Of Logical not Operator
Behavior Of
Logical Operators With
Non Boolean

฀ Python allows us to apply logical operators with non boolean


types also

฀ But before we understand how these operators work with non


boolean types, we must understand some very important
points
Behavior Of
Logical Operators With
Non Boolean

1. None, 0 , 0.0 ,”” are all False values

1. The return value of Logical and & Logical or operators is


never True or False when they are applied on non boolean
types.
Behavior Of
Logical Operators With
Non Boolean

3. If the first value is False , then Logical and returns first value
, otherwise it returns the second value

3. If the first value is True , then Logical or returns first value ,


otherwise it returns the second value

3. When we use not operator on non boolean types , it returns


True if it’s operand is False( in any form) and False if it’s
operand is True ( in any form)
Logical Operators
On Non Boolean Types

• 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

• Various Types Of Assignment Operators

• Compound Operators

• Identity Operators

• Membership Operators

• Precedence And Associativity


Assignment Operators In Python

฀ The Python Assignment Operators are used to assign the


values to the declared variables.

฀ Equals (=) operator is the most commonly used assignment


operator in Python.

฀ For example:
฀ a=10
Assignment Operators In Python

฀ Shortcut for assigning same value to all the variables


฀ x=y=z=10

฀ Shortcut for assigning different value to all the variables


฀ x,y,z=10,20,30
Guess The Output

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

฀ Python allows us to combine arithmetic operators as with


assignment operator.

฀ For example: The statement


฀ x=x+5

฀ Can also be written as


฀ x+=5
Compound Assignment Operators

Operator Example Meaning

+= 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

฀ Identity operators in Python are is and is not

฀ They serve 2 purposes:

฀ To verify if two references point to the same memory location or


not
AND
฀ To determine whether a value is of a certain class or type
Behavior Of is and is not

฀ The operator is returns True if the operands are identical ,


otherwise it returns False.

฀ The operator is not returns True if the operands are not


identical , otherwise it returns False.
Examples Of is Operator

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

฀ Membership operators are used to test whether a value or


variable is found in a sequence
(string, list, tuple, set and dictionary).

฀ There are 2 Membership operators

฀ in

฀ not in
Behavior Of in and not in

฀ in: The ‘in’ operator is used to check if a value exists in a


sequence or not

฀ 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

฀ There can be more than one operator in an expression.

฀ To evaluate these type of expressions there is a rule called


precedence in all programming languages .

฀ It guides the order in which operations are carried out.


Precedence And Associativity

Operator Name
() Parentheses

** Exponent

+x, -x Unary plus, Unary minus

*, /, //, % Multiplication, Division, Floor div,Mod

+, - Addition, Subtraction

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

not Logical NOT

and Logical AND

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

฀ When two operators have the same precedence, Python


follows associativity

฀ Associativity is the order in which an expression is evaluated


and almost all the operators have left-to-right associativity.
Associativity Of Operators

฀ For example, multiplication and division have the same


precedence. Hence, if both of them are present in an
expression, left one is evaluated first.

฀ Similarly , exponentiation ( ** ) has right to left associativity .

฀ So if multiple ** are present , they are solved from right to left.


Guess The Output

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

• Input Function And Math Module In Python


• Using the input( ) Function

• Using the math module

• Different ways of importing a module

• Accepting multiple values in single line


Accepting Input In Python

฀ To accept user input , Python provides us a function called


input ( )

฀ Syntax:

฀ input([prompt])

฀ The input() function takes a single optional argument , which


is the string to be displayed on console.
Return Value Of input( )

฀ The input() function reads a line from keyboard , converts the


line into a string by removing the trailing newline, and returns
it.
Example 1
(Using input() without message)

print("enter your name")


name=input()
print("Hello",name)

Output:
Example 2
(Using input( ) With Message)

name=input("enter your name")


print("Hello",name)

฀ Output:
Example 3
(Using input( ) With Message)

name=input(“Enter your full name:”)


print("Hello",name)

฀ Output:
Accepting Integer Input

฀ By default the function input( ) returns the inputted value as a


string

฀ So , even if we input a numeric value , still Python considers it


to be string
Accepting Integer Input

฀ To understand this behavior , consider the following code:

a=input("enter a number\n")
b=a+1
print(b)

฀ Output:
Accepting Integer Input

฀ To solve this , we can use Type Conversion Functions in


Python , for converting a given value from string to other type.

฀ For example , in the previous code , we can use the function


int( ) to convert string value to integer
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

฀ For converting input values to float and boolean we can call


float( ) and bool( ) functions

฀ 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

฀ Can you write the previous code in one line only ?


Code:
print("Their sum is",int(input("Enter first
num:"))+int(input("Enter secnd num:")))
Exercise

฀ WAP to accept radius of a Circle from the user and calculate


area and circumference.
Code:
radius=float(input("Enter radius:"))
area=3.14*radius**2
circum=2*3.14*radius
print("Area is",area)
print("Circumference is",circum)
Exploring More About
math Module

฀ We have already discussed that Python has a module called


math .

฀ This module helps us perform mathematical calculations

฀ It contains several mathematical constants and functions


Exploring More About
math Module

฀ Following are some important functions :


฀ math.factorial(x)
฀ math.floor(x)
฀ math.ceil(x)
฀ math.gcd(a, b)
฀ math.pow(x,y)
฀ math.sqrt(x)

฀ Following are it’s important mathematical constants:


฀ math.pi : The mathematical constant π = 3.141592…
฀ math.e: The mathematical constant e = 2.718281…,
฀ math.tau: Tau is a circle constant equal to 2π
Modified Version Of Previous
Code Using math Module

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

฀ We can use aliasing for module names

฀ To do this , Python provides us as keyword

฀ 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

฀ We can also import specific members of a module

฀ To do this , Python provides us from keyword

฀ 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

฀ It is also possible to import all names from a module into the


current file by using the wildcard character *

฀ Syntax:
฀ from modname import *

฀ This provides an easy way to import all the members from a


module into the current file
Using WildCard Character

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

฀ In Python , we can print members of a module in the Python


Shell window

฀ This can be done in 2 ways:

฀ By calling the dir( ) function passing it the module name

฀ By calling the help( ) function passing it the module name


Using dir( )

฀ The dir( ) function accepts the name of a module as argument


and returns a list of all it’s members.

฀ However the module must be imported before passing it to the


dir( ) function
Using help( )

฀ The help( ) function accepts the name of a module as


argument and displays complete documentation of all the
members of the module

฀ Here also , module must be imported before using it.


Accepting Different Values

฀ WAP to accept roll number , grade and percentage as input


from the user and display it back
Code
roll=int(input("Enter roll no:"))
name=input("Enter name:");
per=float(input("Enter per:"))
print("Roll no is",roll)
print("Name is",name)
print("Per is",per)
Exercise

฀ 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.

฀ Hint: Use the module datetime to get the current year


Accepting Multiple Values
In One Line

฀ In Python , the input( ) function can read and return a


complete line of input as a string.

฀ However , we can split this input string into individual values by


using the function split( ) available in the class str

฀ The function split( ) , breaks a string into multiple strings by


using space as a separator
Accepting Multiple Values
In One Line

฀ To understand , working of split( ) , consider the following


example:

text=“I Love Python”


word1,word2,word3=text.split()
print(word1)
print(word2)
print(word3)
Output:
I
Love
Python
Accepting Multiple
Values In One Line

text=input(“Type a 3 word message”)


word1,word2,word3=text.split()
print(“First word”,word1)
print(“Secnd word”,word2)
print(“Third word”,word3)
Output:
An Important Point!

฀ The number of variables on left of assignment operator and


number of values generated by split() must be the same
Exercise

฀ Write a program that asks the user to input 2 integers and


adds them . Accept both the numbers in a single line only
Solution

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 ,

฀ By default split( ) function considers , space as a separator

฀ However , we can use any other symbol also as a separator if


we pass that symbol as argument to split( ) function

฀ For example , if we use comma , as a separator then we can


provide comma separated input
Example

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

• eval( ) Function , Command Line Arguments


and Various print( ) Options

• Using the eval( ) Function

• Using Command Line Arguments

• Using format specifiers in Python

• Using the function format( )


Using The Function eval( )

฀ Python has a very interesting function called eval( ) .

฀ This function accepts any valid Python expression and


executes it
Using The Function eval( )

฀ Syntax:
฀ eval(expression)

฀ The argument passed to eval() must follow below mentioned


rules:

฀ It must be given in the form of string

฀ It should be a valid Python code or expression


Examples

• 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

฀ Another important use of eval( ) function is to perform type


conversion .

฀ The eval( ) function interprets the argument inside character string


and coverts it automatically to it’s type.
Example: Same Example
x = eval(‘2.5’) Without eval( ):
print(x) x = ‘2.5’
print(type(x)) print(x)
print(type(x))
Output: Output:
2.5 2.5
<class ‘float’> <class ‘str’>
Using eval( ) With input( )

฀ We can use eval( ) with input( ) function to perform automatic


type conversion of values.

฀ In this way , we will not have to use type conversion functions


like int() , float( ) or bool ()
Example

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))

Suppose user types 25


• Output:
Guess The Output

• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))

• Suppose user types 3.6

• Output:
Guess The Output

• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))

• Suppose user types [10,20,30]

• Output:
Guess The Output

• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))

• Suppose user types Hello

• Output:
Guess The Output

• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))

• Suppose user types “Hello”

• Output:
Command Line Arguments

฀ Command Line Arguments are the values , we can pass while


executing our Python code from command prompt

฀ Syntax: These are called


฀ python prog_name <values> commad line
arguments

฀ For example:
฀ python demo.py 10 20 30

Their main benefit is that they are another mechanism to


provide input to our program
Where Are
Command Line Arguments Stored ?

฀ Command Line Arguments are stored by Python in a special


predefined variable called argv

฀ Following are important features of argv:

฀ This variable itself is stored in a module called sys

฀ So to use it , we must import sys module in our program

฀ The variable argv is actually a list

฀ The name of the program is passed as the first argument which is stored
at the 0th index in argv
Example

Code (suppose name of prog is cmdarg.py):


from sys import argv
print(argv)
print(type(argv))
Suppose we run it as python cmdarg.py 10 20 30
Output:
Accessing Individual Values

฀ argv is a List type object

฀ Lists are index based

฀ They always start from 0th index

฀ So if we want to access individual elements of argv then we can


use the subscript operator passing it the index number
Accessing Individual Values

Code:
from sys import argv
print(argv[0])
print(argv[1])
print(argv[2])

Suppose we run it as python cmdarg.py 10 20


Output:
Guess The Output

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])

Execution: python cmdarg.py

Output:
cmdarg.py
IndexError: list index out of range
Obtaining Number
Of Arguments Passed

฀ The built in function len( ) can be used to get the number of


arguments passed from command prompt

Code:
from sys import argv
n=len(argv)
print("You have passed",n-1,"arguments")
Output:
Using Slicing Operator

฀ A List in Python is also a sequence type like a string

฀ So , it also supports slicing i.e. we can use the


slicing operator [ : ] , to retrieve the list values from any index.

฀ For example , if we don’t want the program name then we can


use the slicing operator passing it the index number 1 as start
index
Example

Code (suppose name of prog is cmdarg.py):


from sys import argv
print(argv[1:])

Execution: python cmdarg.py 10 20 30


Output:
Guess The Output

Code (suppose name of prog is cmdarg.py):


from sys import argv
print(argv[1:])

Execution: python cmdarg.py

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])

Execution: python addnos.py 15 20

Output: By default , Python


treats all the command
First num is 15 line arguments as string
Sec num is 20 values
Their sum is 1520
How To Solve This ?

฀ To solve the previous problem , we will have to type convert


string values to int.

฀ This can be done by using int( ) or eval( ) function


Example

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])

Execution: python cmdarg.py Sachin Kapoor

Output: For Python Sachin and


Kapoor are 2 separate
Hello Sachin arguments , so argv[1]
receives Sachin and argv[2]
receives Kapoor
Guess The Output

If we want to pass Sachin Kapoor as a single argument then we


must enclose it in double quotes
Code:
from sys import argv
print(“Hello”,argv[1])

Execution: python cmdarg.py “Sachin Kapoor”

Output:
Hello Sachin Kapoor
Guess The Output

Code:
from sys import argv
print(“Hello”,argv[1])

Execution: python cmdarg.py ‘Sachin Kapoor’

Output: On command prompt


Hello ‘Sachin only double quoted
strings are treated as
single value.
Using Format Specifiers
With print()

฀ Just like C language Python also allows us to use format


specifiers with variables.

฀ The format specifiers supported by Python are:

฀ %d: Used for int values


฀ %i: Used for int values
฀ %f: Used for float values
฀ %s: Used for string value
฀ %c: Used for single char
Using Format Specifiers
With print()

฀ 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

฀ The number of format specifiers and number of variables


must always match

฀ We should use the specified format specifier to display a


particular value.

฀ For example we cannot use %d for strings

฀ 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()

฀ Python 3 introduced a new way to do string formatting by


providing a method called format( ) in string object

฀ This “new style” string formatting gets rid of the % operator


and makes the syntax for string formatting more regular.
Using The Method 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

• Decision Control Statements


• The if Statement

• Concept of Indentation

• The if-else Statement

• The if-elif-else Statement

• What about ternary operator ?


Decision Control Statements

฀ Decision Control Statements in Python are those statements


which decide the execution flow of our program.

฀ In other words , they allow us to decide whether a particular


part of our program should run or not based upon certain
condition.

฀ The 4 decision control statements in Python are:


฀ if
฀ if….else
฀ if…elif…else
฀ nested if
The if Statement

฀ The if the statement in Python is similar to other languages like


in Java, C, C++, etc.

฀ It is used to decide whether a certain statement or block of


statements will be executed or not .

฀ If a certain condition is true then a block of statement is


executed otherwise not.
The if Statement

฀ Syntax:
if (expression):
statement1
statement2
.
.
statement..n

฀ Some Important Points:


฀ Python does not use { } to define the body of a code block , rather it uses indentation.

฀ A code block starts with indentation and ends with the first unindented line.

฀ The amount of indentation is up to the programmer, but he/she must be consistent


throughout that block.

฀ The colon after if( ) condition is important and is a part of the syntax. However parenthesis
with condition is optional
Exercise

฀ WAP to accept an integer from the user and check whether it


is an even or odd number.
Solution

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 ?

฀ If there are multiple lines in the body of if( ) , then :

฀ Either we can write them inside if( ) by properly indenting them

OR

฀ If we write them just after if ( ) , then we must use semicolon as a separator


What About Multiple Lines ?

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

฀ The if..else statement evaluates test expression and will


execute body of if only when test condition is True.

฀ If the condition is False, body of else is executed.

฀ Indentation is used to separate the blocks.


The if-else Statement

฀ Syntax:
if (expression):
statement 1
statement 2
else:
statement 3
statement 4

Indentation and colon are important for else also


Example

a=eval(input("Enter a number:"))
if(a%2==0):
print("No is even")
else:
print("No is odd")
Exercise

฀ WAP to accept a character from the user and check whether


it is a capital letter or small letter. Assume user will input only
alphabets
Solution

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")

Suppose the input given is A

Output:
TypeError: <= not supported between int and str
Why Did The Exception Occur ?

฀ Recall that, in Python we don’t have character data type and


even single letter data is a string.

฀ So the input “A” , is not converted to UNICODE automatically


because it is still treated as a string value.

฀ Thus , the comparison failed between string and integer.


Solution

฀ The solution is to convert the “A” to it’s corresponding


UNICODE value .

฀ Can you think , how can we do it ?

฀ The answer is , using the function ord( ).

฀ Recall that , this function accepts a single letter string and


returns it’s UNICODE value
Solution

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.

฀ If the condition for if is False, it checks the condition of the


next elif block and so on.

฀ If all the conditions are False, body of else is executed.


The if –elif-else Statement

฀ Syntax:
if (expression):
statement 1
statement 2
elif (expression):
statement 3
statement 4
else:
statement 5
statement 6

Although it is not visible in the syntax , but we can have multiple


elif blocks with a single if block
Exercise

฀ WAP to accept a character from the user and check whether


it is a capital letter or small letter or a digit or some special
symbol
Solution

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

฀ We can have a if...elif...else statement inside


another if...elif...else statement.

฀ This is called nesting in computer programming.

฀ Any number of these statements can be nested inside one


another.

฀ Indentation is the only way to figure out the level of nesting


The nested if Statement

฀ Syntax:
if (expression):
if (expression):
statement 1
statement 2
else:
statement 3
statement 4
statement 5
statement 6
Exercise

฀ WAP to accept 3 integers from the user and without using


any logical operator or cascading of relational operators , find
out the greatest number amongst them
Solution

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.

An year is a leap year if:


It is exactly divisible by 4 AND at the same time
not divisible by 100
OR
it is divisible by 400

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

฀ Many programming languages have an operator called


ternary operator, which is denoted by ? : .

฀ It allows us to write complete if – else statement in just one


line.

฀ For example , C language provides the following form of


ternary operator:

฀ <condition> ? <expression1> : <expression2>


Ternary Operator In Python

฀ But in Python we don’t have a ternary operator officially .

฀ However Python provides us a single line if – else to work just


like ternary operator

฀ Syntax:

฀ <expression1> if <condition> else <expression2>

฀ It first evaluates the condition; if it returns True then


expression1 will be evaluated to give the result, otherwise it will
evaluate expression2.
Example

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

Checking Even Odd Using Single Line if-else


a=eval(input("Enter a number:"))
msg= 'Even no' if a%2==0 else 'Odd No'
print(msg)

Output:
Handling Multiple Conditions

฀ We can handle multiple conditions also using single line if-else

฀ Syntax:
฀ <expression1> if <condition1> else <expression2> if <condition2> else
<expression3>

฀ It first evaluates the condition1; if it returns True then


expression1 will be executed to give the result, otherwise it will
evaluate the condition2; if it returns True then expression2 will
be executed otherwise it will execute expression3.
Example

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

• The while loop

• The while-else loop

• The break , continue and pass Statement


Iterative Statements

฀ There may be a situation when we need to execute a block of


code several number of times.

฀ For such situations , Python provides the concept of loop

฀ A loop statement allows us to execute a statement or group of


statements multiple times
Iterative Statements

฀ The 2 popular loops provided by Python are:

฀ The while Loop

฀ The for Loop

฀ Recall that Python doesn’t provide any do..while loop unlike


C,C++ and Java.
The while Loop

฀ 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.

฀ Each execution of the loop body is known as iteration.

฀ 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

฀ In Python , just like we have an else with if , similarly we also


can have an else part with the while loop.

฀ The statements in the else part are executed, when the


condition is not fulfilled anymore.
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.

฀ Then what is the use of else

฀ To understand this , we need to understand the break statement,


The “break” Statement

฀ Normally a while loop ends only when the test condition in the
loop becomes false.

฀ However , with the help of a break statement a while loop can


be left prematurely,

Now comes the crucial point:


If a loop is left by
break,
the else part is not
executed.
Example

• 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

฀ WAP to accept a string from the user and check whether it


contains any vowel or not.

Sample Output:
Exercise

฀ You have to develop a number guessing game. The program


will generate a random integer secretly. Now it will ask the
user to guess that number . If the user guessed it correctly then
the program prints “Congratulations! You guessed it right” .

฀ If the number guessed by the user is larger than the secret


number then program should print “Number too large” and , if
the number guessed by the user is smaller than the secret
number then program should print “Number too small” .

฀ This should continue until the user guesses the number


correctly or quits . If the user wants to quit in between he will
have to type 0 or negative number
Output
Output
How To Generate Random Number ?

฀ In Python , we have a module named random .

฀ This module contains a function called randint() , which accepts


2 arguments and returns a random number between them
( both included ).

import random
a=random.randint(1,20)
print("Random number is",a)

Output:
The “continue” Statement

฀ The continue statement in Python returns the control to the


beginning of the while loop.

฀ It rejects all the remaining statements in the current iteration


of the loop and moves the control back to the top of the loop.
Example

i=0
while i<10:
i=i+1
if(i%2!=0):
continue
print(i)
Output:
Exercise

฀ Write a program to accept a string from the user and display it


vertically but don’t display the vowels in it.

฀ Sample Output:
Exercise

฀ Write a program to continuously accept integers from the


user until the user types 0 and as soon as 0 is entered display
sum of all the nos entered before 0

฀ Sample Output:
Exercise

฀ Modify the previous code so that if the user inputs negative


integer , your program should ignore it .

฀ Sample Output:
The “pass” Statement

฀ In Python, the pass statement is a no operation statement.

฀ That is , nothing happens when pass statement is executed.

฀ 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

• The for Loop


• The for Loop In Python

• Differences with other languages

• The range( ) Function

• Using for with range( )


The for Loop

฀ Like the while loop the for loop also is a programming


language statement, i.e. an iteration statement, which allows
a code block to be executed multiple number of times.

฀ There are hardly programming languages without for loops.

฀ However the for loop exists in many different flavours, i.e.


both the syntax and the behaviour differs from language to
language
The for Loop

฀ Different Flavors Of “for” Loop:


฀ Count-controlled for loop (Three-expression for loop):
฀ This is by far the most common type. This statement is the one
used by C , C++ and Java . Generally it has the form:
for (i=1; i <= 10; i++)
This kind of for loop is not implemented in Python!

฀ 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

฀ Iterator-based for loop


฀ Finally, we come to the one used by Python. This kind of a for loop
iterates over a collection of items.

฀ In each iteration step a loop variable is set to a value in a


sequence or other data collection.

฀ 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

1. What is the output ?


word="sachin"
if(ch in ["a","e","i","o","u"]):
continue
print(ch,end=" ")

A. schn
B. Error
C. sachin
D. Exception

Correct Answer: B
QUIZ- Test Your Skills

2. What is the output?


i=0
while i<4:
i=i+1
if(i%2!=0):
pass
print("hi",end=" ")
else:
print(i,end=" ")

A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop

Correct Answer: A
QUIZ- Test Your Skills

3. What is the output?


i=0
while i<4:
i=i+1
if(i%2!=0):
continue
print("hi",end=" ")
else:
print(i,end=" ")

A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop

Correct Answer: C
QUIZ- Test Your Skills

4. What is the output?


i=0
while i<4:
i=i+1
if(i%2!=0):
break
print("hi",end=" ")
else:
print(i,end=" ")

A. hi 2 hi 4
B. Syntax Error
C. 24
D. No output

Correct Answer: D
QUIZ- Test Your Skills

5. What is the output ?

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

6. What is the output ?


i=1
while True:
if i%3 == 0:
break
print(i,end=“ “)
i+=1
A. Syntax Error
B. 1 2
C. 1 2 3
D. Blank Screen(No Output)

Correct Answer: A
QUIZ- Test Your Skills

7. What is the output ?

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

8. What is the output ?


x = "abcdef"
i = "i"
while i in x:
print(i, end=" ")

A. abcdef
B. iiiiii
C. Error
D. No output

Correct Answer: D
QUIZ- Test Your Skills

9. What is the output ?


x = "abcdef"
i = “a"
while i in x:
print(i, end=" ")

A. abcdef
B. Infinite loop
C. Error
D. No output

Correct Answer: B
QUIZ- Test Your Skills

10. What is the output ?


x = "abcdef"
i = "a"
while i in x:
x = x[1:]
print(i, end = " ")

A. aaaaaa
B. a
C. Error
D. No output

Correct Answer: B
QUIZ- Test Your Skills

11. What is the output ?


x = 'abcd'
for i in x:
print(i,end=“ “)
x.upper()

A. aBCD
B. ABCD
C. abcd
D. Syntax Error

Correct Answer: C
QUIZ- Test Your Skills

12. What is the output ?


x = 'abcd'
for i in x:
print(i.upper())

A. aBCD
B. ABCD
C. abcd
D. Syntax Error

Correct Answer: B
QUIZ- Test Your Skills

13. What is the output ?


text = "my name is sachin"
for i in text:
print (i, end=", ")

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

14. What is the output ?


text = "my name is sachin"
for i in text.split():
print (i, end=", ")

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

15. What is the output ?


text = "my name is sachin"
for i not in text:
print (i, end=", ")

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

16. What is the output?

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

17. What is the output?


i=2
while True:
if i%3 == 0:
break
print(i,end=“ “)
i += 2

A. Infinite loop
B. 24
C. 23
D. None of the above

Correct Answer: B
The range Function

฀ The range() function is a built-in function in Python, and it


returns a range object.

฀ This function is very useful to generate a sequence of


numbers in the form of a List.

฀ The range( ) function takes 1 to 3 arguments


The range Function
With One Parameter

฀ Syntax:
฀ range(n)

฀ For an argument n, the function returns a range object


containing integer values from 0 to n-1.

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

Example: The function list( ) accepts a range object


and converts it into a list of values .
a=range(10) These values are the numbers from 0 to n-1
where n is the argument passed to the function
b=list(a) range()
print(b)
Output:
What If We Pass
Negative Number ?

Guess: The output is an empty list denoted by


[ ] and it tells us that the function range( )
a=range(-10) is coded in such a way that it always moves
b=list(a) towards right side of the start value which here
is 0.
print(b)
Output: But since -10 doesn’t come towards right of 0, so
the output is an empty list
The range Function
With Two Parameter

฀ Syntax:
฀ range(m,n)

฀ For an argument m,n , the function returns a range object


containing integer values from m to n-1.

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: The output is list of numbers from 1 to 9


because 10 falls towards right of 1
a=range(1,10)
b=list(a)
print(b)
Output:
What If We Pass
First Number Greater?

Guess: The output is an empty list because


as mentioned earlier it traverses towards right
a=range(10,1) of start value and 1 doesn’t come
b=list(a) to the right of 10
print(b)
Output:
Passing Negative Values

฀ We can pass negative start or/and negative stop value to


range( ) when we call it with 2 arguments .

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(7,1,-2) Pay close attention ,


b=list(a) that we are having
start value greater than
print(b) end value , but since
฀ Output: step value is negative ,
so it is allowed

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(2,14,1.5) Note that all three


arguments must be
b=list(a) integers only.
print(b)
฀ 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

฀ We can use 2 argument range() with for also for iterating


through a list of numeric values between a given range

฀ 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

฀ Write a program to accept an integer from the user and


display the sum of all the numbers from 1 to that number.

฀ 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

฀ Write a program to accept an integer from the user and


calculate it’s factorial

฀ 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

฀ Loops can be nested in Python, as they can with other


programming languages.

฀ A nested loop is a loop that occurs within another loop, and


are constructed like so:

฀ 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

฀ Write a program to print the following pattern

Sample Output:
Solution

Code: Output:
for i in range(1,5):
for j in range(1,4):
print("*",end="")
print()
Solution

Can you write the same code using only


single loop ? Output:

Code:
for i in range(1,5):
print("*"*3)
Exercise

฀ Write a program to print the following pattern

Sample Output:
Solution

Code: Output:
for i in range(1,5):
for j in range(1,i+1):
print("*",end="")
print()
Exercise

฀ Write a program to print the following pattern

Sample Output:
Solution

Code: Output:
for i in range(4,0,-1):
for j in range(1,i+1):
print("*",end="")
print()
Exercise

฀ Write a program to accept an integer from the user and


display all the numbers from 1 to that number. Repeat the
process until the user enters 0.
฀ Sample Output:
Solution

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

• User Defined Functions


• What Is A Function ?

• Function V/s Method

• Steps Required For Developing User Defined Function

• Calling A Function

• Returning Values From Function


What Is A Function ?

฀ A function in Python is a collection of statements


having a particular name followed by parenthesis .

฀ To run a function , we have to call it and when we call a


function all the statements inside the function are
executed.

฀ So we don’t have to write the code again and again

฀ This is called code re-usability.


Function V/s Method

฀ Functions are block of codes defined individually .

฀ But if a function is defined inside a class , it becomes a


method

฀ So , methods and functions are same except their


placement in the program.

฀ Also we can call a function directly using it’s name but


when we call a method we have to use either object
name or class name before it
Function V/s Method

For example:
฀ print(“hello”)

฀ Here print( ) is a function as we are calling it directly

฀ message=“Good Morning”
฀ print(message.lower())

฀ Here lower( ) is a method which belongs to the class str


and so it is called using the object message
Steps Required For Function

฀ To create and use a function we have to take 2 steps:

฀ Function Definition: Creating or writing the body of a


function is called defining it. It contains the set of
statements we want to run , when the function execute.

฀ Function Call: A function never runs automatically . So to


execute it’s statements we must call it
Syntax Of Function Definition

def function_name(param 1,param 2, . . .):


statement(s)

฀ Keyword def marks the start of function header.

฀ It is followed by a function name to uniquely identify it.

฀ Parameters (arguments) through which we pass values to a


function. They are optional.

฀ A colon (:) to mark the end of function header.

฀ One or more valid python statements that make up the


function body . All the statements must have same indentation
level
Example Of
Function Definition

def add(a,b):
print("Values are",a,"and",b)
c=a+b
print("Their sum is",c)
How To Call A Function ?

฀ Once we have defined a function, we can call it from


another function, program or even the Python
prompt.

฀ To call a function we simply type the function name with


appropriate parameters.

฀ 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

฀ To return a value or values from a function we have to write


the keyword return at the end of the function body along
with the value(s) to be returned

฀ 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

฀ Write a function called absolute( ) to accept an


integer as argument and return it’s absolute value.
Finally call it to get the absolute value of -7 and 9

฀ 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

฀ Write a function called factorial( ) which accepts a


number as argument and returns it’s factorial.
Finally call the function to calculate and return the
factorial of the number given by the user.

฀ 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

฀ In languages like C or Java , a function can return only one


value . However in Python , a function can return
multiple values using the following syntax:

฀ Syntax:
฀ return <value 1, value 2, value 3, . . . >

฀ For example:
฀ return a,b,c

฀ When we do this , Python returns these values as a tuple,


which just like a list is a collection of multiple values.
Receiving Multiple Values

฀ To receive multiple values returned from a function , we have 2


options:

฀ Syntax 1:
฀ var 1,var 2,var 3=<function_name>()

฀ Syntax 2:
฀ var=<function_name>()

฀ In the first case we are receiving the values in individual variables


. Their data types will be set according to the types of values being
returned

฀ In the second case we are receiving it in a single variable and


Python will automatically make the data type of this variable as tuple
Complete Example

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

• User Defined Functions-II


• Arguments V/s Parameters

• Types Of Arguments
Parameters V/s Arguments?

฀ A lot of people—mix up parameters and arguments,


although they are slightly different.

฀ A parameter is a variable in a method definition.

฀ When a method is called, the arguments are the data we


pass into the method's parameters.
Parameters V/s Arguments?
Types Of Arguments

฀ In Python , a function can have 4 types of arguments:

฀ Positional Argument

฀ Keyword Argument

฀ Default Argument

฀ Variable Length Argument


Positional Arguments

฀ These are the arguments passed to a function in correct


positional order.

฀ Here the number of arguments in the call must exactly


match with number of parameters in the function
definition
Positional Arguments

def attach(s1,s2):
s3=s1+s2 These are called
print("Joined String is:",s3)
POSITIONAL
ARGUMENTS
attach("Good","Evening")

Output:
Positional Arguments

฀ If the number of arguments in call do not match with


the number of parameters in function then we get
TypeError:

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

฀ The problem with positional arguments is that they


always bind to the position of parameters.

฀ So 1st argument will be copied to 1st parameter , 2nd


argument will be copied to 2nd parameter and so on.

฀ Due to this in the previous example the value 150 was


copied to name and “Butter” was copied to price

฀ To solve this problem , Python provides us the concept of


keyword arguments
Keyword Arguments

฀ Keyword arguments are arguments that identify


parameters with their names

฀ With keyword arguments in Python, we can change the


order of passing the arguments without any consequences

฀ 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!

฀ A positional argument can never follow a keyword


argument i.e. the keyword argument should always appear
after positional argument

฀ For example:
฀ def display(num1,num2):
฀ # some code

Now if we call the above function as:


display(10,num2=15)
Then it will be correct. But if we call it as:
display(num1=10,15)
Then it will be a Syntax Error
Default Arguments

฀ For some functions, we may want to make some


parameters optional and use default values in case the user
does not want to provide values for them.

฀ This is done with the help of default argument values.

฀ We can specify default argument values for parameters by


appending to the parameter name in the function definition the
assignment operator (=) followed by the default value.

฀ Syntax:
def function_name(paramname1=value,paramname2=value):
# function body
Complete Example

def greet(name,msg="Good Morning"):


print("Hello",name,msg)

greet("Sachin")
greet("Amit","How are you?")

Output:
Point To Remember!

฀ A function can have any number of default arguments


but once we have a default argument, all the arguments
to it’s right must also have default values.

฀ This means to say, non-default arguments cannot


follow default arguments.
Point To Remember!

฀ For example: if we had defined the function header


above as:

def greet(msg = "Good morning!", name):

฀ Then we would have got the following SyntaxError


Point To Remember!

฀ If a function has default arguments , set then while calling it if we are


skipping an argument then we must skip all the arguments after it
also.
฀ For example: The solution to this problem
def show(a=10,b=20,c=30): is to use default argument as
print(a,b,c) keyword argument :

฀ Now , if we call the above function as : show(5,c=7)


show(5) This will give the output as
฀ It will work and output will be 5 20 30 5 20 7

฀ 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

฀ Write a function called cal_area( ) using default


argument concept which accepts radius and pi as
arguments and calculates and displays area of the Circle.
The value of pi should be used as default argument and
value of radius should be accepted from the user
Solution

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 ?

฀ The error occurred because Python does not support


Function or Method Overloading

฀ Moreover Python understands the latest definition


of a function addnos( ) which takes 3 arguments

฀ Now since we passed 2 arguments only , the call


generated error because Python tried to call the method
with 3 arguments
Solution

฀ The solution to this problem is a technique called variable


length arguments

฀ In this technique , we define the function in such a way that


it can accept any number of arguments from 0 to infinite
Syntax Of
Variable Length Arguments

def <function_name>(* <arg_name>):


Function body

฀ As we can observe , to create a function with variable


length arguments we simply prefix the argument name
with an asterisk.
฀ For example:
def addnos(*a):
฀ The function addnos() can now be called with as many
number of arguments as we want and all the arguments
will be stored inside the argument a which will be internally
treated as tuple
Complete Example

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

฀ Write a function called findlargest( ) which accepts


multiple strings as argument and returns the length of the
largest string as well as the string itself
Solution

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

฀ Modify the previous example so that the function


findlargest( ) now returns the largest string itself and not
it’s length
Solution

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!

฀ A function cannot have 2 variable length arguments. So the


following is wrong:

def addnos(*a,*b):
Point To Remember!

฀ If we have any other argument along with variable length


argument , then it should be set before the variable
length argument
def addnos(n,*a):
sum =n
for x in a:
sum=sum+x
return sum
print(addnos(10,20,30))
print(addnos(10,20,30,40))
Point To Remember!

฀ If we set the other argument used with variable length


argument , after the variable length argument then:
฀ While calling it we must pass it as keyword argument OR
฀ Either it should be set as default argument

def addnos(*a,n): def addnos(*a,n=0):


sum =n sum =n
for x in a: for x in a:
sum=sum+x
sum=sum+x
return sum
return sum
print(addnos(20,30,n=0)) print(addnos(20,30))
print(addnos(20,30,40,n=0)) print(addnos(20,30,40))
Guess The Output

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

• User Defined Functions-III


• Variable Scope

• Local Scope

• Global Scope

• Argument Passing
Variable Scopes

฀ The scope of a variable refers to the places from where we


can see or access a variable.

฀ In Python , there are 4 types of scopes:


฀ Local : Inside a function body
฀ Enclosing: Inside an outer function’s body . We will discuss it
later
฀ Global: At the module level
฀ Built In: At the interpreter level

฀ In short we pronounce it as LEGB


Global Variable

฀ GLOBAL VARIABLE

฀ A variable which is defined in the main body of a file is called


a global variable.

฀ It will be visible throughout the file


Local Variable

฀ LOCAL VARIABLE
฀ A variable which is defined inside a function is local to that function.

฀ It is accessible from the point at which it is defined until the end of


the function.

฀ It exists for as long as the function is executing.

฀ Even the parameter in the function definition behave like local


variables

฀ When we use the assignment operator (=) inside a function,


it’s default behaviour is to create a new local variable – unless
a variable with the same name is already defined in the local
scope.
Example

s = "I love Python"


Since the variable s
def f(): is global , we can
print(s) access it from
anywhere in our
f() code

Output:
I love Python
Example

s = "I love Python" Since we have not


def f(): called the function
f( ) , so the
print(s) statement print(s)
will never get a
chance to run
Output:
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"

Since we have called


Output: the function f( ) ,
NameError ! before declaring
variable s , so we get
NameError!
Example

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

s="I love Python"


def f():
s="I love C"
print(s)
If a variable with
f() same name is defined
print(s) inside the scope of
function as well then
Python creates a new
Output: variable in local scope
of the function and
I love C uses it
I love Python
Example

What if we want to use the same global variable


inside the function also ?
s="I love Python"
def f():
global s
To do this , we need a
s="I love C" special keyword in
print(s) Python called global.
f() This keyword tells
Python , not to create
print(s) any new variable ,
rather use the variable
Output: from global scope
I love C
I love C
Guess The Output ?

s="I love Python"


def f():
print(s) Now , this is a special case! .
In Python any variable
s="I love C" which is changed or created
print(s) inside of a function is local,
if it hasn't been declared as
f() a global variable. To tell
Python, that we want to use
print(s) the global variable, we have
to explicitly state this by
using the keyword "global"
Output:
UnboundLocalError!:
Local variable s referenced before assignment
Guess The Output ?

s="I love Python"


def f():
global s
print(s)
s="I love C"
print(s)
f()
print(s)

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)

print ('global : ',a)


f()
print ('global : ',a)
g()
print ('global : ',a)
h()
print ('global : ',a)
Guess The Output ?

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 ?

def foo(x, y): Output:


global a 42 17 4 17
42 15 3 4
a = 42
x,y = y,x
b = 33
b = 17
c = 100
print(a,b,x,y)

a, b, x, y = 1, 15, 3,4
foo(17, 4)
print(a, b, x, y)
Argument Passing

฀ There are two ways to pass arguments/parameters to


function calls in C programming:

฀ Call by value

฀ Call by reference.
Call By Value

฀ In Call by value, original value is not modified.

฀ In Call by value, the value being passed to the function is


locally stored by the function parameter as formal
argument

฀ So , if we change the value of formal argument, it is


changed for the current function only.

฀ These changes are not reflected in the actual argument’s


value
Call By Reference

฀ In Call by reference , the location (address) of actual


argument is passed to formal arguments, hence any
change made to formal arguments will also reflect in actual
arguments.

฀ In Call by reference, original value is


modified because we pass reference (address).
What About Python ?

฀ When asked whether Python function calling model is


"call-by-value" or "call-by-reference", the correct
answer is: neither.

฀ What Python uses , is actually called "call-by-object-


reference"
A Quick Recap Of Variables

฀ We know that everything in Python is an object.

฀ All numbers , strings , lists , tuples etc in Python are


objects.

฀ Now , recall , what happens when we write the following


statement in Python:
x=10

฀ An object is created in heap , storing the value 10 and x


becomes the reference to that object.
A Quick Recap Of Variables

฀ Also we must recall that in Python we have 2 types of data


: mutable and immutable.

฀ Immutable types are those which do not allow


modification in object’s data and examples are int , float ,
string ,tuple etc

฀ Mutable types are those which allow us to modify object’s


data and examples are list and dictionary
What Is
Call By Object Reference ?

฀ Now , when we pass immutable arguments like integers,


strings or tuples to a function, the passing acts like call-
by-value.

฀ The object reference is passed to the function


parameters.

฀ They can't be changed within the function, because they


can't be changed at all, i.e. they are immutable.
What Is
Call By Object Reference ?

฀ It's different, if we pass mutable arguments.

฀ They are also passed by object reference, but they can


be changed in place in the function.

฀ If we pass a list to a function, elements of that list can be


changed in place, i.e. the list will be changed even in the
caller's scope.
Guess The Output ?

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

• User Defined Functions-IV


• Anonymous Functions OR Lambda Function
What Are Anonymous
Functions ?

฀ An anonymous function is a function that is defined


without a name.

฀ While normal functions are defined using


the def keyword, we define anonymous functions using
the lambda keyword.

฀ Hence, anonymous functions are also called lambda


functions.
Syntax Of Lambda Functions

฀ Syntax:
lambda [arg1,arg2,..]:[expression]

฀ lambda is a keyword/operator and can have any number of arguments.

฀ But it can have only one expression.

฀ Python evaluates the expression and returns the result automatically.


What Is An Expression ?

฀ An expression here is anything that can return some


value.

฀ The following items qualify as expressions.

฀ Arithmetic operations like a+b and a**b

฀ Function calls like sum(a,b)

฀ A print statement like print(“Hello”)


So, What Can Be Written In
Lambda Expression ?

฀ Assignment statements cannot be used in lambda ,


because they don’t return anything, not even None (null).

฀ Simple things such as mathematical operations, string


operations etc. are OK in a lambda.

฀ Function calls are expressions, so it’s OK to put a function call


in a lambda, and to pass arguments to that function.

฀ Even functions that return None, like the print function in


Python 3, can be used in a lambda.

฀ Single line if – else is also allowed as it also evaluates the


condition and returns the result of true or false expression
How To Create
Lambda Functions ?

฀ Suppose, we want to make a function which will


calculate sum of two numbers.

฀ In normal approach we will do as shown below:

def add(a,b):
return a+b

฀ In case of lambda function we will write it as:

lambda a,b: a+b


Why To Create
Lambda Functions ?

฀ A very common doubt is that when we can define our


functions using def keyword , then why we require
lambda functions ?

฀ The most common use for lambda functions is in code


that requires a simple one-line function, where it would
be an overkill to write a complete normal function.

฀ We will explore it in more detail when we will discuss two


very important functions in Python called map( ) and
filter( )
How To Use
Lambda Functions ?

฀ There are 2 ways to use a Lambda Function.

฀ Using it anonymously in inline mode

฀ Using it by assigning it to a variable


How To Use
Lambda Functions ?

฀ Using it as anonymous function

print((lambda a,b: a+b)(2,3))

Output:
How To Use
Lambda Functions ?

฀ Using it by assigning it to a variable

What is happening in this code ?


sum=lambda a,b: a+b
The statement lambda a,b:a+b ,
is creating a FUNCTION OBJECT
print(sum(2,3)) and returning that object . The
print(sum(5,9)) variable sum is referring to that
object. Now when we write
sum(2,3), it behaves like function
Output: call
Guess The Output ?

sum=lambda a,b: a+b Since functions also are objects


in Python , so they have their a
unique memory address as well
print(type(sum)) as their corresponding class as
function
print(sum)

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

฀ Write a lambda function that returns the first


character of the string passed to it as argument

Solution:
firstchar=lambda str: str[0]

print(“First character of Bhopal :",firstchar("Bhopal"))


print(“First character of Sachin :",firstchar("Sachin"))

Output:
Exercise

฀ Write a lambda function that returns the last


character of the string passed to it as argument

Solution:

lastchar=lambda str: str[-1]

print("Last character of Bhopal :",lastchar("Bhopal"))


print("Last character of Sachin :",lastchar("Sachin"))
Output:
Exercise

฀ Write a lambda function that returns True or False


depending on whether the number passed to it as
argument is even or odd

Solution:

iseven=lambda n: n%2==0
print("10 is even :",iseven(10))
print("7 is even:",iseven(7))
Output:
Exercise

฀ Write a lambda function that accepts 2 arguments


and returns the greater amongst them

Solution:

maxnum=lambda a,b: a if a>b else b


print("max amongst 10 and 20 :",maxnum(10,20))
print("max amongst 15 and 5 :",maxnum(15,5))

Output:
PYTHON
LECTURE 23
Today’s Agenda

• User Defined Functions V


• The map( ) Function
• The filter( ) Function
• Using map( ) and filter( ) with Lambda Expressions
What Is map( ) Function?

฀ As we have mentioned earlier, the advantage of the lambda


operator can be seen when it is used in combination with the
map() function.

฀ map() is a function which takes two arguments:

฀ r = map(func, iterable)

฀ The first argument func is the name of a function and the


second argument , iterable ,should be a sequence (e.g. a list ,
tuple ,string etc) or anything that can be used with for loop.

฀ map() applies the function func to all the elements of the


sequence iterable
What Is map( ) Function?

฀ To understand this , let’s solve a problem.

฀ Suppose we want to define a function called square( ) that


can accept a number as argument and returns it’s square.

฀ The definition of this function would be :

def square(num):
return num**2
What Is map( ) Function?

฀ Now suppose we want to call this function for the following


list of numbers:

฀ mynums=[1,2,3,4,5]

฀ One way to do this , will be to use a for loop

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

฀ Another way to solve the previous problem is to use the


map( ) function .

฀ The map( ) function will accept 2 arguments from us.

฀ The first argument will be the name of the function square

฀ The second argument will be the list mynums.

฀ It will then apply the function square on every element of


mynum and return the corresponding result as map
object
Previous Code Using map( )

def square(num):
return num**2

mynums=[1,2,3,4,5]
result=map(square,mynums)
print(result)
Output:

฀ As we can observe , the return value of map( ) function is a map


object

฀ To convert it into actual numbers we can pass it to the function list( )


Previous Code Using map( )

def square(num): def square(num):


return num**2 return num**2

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( )

To make it even shorter we can directly pass the list( ) function to


the function print()
def square(num):
return num**2

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

฀ Write a function called inspect( ) that accepts a


string as argument and returns the word EVEN if
the string is of even length and returns it’s first
character if the string is of odd length

Now call this function for first 3 month names


Solution

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?

฀ Like map( ) , filter( ) is also a function that is very commonly used in


Python .

฀ The function filter ( ) takes 2 arguments:

filter(function, sequence)

฀ The first argument should be a function which must return a boolean value

฀ The second argument should be a sequence of items.

฀ Now the function filter( ) applies the function passed as argument to


every item of the sequence passed as second argument.

฀ 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?

฀ To understand this , let’s solve a problem.

฀ Suppose we want to define a function called


check_even( ) that can accept a number as argument
and return True if it is even , otherwise it should return
False

฀ The definition of this function would be :

def check_even(num):
return num%2==0
What Is filter( ) Function?

฀ Now suppose we have a list of numbers and we want to


extract only even numbers from this list

฀ mynums=[1,2,3,4,5,6]

฀ One way to do this , will be to use a for loop

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

฀ Another way to solve the previous problem is to use the filter( )


function .

฀ The flter( ) function will accept 2 arguments from us.

฀ The first argument will be the name of the function check_even

฀ The second argument will be the list mynums.

฀ It will then apply the function check_even on every element of


mynum and if check_even returned True for that element
then filter( ) will return that element as a part of it’s return
value otherwise that element will not be returned
Previous Code Using filter( )

def check_even(num):
return num%2==0

mynums=[1,2,3,4,5,6]
print(filter(check_even,mynums))

Output:

฀ As we can observe , the return value of filter( ) function is a filter


object

฀ To convert it into actual numbers we can pass it to the function list( )


Previous Code Using filter( )

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

mynums=[1,2,3,4,5] For each value in


print(list(filter(f1,mynums))) mynums , since f1( ) has
not returned any value ,
Output: by default it’s return
[] value is assumed to be
None which is a
representation of False.
Thus filter( ) returned an
empty list.
Guess The Output

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

For every even number


mynums=[1,2,3,4,5]
the return value of the
print(list(map(f1,mynums))) function f1( ) will be 0
and for every odd
number the return value
Output: will be 1. Thus map( ) has
returned a list containing
[1,0,1,o,1] 1 and 0 for each number
in mynums based upon
even and odd.
Guess The Output

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( )

฀ The best use of Lambda Expression is to use it with


map( ) and filter( ) functions

฀ Recall that the keyword lambda creates an anonymous


function and returns it’s address.
Using Lambda Expression
With map( ) And filter( )

฀ So , we can pass this lambda expression as first


argument to map( ) and filter() functions , since their
first argument is the a function object reference

฀ In this way , we wouldn’t be required to specially create a


separate function using the keyword def
Using Lambdas With map( )

def square(num): To convert the above code using lambda


return num**2 ,we have to do 2 changes:

mynums=[1,2,3,4,5] 1. Remove the function square( )


sqrnum=list(map(square,mynums)
print(squrnum) 1. Rewrite this function as lambda in
place of first argument while calling
the function map( )

Following will be the resultant code:

mynums=[1,2,3,4,5]
sqrnum=list(map(lambda num: num*num,mynums))
print(sqrnum)
Exercise

฀ Write a lambda expression that accepts a string as


argument and returns it’s first character

Now use this lambda expression in map( ) function


to work on for first 3 month names
Solution

months=["January","February","March"]
print(list(map(lambda mystring: mystring[0],months)))

Output:
Exercise

฀ Write a lambda expression that accepts a string as


argument and returns the word EVEN if the string
is of even length and returns it’s first character if
the string is of odd length

Now use this lambda expression in map( ) function


to work on for first 3 month names
Solution

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)))

To convert the above code using lambda ,we have to same 2


steps as before.

Following will be the resultant code:

mynums=[1,2,3,4,5,6]
print(list(filter(lambda num:num%2==0 ,mynums)))
Exercise

฀ Write a lambda expression that accepts a character


as argument and returns True if it is a vowel
otherwise False

Now ask the user to input his/her name and display


only the vowels in the name . In case the name does
not contain any vowel display the message No vowels
in your name
Solution

name=input("Enter your name:")


vowels=list(filter(lambda ch: ch in "aeiou" ,name))
if len(vowels)==0:
print("No vowels in your name")
else:
print("Vowels in your name are:",vowels)

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 ?

฀ Unlike C++ or Java, Python doesn’t has arrays.

฀ So , to hold a sequence of values, Python provides us a


special built in class called ‘list’ .

฀ Thus a list in Python is defined as a collection of


values.
Important Characteristics
Of A List

฀ The important characteristics of Python lists are as follows:

฀ Lists are ordered.

฀ Lists can contain any arbitrary objects.

฀ List elements can be accessed by index.

฀ Lists can be nested to arbitrary depth.

฀ Lists are mutable.

฀ Lists are dynamic.


How To Create A List ?

฀ In Python, a list is created by placing all the items (elements)


inside a square bracket [ ], separated by commas.

฀ It can contain heterogeneous elements also.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]
Other Ways Of Creating List

฀ We also can create a list by using the list( ) function

# Create an empty list


list1 = list()
# Create a list with elements 22, 31, 61
list2 = list([22, 31, 61])
# Create a list with strings
list3 = list(["tom", "jerry", "spyke"])
# Create a list with characters p, y, t, h, o, n
list4 = list("python")
Printing The List

฀ We can print a list in three ways:

฀ Directly passing it to the print( ) function

฀ Accessing individual elements using subscript operator [ ]

฀ Accessing multiple elements using slice operator [ : ]


Printing The List

mynums=[10,20,30,40,50]
print(mynums)

Output:
[10,20,30,40,50]
Accessing Individual Elements

฀ A list in Python has indexes running from 0 to size-1

฀ For example:

฀ mynums=[10,20,30,40,50]

฀ The above code will create a logical diagram in memory,


where positive indexing will go from 0 to 4 and negative
indexing from -1 to -5
Accessing Individual Elements
Accessing Individual Elements

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

฀ Redesign the previous code using for loop only to


traverse the list in reverse order. Don’t use slice
operator
Solution

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

฀ The most common way of adding a new element to an existing


list is by calling the append( ) method.

฀ 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

฀ Write a program to accept five integers from the


user , store them in a list . Display these integers
and also display their sum

฀ 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

฀ Just like we can apply slice operator with strings , similarly


Python allows us to apply slice operator with lists also.

฀ Syntax: list_var[x:y]

• x denotes the start index of slicing and y denotes the end


index . But Python ends slicing at y-1 index.
The Slicing Operator

• 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

• String slicing can accept a third parameter also after the


two index numbers.

• The third parameter is called step value.

• So the complete syntax of slicing operator is:

s[begin:end:step]

• Step value indicates how many characters to move forward


after the first character is retrieved from the string and it’s
default value is 1 , but can be changed as per our choice.
Using Step Value

• Another point to understand is that if step is positive


or not mentioned then
• Movement is in forward direction ( L฀R)
• Default for start is 0 and end is len

• But if step is negative , then


• Movement is in backward direction (R฀L)
• Default for start is -1 and end is –(len+1)
The Slicing Operator

• 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

฀ Python allows us to edit/change/modify an element in


a list by simply using it’s index and assigning a new value
to it
Syntax:
list_var[index_no]=new_value
Example
sports=["cricket","hockey","football"]
print(sports)
sports[1]="badminton"
print(sports)
Output
Guess The Output ?

sports=["cricket","hockey","football"]
print(sports)
sports[3]="badminton"
print(sports)

Output:
Modifying Multiple Values

฀ Python allows us to modify multiple continuous list


values in a single statement , which is done using the
regular slice operator.
Syntax:
list_var[m:n]=[list of new value ]
Example:
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=["badminton","tennis"]
print(sports)
Output:
Guess The Output ?

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

฀ Python allows us to delete an item from the list by calling


the operator/keyword called del
Syntax:
del list_var[index_no]

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

฀ Python allows us to delete multiple items from the list in


2 ways:

฀ By assigning empty list to the appropriate slice

OR

฀ By passing slice to the del operator


Example

฀ Assigning Empty List

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

฀ Passing slice to del operator

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

฀ We can delete or remove the entire list object as well as


it’s reference from the memory by passing the list object
reference to the del operator
Syntax:
del list_var
Example:
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports
print(sports)
Output:
Appending Or Prepending
Items To A List

฀ Additional items can be added to the start or end of a list


using the + concatenation operator or the += compound
assignment operator

฀ The only condition is that the item to be concatenated must be a


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

฀ Python allows us to multiply a list by an integer and


when we do so it makes copies of list items that many
number of times, while preserving the order.
฀ Syntax:
list_var * n
Example:
sports=["cricket","hockey","football"]
sports=sports*3
print(sports)
Output:
Guess The Output ?

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

฀ We can apply membership operators in and not in on


the list to search for a particular item
Syntax:
element in list_var

Example:
sports=["cricket","hockey","football"]
print("cricket" in sports)

Output:
Exercise

฀ Write a program to accept 5 unique integers from


the user. Make sure if the integer being entered is
already present in the list your code displays the
message “Item already present” and ask the user to
reenter the integer.
Output:
Solution

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

print("integers inputted by you are:")


for x in myints:
print(x)
Exercise

฀ Write a program to accept 2 lists from the user of 5


nos each . Assume each list will have unique nos
Now find out how many items in these lists are
common .
Output:
Exercise

฀ Rewrite the previous code so that your code alos


displays the items which are common in both the
lists

Output:
PYTHON
LECTURE 26
Today’s Agenda

• List -III
• Built In Functions For List
Built In Functions For List

฀ There are some built-in functions in Python that we can


use on lists.

฀ These are:
฀ len()
฀ max()
฀ min()
฀ sum()
฀ sorted()
฀ list()
฀ any()
฀ all()
The len( ) Function

฀ Returns the number of items in the list


Example:
fruits=["apple","banana","orange",None]
print(len(fruits))

Output:
4
The max( ) Function

฀ Returns the greatest item present in the list

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

฀ Returns the least item present in the list

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

฀ Returns the sum of all the items present in the list .


However items must be of Numeric or boolean type

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

฀ Returns a sorted version of the list passed as argument.

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

฀ To sort the list in descending order , we can pass the


keyword argument reverse with value set to True to
the function sorted( )

Example:
nums=[3,1,5,2]
print(sorted(nums,reverse=True))

Output:
The list( ) Function

฀ The list( ) function converts an iterable i.e tuple ,


range, set , dictionary and string to a list.
Syntax:
list(iterable)

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

฀ The any( ) function accepts a List as argument and


returns True if atleast one element of the List is True. If
not, this method returns False. If the List is empty, then
also it returns False
Syntax:
list(iterable)

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

฀ The all( ) function accepts a List as argument and returns


True if all the elements of the List are True or if the
List is empty .If not, this method returns False.

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

฀ There are some methods also in Python that we can use on


lists.

฀ These are:
฀ append()
฀ extend()
฀ insert()
฀ index()
฀ count()
฀ remove()
฀ pop()
฀ clear()
฀ sort()
฀ reverse()
The append( ) Method

฀ Adds a single element to the end of the list . Modifies the


list in place but doesn’t return anything

Syntax:
list_var.append(item)

Example:
primes=[2,3,5,7]
primes.append(11)
print(primes)
Output:
Guess The Output ?

animal = ['cat', 'dog', 'rabbit']


wild_animal = ['tiger', 'fox']
animal.append(wild_animal)
print(animal) It's important to notice that,
append() adds entire list as a
single element .
If we need to add items of a list to
the another list (rather than the
list itself), then we must use the
Output: extend() method .
Guess The Output ?

animal = ['cat', 'dog', 'rabbit']


wild_animal = ['tiger', 'fox']
animal.append(wild_animal)
print(animal[3])
print(animal[3][0])
print(animal[3][0][0])
print(animal[3][1][0])

Output:
Exercise

฀ Write a program to accept an alphanumeric string


from the user. Now extract only digits from the
given input and add it to the list . Finally print the
list as well as it’s sum. Make sure your list contains
numeric representation of digits

Output:
Solution

text=input("Enter an alphanumeric string:")


nums=[]
for x in text:
if x in "0123456789":
nums.append(int(x))
print(nums)
The extend( ) Method

฀ extend() also adds to the end of a list, but the argument


is expected to be an iterable.
฀ The items in <iterable> are added individually.
฀ Modifies the list in place but doesn’t return anything

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 ?

animal = ['cat', 'dog', 'rabbit']


wild_animal = ['tiger', 'fox']
animal.extend(wild_animal)
print(animal)

Output:
Guess The Output ?

animal = ['cat', 'dog', 'rabbit']


wild_animal = ['tiger', 'fox']
animal.extend(wild_animal)
print(animal[3])
print(animal[3][0])
print(animal[3][1])

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

฀ The insert() method inserts the element to the list at the


given index.
฀ Modifies the list in place but doesn’t return anything

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

฀ Write a program to accept any 5 random integers


from the user and add them in a list in such a way
that list always remains sorted. DO NOT USE THE
FUNCTION sort( )

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

฀ The index() method searches an element in the list and


returns it’s index.
฀ If the element occurs more than once it returns it’s
smallest/first position.
฀ If element is not found, it raises a ValueError exception

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 ?

vowels = ['a', 'e', 'i', 'o', 'i', 'u']


pos = vowels.index('e')
print('The index of e:',pos)
pos = vowels.index('i')
print('The index of i:',pos)

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 ?

vowels = ['a', 'e', 'i', 'o', 'i', 'u']


pos = vowels.index('f')
print('The index of e:',pos)
pos = vowels.index('i')
print('The index of i:',pos)

Output:
The count( ) Method

฀ The count() method returns the number of


occurrences of an element in a list

฀ In simple terms, it counts how many times an element has


occurred in a list and returns it.

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 ?

vowels = ['a', 'e', 'i', 'o', 'i', 'u']


x = vowels.count('i')
print("i occurs",x,"times")
x = vowels.count('e')
print("e occurs",x,"times")
x = vowels.count('j')
print("j occurs",x,"times")

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 ?

strings = ['Cat', 'Bat', 'Sat', 'Cat', 'cat', 'Mat']


x=strings.count("Cat")
print("Cat occurs",x,"times")

Output:
The remove( ) Method

฀ The remove() method searches for the given element in


the list and removes the first matching element.

฀ If the element(argument) passed to the remove()


method doesn't exist, ValueError exception is thrown.

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)

฀ Important points about pop( ) method:

฀ If the index passed to the pop() method is not in the range, it throws IndexError:
pop index out of range exception.

฀ The parameter passed to the pop() method is optional. If no parameter is passed,


the default index -1 is passed as an argument which returns the last element

฀ 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 ?

fruits = ['apple', 'banana', 'cherry']


print(fruits)
print(fruits.pop(1))
print(fruits)

Output:
Guess The Output ?

fruits = ['apple', 'banana', 'cherry']


print(fruits)
print(fruits.pop())
print(fruits)

Output:
Guess The Output ?

fruits = ['apple', 'banana', 'cherry']


print(fruits)
print(fruits.pop(3))
print(fruits)

Output:
Guess The Output ?

fruits = ['apple', 'banana', 'cherry']


print(fruits)
print(fruits.pop(-3))
print(fruits)

Output:
Guess The Output ?

fruits = ['apple', 'banana', 'cherry']


print(fruits)
print(fruits.pop(-4))
print(fruits)

Output:
del v/s pop( ) v/s remove( )

฀ pop( ) : Takes Index , removes element & returns it

฀ remove( ) : Takes value, removes first occurrence and


returns nothing

฀ del : Takes index, removes value at that index and returns


nothing

฀ Even their exceptions are also different if index is wrong or


element is not present:
฀ pop() : throws IndexError: pop index out of range
฀ remove(): throws ValueError: list.remove(x): x not in list
฀ del: throws IndexError: list assignment index out of range
The clear( ) Method

฀ The clear() method removes all items from the list.


฀ It only empties the given list and doesn't return any value.

Syntax:
list_var.clear( )

Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits)
fruits.clear() Output:
print(fruits)
The sort( ) Method

฀ The sort() method sorts the elements of a given list.

฀ The order can be ascending or descending

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 ?

vowels = ['e', 'a', 'u', 'o', 'i']


vowels.sort()
print(vowels)

Output:
Guess The Output ?

vowels = ['e', 'a', 'u', 'o', 'i']


vowels.sort(reverse=True)
print(vowels)

Output:
Guess The Output ?

a = ["bee", "wasp", "moth", "ant"]


a.sort()
print(a)

Output:
Guess The Output ?

a = ["bee", "wasp", "moth", "ant"]


a.sort(reverse=True)
print(a)

Output:
Guess The Output ?

a = ["bee", "wasp", "moth", "ant"]


a.sort(key=len)
print(a)

Output:
Guess The Output ?

a = ["january", "february", "march"]


a.sort(key=len,reverse=True)
print(a)

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

฀ We also can pass our own function name to be used as key


but it should take only 1 argument and return some value
based on that argument.

฀ This return value will be used by Python as key to


sorting
Guess The Output ?

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 ?

student_rec = [['john', 'A', 12],['jane', 'B', 7],['dave',


'B', 10]]
student_rec.sort()
print(student_rec)

Output:
Guess The Output ?

def myFunc(val):
return val[2]

student_rec = [['john', 'A', 12],['jane', 'B', 7],['dave',


'B', 10]]
student_rec.sort(key=myFunc)
print(student_rec)

Output:
The reverse( ) Method

฀ The reverse() method reverses the elements of a given list.

฀ It doesn't return any value. It only reverses the elements and


updates the list.

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 ?

฀ Comprehensions are constructs that allow sequences to be


built from other sequences.

฀ In simple words to build a List from another List or Set from


another Set , we can use Comprehensions

฀ Python 2.0 introduced list comprehensions and Python


3.0 comes with dictionary and set comprehensions.
Understanding
List Comprehension

฀ To understand List comprehensions let’s take a


programming challenge.

฀ Suppose you want to take the letters in the word “Bhopal”,


and put them in a list.

฀ Can you tell in how many ways can you do this ?

฀ Till now , we know 2 ways to achieve this:


฀ Using for loop
฀ Using lambda
Using “for” Loop

text="Bhopal"
myList=[]
for x in text:
myList.append(x)
print(myList)

Output:
Using Lambda

myList=list(map(lambda x:x ,"Bhopal"))


print(myList)

Output:
Understanding
List Comprehension

฀ Now , we can solve the same problem by using List


Comprehension also .

฀ The advantage is that List Comprehensions are 35%


faster than FOR loop and 45% faster than map
function
Understanding
List Comprehension

฀ To understand this , look at the same code using List


Comprehension:

myList=[x for x in "Bhopal"]


print(myList)

Output:
Syntax For
List Comprehension

฀ Syntax:

list_variable = [x for x in iterable <test_cond>]

฀ Explanation

฀ For a Python List Comprehension, we use the delimiters for a list-


square brackets.

฀ Inside those, we use a for-statement on an iterable.

฀ Then there is an optional test condition we can apply on each


member of iterable

฀ Finally we have our output expression


Exercise

฀ Write a program to produce square of nos from 1


to 5 , store them in a list and print the list.

Do the code using:


1. Normal for loop
2. List Comprehension

Output:
Using for Loop

squaresList=[]
for i in range(1,6):
squaresList.append(i**2)

print(squaresList)
Using List Comprehension

squaresList=[x**2 for x in range(1,6)]


print(squaresList)
Exercise

฀ Write a program to accept a string from the user


and convert each word of the given string to
uppercase , store it in a list and print the list

Do the code using:


1. Normal for loop
2. 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

฀ Write a program to accept 5 integers from the user


and store them in a list . Now display the list and
sum of the elements.

Do the code using:


1. Normal for loop
2. List Comprehension

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

฀ As previously mentioned , it is possible to add a test


condition in List Comprehension.

฀ When we do this , we get only those items from the


iterable for which the condition is True.

฀ Syntax:

list_variable = [x for x in iterable <test_cond>]


Exercise

฀ Write a program to produce square of only odd nos


from 1 to 5 , store them in a list and print the list.

Solution
squaresList=[x**2 for x in range(1,6) if x%2!=0]
print(squaresList)

Output:
Exercise

฀ Create a function called removevowels() which


accepts a string as argument and returns a list with
all the vowels removed from that string

Do this code using:


฀ Normal for loop
฀ List Comprehension

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

฀ Create a function called get_numbers() which


accepts a list of strings , symbols and numbers as
argument and returns a list containing only
numbers from that list.

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

฀ Create a function called getlength() which accepts


a string as argument and returns a list containing
the length of all the words of that string except the
word “the”. Accept the string from the user.

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

฀ List Comprehension allows us to mention more than


one if condition.

฀ To do this we simply have to mention the next if after the


condition of first if

฀ Syntax:

list_variable = [x for x in iterable <test_cond 1> <test cond 2>]


Exercise

฀ Write a program to produce square of only those


numbers which are divisible by 2 as well as 3 from
1 to 20 , store them in a list and print the list.

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

฀ Write a function called get_upper( ) which accepts


a string as argument and returns a list containing
only upper case letters but without any vowels of
that string. Accept the string from the user as input

Output:
Solution

def get_upper (text):


myList=[x for x in text if 65<=ord(x)<=90 if x not in "AEIOU"]
return myList

text=input("Type a string:")
myList=get_upper(text)
print(myList)
What About
Logical Operators ?

฀ List Comprehension allows us to use logical or/and


operator also but we should use only 1 if statement

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

฀ Write a function called remove_min_max( ) which


accepts a list as argument and removes the
minimum and maximum elements from the list
and returns it

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

฀ List Comprehension allows us to put if- else statements


also

฀ But since in a comprehension, the first thing we specify is


the value to put in a list, so we put our if-else in place of
value.

฀ Syntax:

list_variable = [expr1 if cond else expr2 for x in iterable ]


Example

myList=["Even" if i%2==0 else "Odd" for i in range(1,11)]


print(myList)

Output:
Nested
List Comprehension

฀ List Comprehension can be nested also.

฀ To understand this , look at the code in the next slide and


figure out it’s output
Nested
List Comprehension

a=[20,40,60]
b=[2,4,6] Explanation:

c=[] The code is multiplying


every element of list a , with
for x in a: every element of list b and storing
for y in b: the product in list c
c.append(x * y)
print(c)

Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Nested
List Comprehension

฀ Now the same code can be rewritten using Nested List


Comprehension.

฀ To do this , we will condense each of the lines of code into


one line, beginning with the x * y operation.

฀ This will be followed by the outer for loop, then the


inner for loop.
Example

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

฀ Write a function called flatten( ) which accepts a


nested list as argument and returns a single list
containing all the elements of the nested list

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 ?

฀ Python provides another type that is an ordered


collection of objects.

฀ This type is called a tuple.


Differences With List

฀ Tuples are identical to lists in all respects, except for the


following properties:

฀ Tuples are defined by enclosing the elements in parentheses (())


instead of square brackets ([]).

฀ Tuples are immutable.


Advantages Of Tuple Over List

฀ Program execution is faster when manipulating a


tuple than it is for the equivalent list.

฀ They prevent accidental modification.

฀ There is another Python data type called a dictionary,


which requires as one of it’s components a value that is of
an immutable type. A tuple can be used for this purpose,
whereas a list can’t be.
How To Create A Tuple ?

฀ As mentioned before a tuple is created by placing all the items


(elements) inside a parenthesis ( ), separated by commas.

฀ It can contain heterogeneous elements also.

# empty tuple
my_tuple = ()

# tuple having integers


my_tuple = (1, 2, 3)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
Guess The Output ?

my_tuple = (2) Why did it happen ?


print(my_tuple)
print(type(my_tuple)) Since parentheses are also
used to define operator
precedence in expressions ,
so , Python evaluates
Output: the expression (2) as simply
the integer 2 and
creates an int object.
So , How To Create A
1 Element Tuple ?

฀ To tell Python that we really want to define a singleton


tuple, include a trailing comma (,) just before the
closing parenthesis.

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 and unpacking is another thing which is


commonly used with tuples.

฀ 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

฀ After running this code, we have x = 1, y = 2 and z = 3.

฀ The value of the tuple a is unpacked into the 3 variables


x, y and z.

฀ Note that the number of variables has to exactly match the


number of elements in the tuple, or there will be an exception.
Uses Of Packing
And Unpacking

฀ In the previous code , the variable a is just used as a


temporary store for the tuple.

฀ We also can leave the middle-man and do this:


x, y, z = 1, 2, 3

฀ After running this code, as before, we have x = 1, y =2


and z = 3.

฀ But can you guess what Python is doing internally ?


Internal Working

฀ First the values are packed into a tuple:

฀ Next, the tuple is assigned to the left hand side of the = sign:

฀ Finally, the tuple is unpacked into the variables:


Swapping Of 2 Variables

฀ We have seen the following code many times before which


swaps the variables a and b :
a = 10
b = 20
b, a = a, b

฀ Now , can you tell what is happening internally ?

฀ First, a and b get packed into a tuple.


฀ Then the tuple gets unpacked again, but this time into
variables b then a.
฀ So the values get swapped!
Returning Multiple Values
From Function

def calculate(a,b): Here Python will do the


following:
c=a+b 1. It will pack the values of
c and d in a tuple
d=a-b 2. Then it will unpack this
tuple into the variables
return c,d x and y
3. In the second call since
x,y=calculate(5,3) z is a single variable , it
is automatically
converted into a tuple
print("Sum is",x,"and difference is",y)
z=calculate(15,23)
print("Sum is",z[0],"and difference is",z[1])

Output:
Guess The Output ?

def add(a,b,c,d): Why did it happen ?


print("Sum is",a+b+c+d) Since we are passing mytuple as a
single argument , so Python
is giving exception.
mytuple=(10,20,30,40)
What is the solution ?
add(mytuple)
To overcome this we must
unpack mytuple to 4 individual
values. This can be done by
prefixing mytuple with
Output: a *. So the call will be
add(*mytuple)
Solution

def add(a,b,c,d):
print("Sum is",a+b+c+d)

mytuple=(10,20,30,40)
add(*mytuple)

Output:
Accessing The Tuple

฀ Similar to a list , we can access/print a tuple in three


ways:

฀ Directly passing it to the print( ) function

฀ Accessing individual elements using subscript operator [ ]

฀ Accessing multiple elements using slice operator [ : ]


Printing The Entire Tuple

values=(10,20,30,40)
print(values)

Output:
Accessing
Individual Elements

฀ Like a list , a tuple also has indexes running from 0 to


size-1

฀ For example:

฀ mynums=(10,20,30,40,50)

฀ The above code will create a logical diagram in memory,


where positive indexing will go from 0 to 4 and
negative indexing from -1 to -5
Accessing
Individual Elements
Accessing Individual
Elements

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

Given the tuple below that represents the Arijit Singh’s


Aashiqui 2 songs.
Write code to print the album details, followed by a listing of
all the tracks in the album.
album="Aashiqui 2", 2013 ,"Arijit Singh",((1,"Tum hi
ho"),(2,"Chahun Mai Ya Na"),(3,"Meri Aashiqui"),(4,"Aasan
Nahin Yahaan"))
Output:
Solution

album="Aashiqui 2","Arijit Singh",2013,((1,"Tum hi


ho"),(2,"Chahun Mai Ya Na"),(3,"Meri
Aashiqui"),(4,"Aasan Nahin Yahaan"))

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]

• x denotes the start index of slicing and y denotes the end


index . But Python ends slicing at y-1 index.
The Slicing Operator

• 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

• The concept of step value in slicing with tuple is also


same as that with list
• Movement is in forward direction ( L฀R)
• Default for start is 0 and end is len

• But if step is negative , then


• Movement is in backward direction (R฀L)
• Default for start is -1 and end is –(len+1)
The Slicing Operator

• 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

฀ Unlike lists, tuples are immutable.

฀ This means that elements of a tuple cannot be changed


once it has been assigned.
Guess The Output ?

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

฀ As we discussed previously, a tuple is immutable.

฀ This also means that we can’t delete just a part of it.

฀ However we can delete an entire tuple if required.


Guess The Output ?

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

฀ A lot of functions that work on lists work on tuples too.

฀ 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

฀ Returns the number of items in the tuple


Example:
fruits=("apple","banana","orange",None)
print(len(fruits))

Output:
4
The max( ) Function

฀ Returns the greatest item present in the tuple

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

฀ Returns the least item present in the tuple

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

฀ Returns the sum of all the items present in the tuple .

฀ As before , the items must be of Numeric or boolean


type

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

฀ Returns a sorted version of the tuple passed as


argument.
Did you notice a special
point ?
Example:
nums=(7,4,9,1)
Although sorted( ) is working
print(sorted(nums)) on a tuple , but it has returned
print(nums) a list

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

฀ To sort the tuple in descending order , we can pass the


keyword argument reverse with value set to True to
the function sorted( )

Example:
nums=(7,4,9,1)
print(sorted(nums,reverse=True))
print(nums)

Output:
The tuple( ) Function

฀ The tuple( ) function converts an iterable i.e list ,


range, set , dictionary and string to a tuple.
Syntax:
tuple(iterable)

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

฀ The any( ) function accepts a Tuple as argument and


returns True if atleast one element of the Tuple is True.
If not, this method returns False. If the Tuple is empty,
then also it returns False
Syntax:
list(iterable)

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

฀ The all( ) function accepts a Tuple as argument and


returns True if all the elements of the Tuple are True
or if the Tuple is empty .If not, this method returns
False.

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

• Operations Allowed On Tuple


Tuple Methods

 As mentioned previously a Tuple is immutable.


 So only those methods work with it which do not change the
tuple data
 Can you figure out which of these methods work with
tuples ?
 These are: Answer:
 append()
 extend() Only index( ) and count( ).
 insert() Rest all the methods change the
 index() sequence object on which they
 count() have been called.
 remove()
 pop()
 clear()
 sort()
 reverse()
The index( ) Method

 The index() method searches an element in the tuple and


returns it’s index.
 If the element occurs more than once it returns it’s
smallest/first position.
 If element is not found, it raises a ValueError exception

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

 The count() method returns the number of


occurrences of an element in a tuple

 In simple terms, it counts how many times an element has


occurred in a tuple and returns it.

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 ?

vowels = ('a', 'e', 'i', 'o', 'i', 'u')


x = vowels.count('i')
print("i occurs",x,"times")
x = vowels.count('e')
print("e occurs",x,"times")
x = vowels.count('j')
print("j occurs",x,"times")

Output:
Operations Allowed On Tuple

 We can apply four types of operators on Tuple objects

 These are:

 Membership Operators

 Concatenation Operator

 Multiplication

 Relational Operators
Membership Operators

 We can apply the ‘in’ and ‘not in’ operators on tuple.

 This tells us whether an item belongs / not belongs to


tuple.
Guess The Output ?

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

 Concatenation is the act of joining.

 We can join two tuples using the concatenation


operator ‘+’.

 All other arithmetic operators are not allowed to work on


two tuples.

 However * works but as a repetition operator


Guess The Output ?

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

 Python allows us to multiply a tuple by a constant

 To do this , as usual we use the operator *


Guess The Output ?

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

 The relational operators work with tuples and other


sequences.

 Python starts by comparing the first element from each


sequence.

 If they are equal, it goes on to the next element, and so


on, until it finds elements that differ.

 Subsequent elements are not considered (even if they


are really big).
Guess The Output ?

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 ?

 A Python string is a sequence of zero or more characters.

 It is an immutable data structure.

 This means that we although we can access the internal


data elements of a string object but we can not change it’s
contents
How Can Strings Be Created ?

 Python provides us 3 ways to create string objects:

 By enclosing text in single quotes

 By enclosing text in double quotes

 By enclosing text in triple quotes (generally used for multiline


strings)
Example

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 ?

 Python provides us 3 ways to access string objects:

 Directly passing it to the print( ) function

 Accessing individual elements using subscript operator [ ]

 Accessing multiple elements using slice operator [ : ]


Printing The Whole String

city="Bhopal"
print(city)

Output:
Bhopal
Accessing Individual
Elements

 A string in Python has indexes running from 0 to size-1

 For example:

 city=“Bhopal”

 The above code will create a logical diagram in memory,


where positive indexing will go from 0 to 5 and negative
indexing from -1 to -6
s
Accessing Individual Element
s
Accessing Individual Element

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

 Redesign the previous code using for loop only to


traverse the string in reverse order. Don’t use slice
operator
Solution

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]

• x denotes the start index of slicing and y denotes the end


index . But Python ends slicing at y-1 index.
The Slicing Operator

• 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

• String slicing can accept a third parameter also after the


two index numbers.

• The third parameter is called step value.

• So the complete syntax of slicing operator is:

s[begin:end:step]

• Step value indicates how many characters to move forward


after the first character is retrieved from the string and it’s
default value is 1 , but can be changed as per our choice.
Using Step Value

• Another point to understand is that if step is positive


or not mentioned then
• Movement is in forward direction ( L→R)
• Default for start is 0 and end is len

• But if step is negative , then


• Movement is in backward direction (R→L)
• Default for start is -1 and end is –(len+1)
The Slicing Operator

• 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

 There are 6 operators which work on Strings:

 + : For joining 2 strings

 * : For creating multiple copies of a string

 in : For searching a substring in a string

 not in: Opposite of in

 Relational Operator : For comparing 2 strings

 Identity Operators : For comparing addresses


The Operator +

The + operator concatenates strings. It returns a string


consisting of the operands joined together

Example:
a="Good"
b="Morning"
c="User"
print(a+b+c)

Output:
GoodMorningUser
The Operator *

 The * operator creates multiple copies of a string.

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

 The in operator returns True if the first operand is


contained within the second, and False otherwise:

Example:
a="banana"
print(“nana” in a)
print(“nani” in a)

Output:
True
False
The Operator not in

 The not in operator behaves opposite of in and


returns True if the first operand is not contained within
the second, and False otherwise:

Example:
a="banana"
print(“nana” not in a)
print(“nani” not in a)

Output:
False
True
The Relational Operators

 We can use ( > , < , <= , >= , == , != ) to compare two strings.

 Python compares string lexicographically i.e using Unicode


value of the characters.
Example: Output:

False
"tim" == "tie" True
"free" != "freedom" True
"arrow" > "aron" True
"right" >= "left“ False
"teeth" < "tee" False
True
"yellow" <= "fellow"
"abc" > " "
The Identity Operators

 ‘is’ operator returns True if both the operand point to same


memory location.
 ’is not’ operator returns True if both the operand point to
different memory location.

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

 There are some built-in functions in Python that we can


use on strings.

 These are:
 len()
 max()
 min()
 chr()
 ord()
The len( ) Function

 Returns the number of charcters in the string

Example:
name="Sachin"
print(len(name))

Output:
6
The max( ) Function

 Returns a character which is alphabetically the highest


character in the string.

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

 Returns a character which is alphabetically the lowest


character in the string.

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

 Returns a character (a string) of the unicode value


passed as an integer.

 The valid range of the argument is from 0 through


1,114,111.

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

 Returns an integer of the unicode value passed as an


character.

 But the argument passed should be only 1 character in


length.

Example:
print(ord(‘a’))

Output:
97
Guess The Output ?

print(ord("+"))

Output:
43
Guess The Output ?

print(ord("5"))

Output:
53
The str( ) Function

 Returns a string representation of an object.

 We can pass object of any type and Python will convert it to


string

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

 In Python version 3.6, a new string formatting


mechanism was introduced.

 This feature is called String Interpolation , but is more


usually referred to by its nickname f-string.
String Interpolation

 To understand this feature , can you tell how can we print the
following 2 variables using print( ):

name=“Sachin”
age=34

 Till now , we know 4 ways:

1. print(“My name is”,name,”and my age is”,age)


2. print(“My name is ”+name+” and my age is ”+str(age))
3. print(“My name is {0} and my age is
{1}”.format(name,age))
4. print(“My name is %s and my age is %d”%(name,age))
String Interpolation

 But , from Python 3.6 onwards , there is much more simpler


way to print them which is called f-string.

 f-strings have an f at the beginning and curly braces


containing expressions that will be replaced with their
values.

 The expressions are evaluated at runtime and then formatted

name="Sachin"
age=34
print(f"My name is {name} and my age is {age}")
Arbitary Expressions

 Because f-strings are evaluated at runtime, we can put any


valid Python expressions in them

a=10
b=20
print(f"sum is {a+b}")

Output:
Function Calls

 We could also call functions. Here’s an example:

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

 We could also call methods. Here’s an example:

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

 A string object has a number of method or member


functions.

 These can be grouped into different categories .

 These categories are:


 String conversion methods
 String comparison methods
 String searching methods
 String replace methods
String Conversion 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

text="python is awesome. java rocks"


newtext=text.capitalize()
print(f"Original text is {text}\nCapitalized text is {newtext}")

Output:
String Conversion Methods

 lower( ) and upper( )


Returns a copy of the string with all letters converted to
lowercase and uppercase respectively
Example:
name="Sachin Kapoor"
lc=name.lower()
uc=name.upper() print(f"Original
name is {name}") print(f"Lower
name is {lc}") print(f"Upper name
is {uc}")
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

text = "i lOVe pYTHoN"


print(text.title())

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

text = "He's an engineer, isn't he?"


print(text.title())

Output:
String Comparison Methods

 islower( ) and isupper( )


Returns True or False depending on whether all alphabets
in the string are in lowercase and uppercase respectively
String Comparison Methods

Example:
s = 'this is good'
print(s.islower())

s = 'th!s is a1so g00d'


print(s.islower())

s = 'this is Not good'


print(s.islower())
Output:
String Comparison Methods

Example:
s = "THIS IS GOOD!"
print(s.isupper())

s = "THIS IS ALSO G00D!"


print(s.isupper())

s= "THIS IS not GOOD!"


print(s.isupper())
Output:
String Comparison Methods

Example:
s = ""
print(s.isupper())
print(s.islower())

Output:
String Comparison Methods

 istitle( )

Returns True if the string is in titlecase or empty ,


otherwise returns False
String Comparison Methods

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( )

Returns True if the string contains only alphabets ,


otherwise returns False
String Comparison Methods

Example: Output:
name = "Monalisa" True
print(name.isalpha()) False
False
name = "M0nalisa"
print(name.isalpha())

name = "Monalisa Shah"


print(name.isalpha())
String Comparison Methods

 isdigit( )

Returns True if the string contains only digits , otherwise


returns False
String Comparison Methods

Example: Output:
text = "12345" True
print(text.isdigit()) True
False
text = "012345" False
print(text.isdigit())

text = "12345 6"


print(text.isdigit())

text = "a12345"
print(text.isdigit())
String Comparison Methods

 isalnum( )

Returns True if the string contains only alphanumeric


characters , otherwise returns False
String Comparison Methods

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( )

Returns True if the string contains only whitespace


characters , otherwise returns False
String Comparison Methods

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( )

 The startswith() method takes maximum of three


parameters:
 prefix - String to be checked
 start (optional) - Beginning position where prefix is to be checked
within the string.
 end (optional) - Ending position where prefix is to be checked within
the string.
 It returns True if the string starts with the specified
prefix , otherwise returns False
String Comparison Methods

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)

result = text.startswith('Python is easy to learn.')


print(result)

result = text.startswith('is easy',7)


print(result)
String Comparison Methods

 endswith( )

 The endswith() method takes maximum of three


parameters:
 suffix - String to be checked
 start (optional) - Beginning position where suffix is to be checked
within the string.
 end (optional) - Ending position where suffix is to be checked within
the string.
 It returns True if the string ends with the specified
suffix , otherwise returns False
String Comparison Methods

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)

result = text.endswith('is', 7, 13)


print(result)

result = text.endswith('easy', 7, 13)


print(result)

result = text.endswith('easy', 7, 14)


print(result)
String Searching Methods

 index( )
Returns the index of first occurrence of a substring
inside the string (if found).

If the substring is not found, it raises an exception.

Syntax:The index() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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

Syntax:The find() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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

If the substring is not found, it returns 0

Syntax:The count() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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.

Syntax:The replace() method takes three parameters:


 old - old substring we want to replace
 new - new substring which would replace the old substring
 count (optional) - the number of times we want to replace the old substring with
the new 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).

Syntax:The strip() method takes one optional parameter:


 chars (optional) - a string specifying the set of characters to be
removed.

 If the chars argument is not provided, all leading and


trailing whitespaces are removed from the string.
String Replacement Methods

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

Write a program to simulate user registration process. Your


code should do the following:
1. It should first ask the user to input his full name. If he doesn’t
enter his full name then program should display the error
message and again ask the user to enter full name . Repeat the
process until the user types his full name.[ full name means a
string with atleast 2 words separated with a space]
2. Then it should ask the use to input his password. The rules for
password are:
1. It should contain atleast 8 characters
2. It should contain atleast 1 digit and 1 upper case letter
Repeat the process until the user correctly types his
Password.
Finally , display the user’s first name with a THANK YOU
message. Create separate functions for accepting fullname ,
password and returning firstname
Sample Output
Solution

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.

Syntax:The split() method takes two parameters:


 separator (optional)- This is the delimiter. The string splits at the
specified separator .If the separator is not specified, any
whitespace (space, newline etc.) string is a separator.
 maxsplit (optional) - The maxsplit defines the maximum number
of splits.The default value of maxsplit is -1, meaning, no limit on
the number of splits.

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

Write a program to which takes a string from the


user and displays a list of all of the words that the
string contains removing all special characters
except space. It should also display number of words
in the string.
For example:
Input:
Let's learn C++, Python and then Java.
Output:
['Lets', 'learn', 'C', 'Python', 'and', 'then', 'Java']
7
String Replacement Methods

 join( )
The join() method returns a string concatenated with the
elements of an iterable.

But the iterable should only contain strings

The join() method takes an iterable - objects capable of


returning its members one at a time

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 ?

 Python dictionary is an unordered collection of


items.

 The collections we have studied till now like list , tuple


and string are all ordered collections as well as can
hold only one value as their element

 On the other hand dictionary is an unordered


collection which holds the data in a key: value pair.
What Is Key-Value Pair?

 Sometimes we need to store the data so that one piece of


information is connected to another piece of information.

 For example RollNo→Student Name or


Customer Name→Mobile Number

 In these examples RollNo will be called a key while it’s


associated Student Name will be called value

 To store such paired data Python provides us the data type


called dictionary
How To Create A Dictionary?

 Creating a dictionary is as simple as placing items inside


curly braces { } separated by comma.

 Every item has a key and the corresponding value


expressed as a pair, key: value.

 While values can be of any data type and can repeat,


but keys must be of immutable type and must be
unique.
General Syntax Of
Creating A Dictionary

Syntax:

d={
<key>: <value>,
<key>: <value>,
...
<key>: <value>
}
How To Create A Dictionary?

# empty dictionary
my_dict = { }

# dictionary with integer keys


my_dict = {1: 'Amit', 2: 'Brajesh',3:'Chetan'}

# dictionary with mixed keys


my_dict = {1: 'John', 'a':'vowel'}

# dictionary with list as values


my_dict = {'Rahul':['C', 'C++'], 'Ajay':['Java', 'C', 'Python'],
'Neeraj':['Oracle', 'Python']}
Important Characteristics
Of Dictionaries

 The important characteristics of Python dictionaries are as


follows:

 They can be nested.


Click to add text
 They are mutable.

 They are dynamic.

 They are unordered.

 Unlike Lists and tuples , a dictionary item is accessed by it’s


corresponding key not index
Other Ways Of Creating
Dictionary

 We also can create a list by using the dict( ) function

# Create an empty dictionary


my_dict = dict()

# Create a dictionary with elements


my_dict = dict({1:'apple', 2:'ball'})

# Create a dictionary with other sequences


my_dict = dict([(1,'apple'), (2,'ball')])
PYTHON
LECTURE 35
Today’s Agenda

• Strings -III
• String Methods
String Methods

 A string object has a number of method or member


functions.

 These can be grouped into different categories .

 These categories are:


 String conversion methods
 String comparison methods
 String searching methods
 String replace methods
String Conversion 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

name="Guido Van Rossum"


newname=name.capitalize()
print(f"Original name is {name}\nCapitalized name is {newname}")

Output:
String Conversion Methods

text="python is awesome. java rocks"


newtext=text.capitalize()
print(f"Original text is {text}\nCapitalized text is {newtext}")

Output:
String Conversion Methods

 lower( ) and upper( )


Returns a copy of the string with all letters converted to
lowercase and uppercase respectively
Example:
name="Sachin Kapoor"
lc=name.lower()
uc=name.upper() print(f"Original
name is {name}") print(f"Lower
name is {lc}") print(f"Upper name
is {uc}")
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

text = "i lOVe pYTHoN"


print(text.title())

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

text = "He's an engineer, isn't he?"


print(text.title())

Output:
String Comparison Methods

 islower( ) and isupper( )


Returns True or False depending on whether all alphabets
in the string are in lowercase and uppercase respectively

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())

s = 'th!s is a1so g00d'


print(s.islower())

s = 'this is Not good'


print(s.islower())
Output:
String Comparison Methods

Example:
s = "THIS IS GOOD!"
print(s.isupper())

s = "THIS IS ALSO G00D!"


print(s.isupper())

s= "THIS IS not GOOD!"


print(s.isupper())
Output:
String Comparison Methods

Example:
s = ""
print(s.isupper())
print(s.islower())

Output:
String Comparison Methods

 istitle( )

Returns True if the string is in titlecase or empty ,


otherwise returns False
String Comparison Methods

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( )

Returns True if the string contains only alphabets ,


otherwise returns False
String Comparison Methods

Example: Output:
name = "Monalisa" True
print(name.isalpha()) False
False
name = "M0nalisa"
print(name.isalpha())

name = "Monalisa Shah"


print(name.isalpha())
String Comparison Methods

 isdigit( )

Returns True if the string contains only digits , otherwise


returns False
String Comparison Methods

Example: Output:
text = "12345" True
print(text.isdigit()) True
False
text = "012345" False
print(text.isdigit())

text = "12345 6"


print(text.isdigit())

text = “a12345"
print(text.isdigit())
String Comparison Methods

 isdecimal( )

Returns True if the string contains only


decimal characters , otherwise returns False
String Comparison Methods

Example: Output:
text = "12345" True
print(text.isdecimal()) True
False
text = "012345" False
print(text.isdecimal())

text = "12345 6"


print(text.isdecimal())

text = “a12345"
print(text.isdecimal())
String Comparison Methods

 isnumeric( )

Returns True if the string contains only


numeric characters , otherwise returns False
String Comparison Methods

Example: Output:
text = "12345" True
print(text.isnumeric()) True
False
text = "012345" False
print(text.isnumeric())

text = "12345 6"


print(text.isnumeric())

text = “a12345"
print(text.isnumeric())
isdigit( ) V/s isdecimal( ) V/s
isnumeric( )

 To understand the difference between isdigit( ) , isdecimal( )


and isnumeric( ) , we will first have to understand what
Python considers as digits , decimal or numerics for
special symbols

 In Python:

 superscript and subscripts (usually written using unicode) are also


considered digit characters , numeric characters but not decimals.

 roman numerals, currency numerators and fractions (usually


written using unicode) are considered numeric characters but not
digits or decimals
String Comparison Methods

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( )

Returns True if the string contains only alphanumeric


characters , otherwise returns False
String Comparison Methods

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( )

Returns True if the string contains only whitespace


characters , otherwise returns False
String Comparison Methods

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( )

 The startswith() method takes maximum of three


parameters:
 prefix - String to be checked
 start (optional) - Beginning position where prefix is to be checked
within the string.
 end (optional) - Ending position where prefix is to be checked within
the string.
 It returns True if the string starts with the specified
prefix , otherwise returns False
String Comparison Methods

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)

result = text.startswith('Python is easy to learn.')


print(result)

result = text.startswith('is easy',7)


print(result)
String Comparison Methods

 endswith( )

 The endswith() method takes maximum of three


parameters:
 suffix - String to be checked
 start (optional) - Beginning position where suffix is to be checked
within the string.
 end (optional) - Ending position where suffix is to be checked within
the string.
 It returns True if the string ends with the specified
suffix , otherwise returns False
String Comparison Methods

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)

result = text.endswith('is', 7, 13)


print(result)

result = text.endswith('easy', 7, 13)


print(result)

result = text.endswith('easy', 7, 14)


print(result)
String Searching Methods

 index( )
Returns the index of first occurrence of a substring
inside the string (if found).

If the substring is not found, it raises an exception.

Syntax:The index() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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

Syntax:The find() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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).

If the substring is not found, it returns -1

Syntax:The rfind() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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

If the substring is not found, it returns 0

Syntax:The count() method takes three parameters:


 sub - substring to be searched in the string str.
 start and end(optional) - substring is searched within str[start:end]
String Searching Methods

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.

Syntax:The replace() method takes three parameters:


 old - old substring we want to replace
 new - new substring which would replace the old substring
 count (optional) - the number of times we want to replace the old substring with
the new 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).

Syntax:The strip() method takes one optional parameter:


 chars (optional) - a string specifying the set of characters to be
removed.

 If the chars argument is not provided, all leading and


trailing whitespaces are removed from the string.
String Replacement Methods

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

Write a program to simulate user registration process. Your


code should do the following:
1. It should first ask the user to input his full name. If he doesn’t
enter his full name then program should display the error
message and again ask the user to enter full name . Repeat the
process until the user types his full name.[ full name means a
string with atleast 2 words separated with a space]
2. Then it should ask the use to input his password. The rules for
password are:
1. It should contain atleast 8 characters
2. It should contain atleast 1 digit and 1 upper case letter
Repeat the process until the user correctly types his
Password.
Finally , display the user’s first name with a THANK YOU
message. Create separate functions for accepting fullname ,
password and returning firstname
Sample Output
Solution

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.

Syntax:The split() method takes two parameters:


 separator (optional)- This is the delimiter. The string splits at the
specified separator .If the separator is not specified, any
whitespace (space, newline etc.) string is a separator.
 maxsplit (optional) - The maxsplit defines the maximum number
of splits.The default value of maxsplit is -1, meaning, no limit on
the number of splits.

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.

But the iterable should only contain strings

The join() method takes an iterable - objects capable of


returning its members one at a time

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

 Since dictionary is mutable, so we can add new items or


change the value of existing items using either of two
ways.

 These are:

 assignment operator or

 update( ) method of dictionary object


Updating Using
Assignment Operator

 Syntax Of Assigment Operator:


dict_var[key]=value

 When we use assignment operator , Python simply


searches for the key in the dictionary object.

 If the key is found , it’s value is replaced with the value


we have passed, otherwise a new key-value pair entry
is created
Guess The Output ?

student_data = {1:'Amit', 2:'Brajesh',3:'Chetan',


4:'Deepak',5:'Neeraj'}
print("Before updating:")
print(student_data)
student_data[2]='Brajendra'
print("After updating:")
print(student_data)

Output:
Guess The Output ?

student_data = {1:'Amit', 2:'Brajesh',3:'Chetan',


4:'Deepak',5:'Neeraj'}
print("Before updating:")
print(student_data)
student_data[8]='Ankit‘
print("After updating:")
print(student_data)

Output:
Updating Using
update( ) Method

 Syntax Of update( ) Method:

dict_var.update( dict_var2)

 The update( ) method merges the keys and values of


one dictionary/iterable into another, overwriting
values of the same key
Guess The Output ?

student_data = {1:'Amit', 2:'Brajesh',3:'Chetan',


4:'Deepak',5:'Neeraj'}
student_data2={2:'Brajendra',8:'Ankit'}
print("Before updating:")
print(student_data)
student_data.update(student_data2)
print("After updating:")
print(student_data)
Output:
Exercise

Write a program to create a dictionary called accounts


containing account id and balance of account holders .
Initialize it with the following data:
101: 50000
102:45000
103:55000
Now ask the user to input an account id and amount . If
the account id is present in the dictionary then update the
balance by adding the amount given otherwise add a new
entry of account id and balance in the dictionary. Finally
print all the accounts details.
Sample Output
Solution

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

 Since dictionary is mutable, so we can remove items from the


dictionary.

 There are certain methods available in Python to delete the


items or delete entire dictionary.

 These are:

 pop(key): removes the entry with provided key and returns it’s
value

 del: deletes a single item or the dictionary entirely

 clear(): clears all the items in the dictionary and returns an empty
dictionary
The pop() Method

 Syntax Of pop( ) Method:

dict_var.pop(key,[default])

 The pop() method takes two parameters:


 key - key which is to be searched for removal
 default - (optional) value which is to be returned when the key is not in the
dictionary
 Return Value From pop( )
 If key is found – it returns value of removed/popped element from the
dictionary
 If key is not found – it returns the value specified as the second argument
(default)
 If key is not found and default argument is not specified – it
raises KeyError exception
Guess The Output ?

sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,


"Jun":30}
print(sixMonths)
print(sixMonths.pop("Jun"))
print(sixMonths)
print(sixMonths.pop("Jul",-1))
print(sixMonths.pop("Jul","Not found"))
print(sixMonths.pop("Jul"))
Output:
The del Operator

 Just like list , Python also allows us to delete an item from the
dictionary by calling the operator/keyword del

 Syntax Of del Operator:

del dict_var[key]

 It removes the entry from the dictionary whose key is passed as


argument

 If the key is not found or dictionary is empty it raises


KeyError exception

 If we do not pass the key then del deletes the entire dictionary
object
Guess The Output ?

threeMonths = {"Jan":31, "Feb":28, "Mar":31}


print(threeMonths)
del threeMonths
print(threeMonths)

Output:
The clear() Method

 The clear() method removes all items from the


dictionary.

 Syntax Of clear( ) Method:

dict_var.clear( )

 The clear() method doesn’t take any argument

 It returns nothing ( None )


Guess The Output ?

threeMonths = {"Jan":31, "Feb":28, "Mar":31}


print(threeMonths)
threeMonths.clear()
print(threeMonths)

Output:
Functions Used With
Dictionary

 Like list , Python allows us to use the following functions


with dictionary object

 len()
 max()
 min()
 any()
 all()
 sorted()
The len( ) Function

 Returns the number of items in the dictionary

Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}

print(len(sixMonths))
Output:
6
The max( ) Function

 Returns the greatest key present in the dictionary

Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}

print(max(sixMonths))

Output:
May
Guess The Output ?

sixMonths = {"Jan":31, "Feb":28, 3:31, "Apr":30 ,5:31 ,6:30}


print(max(sixMonths))

Output:
Guess The Output ?

sixMonths = {1:31, 2:28, 3:31,4:30,5:31,6:30}


print(max(sixMonths))

Output:
6
Guess The Output ?

data = {False: 10,True: 5}


print(max(data))

Output:
True
Guess The Output ?

data={False:0,True:1,None:2}
print(max(data))

Output:
Exercise

Write a program to create a dictionary called players


and accept names of 5 players and their runs from the
user. Now find out 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)
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

 Returns the least item present in the dictionary

Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}

print(min(sixMonths))

Output:
Apr
The any( ) Function

 Like list and tuple , any( ) function accepts a dict as


argument and returns True if atleast one element of the
dict is True. If not, this method returns False. If the dict
is empty, then also it returns False

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

 The all( ) function accepts a dict as argument and returns


True if all the keys of the dict are True or if the List is
empty .If not, this method returns False.

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

 Like it is with lists and tuples, the sorted() function


returns a sorted list of only keys in the dictionary.

 The sorting is in ascending order, and doesn’t modify the


original dictionary.
Guess The Output ?

sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,


"Jun":30}
print(sorted(sixMonths))
print(sixMonths)

Output:
Guess The Output ?

sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30,


4:31, 5:30}
print(sorted(sixMonths))

Output:
Guess The Output ?

sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30,


"May":31, "Jun":30}
print(sorted(sixMonths,reverse=True))

Output:
The kwargs Function
Argument

 To understand kwargs , try to figure out the output of the


code below

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

 To overcome this problem , we used the technique of


variable length arguments, where we prefix the
function parameter with an asterisk

 This allows us to pass any number of arguments to the


function and inside the function they are received as tuple
The args 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

 Using *args , we cannot pass keyword arguments

 So , Python has given us a solution for this


,called **kwargs, which allows us to pass the variable
length of keyword arguments to the function.
The kwargs Function
Argument

 In the function, we use the double asterisk ** before the


parameter name to denote this type of argument.

 The arguments are passed as a dictionary and the name of


the dictionary is the name of parameter

 The keywords become keys and the actual data passed


becomes values
The kwargs 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="Sachin", Lastname="Kapoor", Age=38,


Phone=9826012345)

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

 Python provides us following methods to work upon


dictionary object:

 clear()
 copy()
 get()
 items()
 keys()
 pop()
 update()
 values()
The copy( ) Method

 This method returns a shallow copy of the dictionary.

Syntax:
dict.copy()

Example:
original = {1:'one', 2:'two'}
new = original.copy()
print('new: ', new)
print('original: ', original)
Output:
copy( ) v/s =

 When copy() method is used, a new dictionary is


created which is filled with a copy of the data from the
original dictionary.

 When = operator is used, a new reference to the


original dictionary is created.
Guess The Output ?

original = {1:'one', 2:'two'} original = {1:'one', 2:'two'}


new = original new = original.copy()
new.clear() new.clear()
print('new: ', new)
print('new: ', new) print('original: ', original)
print('original: ', original)

Output: Output:
Using in And not in
With Dictionary

 We can apply the ‘in’ and ‘not in’ operators on a dictionary


to check whether it contains a certain key.

 If the key is present then in returns True ,otherwise it


returns False.

 Similarly , if the key is not present not in returns True ,


otherwise it returns False
Guess The Output ?

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

 Just like we have list comprehension , we also have


dictionary comprehension

 Dictionary Comprehension is a mechanism for


transforming one dictionary into another dictionary.

 During this transformation, items within the original


dictionary can be conditionally included in the new
dictionary and each item can be transformed as needed.
Syntax For
Dictionary Comprehension

 Syntax:

dict_variable = { key:value for (key,value) in iterable}

 Explanation

 Iterable can be any object on which iteration is possible

 (key,value) is the tuple which will receive these key-value pairs


one at a time

 key:value is the expression or key-value pair which will be


assigned to new dictionary
Exercise

 Write a program to produce a copy of the


dictionary cars using dictionary comprehension

cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
newcars={ k:v for (k,v) in cars.items()}
print(newcars)

Output:
Exercise

 Write a program to produce a new dictionary from


the given dictionary with the values of each key
getting doubled

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


double_dict1 = {k:v*2 for (k,v) in dict1.items()}
print(double_dict1)

Output:
Exercise

 Write a program to produce a new dictionary from


the given dictionary with the keys of each key
getting doubled

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


double_dict1 = {k*2:v for (k,v) in dict1.items()}
print(double_dict1)

Output:
Exercise

 Write a program to accept a string from the user


and print the frequency count of it’s letters , i.e.
how many times each letter is occuring in the
string

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

 Like list comprehension , dictionary comprehension


also allows us to add conditions to make it more powerful.

 Syntax:
dict_variable = { key:value for (key,value) in iterable <test_cond>}

 As usual , only those key-value pairs will be returned by


dictionary comprehension which satisfy the condition
Exercise

 Write a program to produce a new dictionary from


the given dictionary but with the values that are
greater than 2 and store their doubles

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


dict2 = {k:v*2 for (k,v) in dict1.items() if v>2}
print(dict2)

Output:
Exercise

 Write a program to produce a new dictionary from


the given dictionary but with the double of the
values that are greater than 2 as well as multiple of
2

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


dict2 = {k:v*2 for (k,v) in dict1.items() if v>2 if v%2==0}
print(dict2)

Output:
Exercise

 Write a program to produce a new dictionary from


the given dictionary but the value should be the
string “EVEN” for even values and “ODD” for odd
values

dict1 = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}


dict2= {k:'even' if v%2==0 else 'odd' for (k,v) in dict1.items()}
print(dict2)

Output:
Restrictions On
Dictionary Keys

1. Almost any type of value can be used as a dictionary key in


Python , like integer, float, Boolean etc

Example:
d={65:"A", 3.14:"pi", True:1}
print(d)

Output:
Restrictions On
Dictionary Keys

2. We can even use class names as keys.

Example:
d={int:1, float:2, bool:3}
print(d)
print(d[float])

Output:
Restrictions On
Dictionary Keys

3. Duplicate keys are not allowed. If we assign a value to an


already existing dictionary key, it does not add the key a
second time, but replaces the existing value:

Example:
d={"MP":"Indore","UP":"Lucknow","RAJ":"Jaipur"}
print(d)
d["MP"]="Bhopal"
print(d)
Output:
Restrictions On
Dictionary Keys

4. If we specify a key a second time during the initial


creation of a dictionary, the second occurrence will
override the first:
Example:
d={"MP":"Indore","UP":"Lucknow","RAJ":"Jaipur","MP":"Bhopal"}
print(d)

Output:
Restrictions On
Dictionary Keys

5. A dictionary key must be of a type that is immutable.


Like integer, float, string and Boolean—can serve as
dictionary keys. Even a tuple can also be a dictionary key,
because tuples are immutable:

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

6. However, neither a list nor another dictionary can serve as


a dictionary key, because lists and dictionaries are
mutable:

Example:
d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
print(d)

Output:
Restrictions On
Dictionary Values

 There are no restrictions on dictionary values.

 A dictionary value can be any type of object Python


supports, including mutable types like lists and
dictionaries, and user-defined objects

 There is also no restriction against a particular value


appearing in a dictionary multiple times:
Exercise

 Write a complete COUNTRY MANAGEMENT APP. Your


code should store COUNTRY CODE and COUNTRY NAME
as key-value pair in a dictionary and allow perform following
operations on the dictionary :
 View
 Add
 Delete

To start the program initialize your dictionary with


the following set of key-value pairs:

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

• Introduction To Object Oriented


Programming-I

• Problems With Procedure Oriented Programming


• What Is Object Oriented Programming ?
• What Is A Class ?
• What Is An Object ?
• Syntax Of Creating A Class In Python
• Syntax Of Creating Object
• Types Of Data Members A Class Can Have
• The Method init ()
• The Argument self
• Passing Parameters To init ()
Question ???

 Can you tell , what kind of programming paradigm


we have followed this point in Python ?

 The answer is : POP (Procedure Oriented


Programming)

 In all the programs we wrote till now, we have designed our program
around functions i.e. blocks of statements which manipulate
data.

 This is called the procedure-oriented programming.


Advantages

 Advantages Of Procedure Oriented Programming

 It’s easy to implement

 The ability to re-use the same code at different places in the


program without copying it.

 An easier way to keep track of program flow for small


codes

 Needs less memory.


Disadvantages

 Disadvantages Of Procedure Oriented


Programming

 Very difficult to relate with real world objects.

 Data is exposed to whole program, so no security for


data.

 Difficult to create new data types

 Importance is given to the operation on data rather than


the data.
So , What Is The Solution ?

 Solution to all the previous 4 problems is Object


Oriented Programming

 Many people consider OOP to be a modern programming


paradigm, but the roots go back to 1960s.

 The first programming language to use objects was


Simula 67
What Is OOP?

 OOP is a programming paradigm (way of


developing programs)

 In OOP, we have the flexibility to represent real-world


objects like car, animal, person, ATM etc. in our code

 It allows us to combine the data and functionality and


wrap it inside something which is called an object
What Is An Object?

• In programming any real world entity which has


specific attributes or features can be represented as an
object.

• In simple words, an object is something that possess some


characteristics and can perform certain functions.
What Is An Object?

• For example, car is an object and can perform functions


like start, stop, drive and brake.

• These are the functions or behaviours of a car.

• And the characteristics or attributes are color of car,


mileage, maximum speed, model , year etc.
Are We Objects ?

• Yes , we humans are objects because:

• We have attributes as name, height, age etc.

• We also can show behaviors like walking, talking,


running, eating etc
Classes

• Now to create/represent objects we first have to write all


their attributes and behaviours under a single group .

• This group is called a class .

• Thus a class is an architecture/blueprint of the object. It is


a proper description of the attributes and methods of the
object.
Classes

• For Example:- The design of a car of same type is a class.


We can create many objects from a class. Just like we can
make many cars of the same type from a design of car.
A Dog Class
A Student Class
Creating A Class

 Defining a class is simple in Python.

 We start with the class keyword to indicate that we are


creating a class, then we add the name of the class followed
by a colon

 We can then add class members , which are methods


and attributes
Syntax Of Creating A Class

Syntax:
class <class_name>:
# class members

Example:
class Emp:
pass
Creating Objects

 In order to use a class we have to create it’s object which is


also called instantiating a class because objects are also
called instance of the class

 So, to create an instance of a class, we use the class


name, followed by parentheses and assign it to a
variable.
Syntax Of Creating Object

Syntax:
var_name=class_name( )

Example:
e=Emp()
Full Code

class Emp:
pass
1.The first line shows the class
name which is Emp.

e=Emp() 2. The second line shows the


address of the object to which the
print(type(e)) reference e is pointing

print(e) 3. The name main is the


name of the module which Python
automatically allots to our file

Output:
Adding
Data Members/Attributes

 Once we have defined the class , our next step is to provide it


data members/variables which can be used to hold values related
to objects.

 In Python , a class can have 3 types of variables:

 Instance Variables: Created per instance basis

 Local Variables: Created locally inside a method and destroyed when


the method execution is over

 Class Variables: Created inside a class and shared by every object of


that class. Sometimes also called as static variables
What Is An Instance Variable?

 Object variables or Instance Variables are created by


Python for each individual object of the class.

 In this case, each object has its own copy of the


instance variable and they are not shared or related in
any way to the field by the same name in a different object
Creating Instance Variables

 Creation of instance variables in Python is entirely


different than C++ or Java

 In these languages , we declare the data members inside


the class and when we instantiate the class , these
members are allocated space .
Creating Instance Variables
In C++

 For example in C++ ,we would write :

class Emp Now to use this Emp class we would say:


{
Emp obj;
int age;
char name[20]; Doing this will create an object in memory by
double salary; the name e and will contain three
…….. instance members called as
age , name and salary . Also this line
……..
will automatically call a special method
}; These are called constructor for
called initializing the object
instance
variables in
C++
Creating Instance Variables
In Java

 In Java ,we would write :

class Emp Now to use this Emp class we would say:


{
Emp obj=new Emp( );
int age;
String name; Doing this will create an object in heap with
double salary; the data members as age , name and salary
…….. and the reference e will be pointing to that
object. Here also the special method
……..
called constructor will be called
} These are automatically for initializing the object
called
instance
variables in
Java
Creating Instance Variables
In Python

 But in Python we use a very special method called init__() ,


to create as well as initialize an object’s initial attributes by
giving them their default value.

 Python calls this method automatically , as soon as the object


of the class gets created.

 Since it is called automatically , we can say it is like a


constructor in C++ or Java.
Full Code

class Emp:
def init (self):
print("Object created. . .")

As you can observe ,


e=Emp() Python has
automatically called the
special method
Output: init () as soon as
we have created the
object of Emp class
Another Example

class Emp:
def init (self):
print("Object created. . .")

e=Emp()
f=Emp()
g=Emp()

Output:
The argument self ?

 You must have noticed that the code is using an argument


called self in the argument list of init ()

 So , now 2 questions arise , which are :

 What is self ?

 Why it is required ?
What Is self ?

 In Python , whenever we create an object , Python calls


the method init()

 But while calling this method , Python also passes the


address of the object , for which it is calling init ()
, as the first argument.

 Thus , when we define the init () method we must


provide it atleast one formal argument which will
receive the object’s address .

 This argument is named as self


What If We Don’t Create 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

 Python always passes address of the object to every


instance method of our class whenever we call it, not
only to the method init ()

 So, every instance method which we define in our class


has to compulsorily have atleast one argument of type self
More About self

 The argument self always points to the address of the


current object

 We can think it to be like this reference or this pointer


of Java or C++ languages
Is self A Keyword ?

 No , not at all

 Many programmers wrongly think self to be a keyword


but it is not so.

 It is just a name and can be changed to anything else but


the convention is to always use the name self

 Another Important Point!


 The argument self is local to the method body , so we
cannot use it outside the method
Guess The Output

class Emp:
def init (self):
print("Object Created...")

e=Emp()
print(self)

Output:
The Most Important Role
Of self

 We can also use self to dynamically add instance members


to the current object.

 To do this ,we simply have to use self followed by dot operator


followed by name of the variable along with it’s initial value

 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!

 The instance variables called age , name and salary


are accessed in 2 ways in Python:

 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

 Although the code works fine , but it has one problem .

 The problem is that for every object of Emp class ,


Python will call init () method and thus every object
will be initialized with the same values

 To overcome this problem we can make the method


init () parameterized
Passing Parameters
To init ()

 Since init__() is also a method so just like other methods we


can pass arguments to it .

 But we need to remember 2 things for this:

 Since init () is called by Python at the time of object creation


so we will have to pass these arguments at the time of creation of
the object

 We will have to define parameters also while defining init ()


to receive these arguments

 Finally using these parameters we can initialize instance


members to different values for different objects
Passing Parameters
To init ()

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 argument self , should always be the first argument as


Python passes the address of the current object as the first
argument

 The variables age , name and salary used in the argument list
of init__() are called parameters or local variables.

 They will only survive until the method is under execution


and after that they will be destroyed by Python
An Important Point

 Any variable declared inside the body of any method


inside the class without using self will also be called as
local variable

 It is a common convention to give parameters the


same name as instance members , but it is not at all
compulsory.
Passing Parameters
To init ()

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 ?

 Recall , that we have already discussed that PYTHON


DOES NOT SUPPORT METHOD/FUNCTION
OVERLOADING .

 So if two methods have same name then the second


copy of the method will overwrite the first copy.

 So , in our case Python remembers only one init ()


method , which is defined last and since it is taking 3
arguments (excluding self) so our call:
e1=Emp(“amit”)
generated the exception
Question ?

 Can we do something so that the code runs with


different number of arguments passed to Emp
objects ?

 Yes !

 The solution is to use default arguments

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

• Introduction To Object Oriented


Programming-II

• Types Of Methods
• Adding Instance Methods
• Obtaining Details Of Instance Variables
• Different Ways To Create Instance Variables
• Deleting Instance Variables
Adding
Methods In Class

 Once we have defined the class , our next step is to provide


methods in it

 In Python , a class can have 3 types of methods:

 Instance Methods: Called using object

 Class Methods: Called using class name

 Static Methods: Called using class name


Adding Instance Methods

 Instance methods are the most common type of methods


in Python classes.

 These are called instance methods because they can


access instance members of the object.
Adding Instance Methods

 These methods always take atleast one


parameter, which is normally called self, which points to
the current object for which the method is called.

 Through the self parameter, instance methods can


access data members and other methods on the same
object.

 This gives them a lot of power when it comes to modifying


an object’s state.
Example

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

 Write a program to create a class called Circle , having an instance


member called radius. Provide following instance methods in your
class:
 init () : This method should initialize radius with the parameter
passed
 cal_area(): This method should calculate and print the area of the Circle
 cal_circumference(): This method should calculate and print the
circumference of the Circle
 Finally , in the main script , create a Circle object , initialize radius
with user input and calculate and display it’s area and
circumference
Output:
Solution

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:

def init__(self): Why did the code give exception?


self.name=“Amit”
self.age=24 The syntax we are using for accessing
self.sal=50000.0 name , age and sal is only applicable
def show(self): to local variables and not for instance
print(age,name,sal) members.
And since there are no local
e1=Emp()
variables by the name of name , age
and sal , so the code is giving exception
e1.show()

Output:
Guess The Output ?

class Emp:

def init__(self,name,age,sal): Why did the code give exception?


self.name=name
self.age=age The variables name, age and sal
self.sal=sal are local variables declared inside
def show(self): the method init () and hence
print(age,name,sal) are not available to the method
show() , so the code gave
e1=Emp("amit",34,50000.0) NameError exception
e1.show()

Output:
Guess The Output ?

class Emp:

def init (self):


self.name=“Amit”
self.age=24
self.sal=50000.0
def show(self):
print(self.age,self.name,self.sal)

e1=Emp()
e1.show()
Output:
Obtaining Details Of
Instance Variables

 Every object in Python has an attribute denoted


by dict .

 This attribute is automatically added by Python and


it contains all the attributes defined for the object
itself.

 It maps the attribute name to its value.


Guess The Output ?

class Emp:

def init (self):


self.name="Amit"
self.age=24
self.sal=50000.0

e1=Emp()
print(e1. dict )

Output:
Guess The Output ?

class Emp:

def init (self):


self.name="Amit"
self.age=24
sal=50000.0

e1=Emp()
print(e1. dict )

Output:
Guess The Output ?

class Emp:

def init (self):


self.name="Amit"
self.age=24
def set_sal(self):
self.sal=50000.0

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 ?

 Till now we can say there are 4 ways in Python to create


instance variables:

 Inside the constructor/ init () method using self

 Inside any instance method of the class using self

 Outside the class using it’s object reference

 Using the instance attribute dict


Guess The Output ?

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

 We can delete/remove instance variables in 2 ways:

 Using del self .<var_name> from the body of any instance


method within the class

 Using del <obj_ref>.<var_name> from outside the class


Guess The Output ?

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 ?

Since the object


class Emp:
pointed by self is also
def init (self,name,age,sal): pointed by e1 , so
self.name=name Python didn’t remove
self.age=age the object , rather it
self.sal=sal only removes the
reference self
def remove(self):
del self
e1=Emp("Amit",24,50000.0)
print(e1.__dict )
e1.remove()
print(e1.__dict )

Output:
Guess The Output ?

class Emp: Since instance variables


def init (self,name,age,sal): have a separate copy
self.name=name created for every object
self.age=age , so deleting an instance
self.sal=sal variable from one object
e1=Emp("Amit",24,50000.0) will not effect the other
e2=Emp("Sumit",25,45000.0) object’s same instance
print(e1.__dict__) variable
print(e2.__dict__)
del e1.sal
del e2.age
print()
print(e1.__dict__)
print(e2.__dict__)
Output:
PYTHON
LECTURE 40
Today’s Agenda

• Introduction To Object Oriented


Programming-III

• Adding Class Variables


• Different Ways To Create A Class Variable
• Different Ways To Access A Class Variable
• Obtaining Details Of Class Variables
• Deleting Class Variables
Class Variables

 Class variables are those variables which are defined


within the class body outside any method

 They are also called as static variables , although there is


no static keyword used with them
Class Variables

 The are shared by all instances of the class and have


the same value for each instance of the class.

 They have a single copy maintained at the class level


What Is Class Level ?

 The term class level means inside the class object.

 In Python , for every class one special object is


created called as class object

 Don’t think it is the same object which we create.


No it is not that!

 Rather , for every class , Python itself creates an object


called as class object and inside this object all the class /
static variables live
When Should
We Use Class Variable ?

 Whenever we don’t want to create a separate copy of the


variable for each object , then we can declare it as a
class variable.

 For example :

 The variable pi in a class called Circle can be declared as a class level


variable since all Circle objects will have the same value for pi

 Another example could be a variable called max_marks in a class


called Student . It should also be declared at the class level because
each Student will have same max_marks
Using Class Variable

 We can use a class variable at 6 places in Python:

 Inside the class body but outside any method

 Inside the constructor using the name of the class

 Inside instance method using name of the class

 Inside classmethod using name of the class or using the special


reference cls

 Inside staticmethod using the name of the class

 From outside the class using name of the class


Declaring Inside Class Body

 To declare a class variable inside class body but outside any


method body , we simply declare it below the class header

 Syntax:
class <class_name>:
<var_name>=<value>
def init__(self):
This is called a
// object specific code class variable

 To access the class level variables we use class name before


them with dot operator
How To Access and Modify
Class Variables?

 We must clearly understand the difference between


accessing and modifying .

 Accessing means we are just reading the value of the


variable

 Modifying means we are changing it’s value


How To Access
Class Variables?

 The class variables can be accessed in 4 ways:

 Using name of the class anywhere in the program

 Using self inside any instance method

 Using object reference outside the class

 Using special reference cls inside classmethod

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?

 The class variables can be modified in 3 ways:

 Using name of the class anywhere inside the methods of the class

 Using special reference cls inside classmethod

 Using name of the class outside the class body

 Special Note:We must never modify a class variable


using self or object reference , because it will not
modify the class variable , rather will create a new
instance variable by the same name
Example

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

 Write a program to create a class called Emp , having 3 instance members


called name , age and sal . Also declare a class variable called
raise_amount to store the increment percentage of sal and set it to 7.5 .
 Now provide following methods in your class
 init_ () : This method should initialize instance members with the parameter
passed
 increase_sal(): This method should calculate the increment in sal and add it to the
instance member sal
 display(): This method should display name , age and sal of the employee
 Finally , in the main script , create 2 Emp objects , initialize them and
increase their salary . Finally display the data
Output:
Solution

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

 We can declare a class variable inside the constructor also by


prefixing the variable name with the name of the class and
dot operator

 Syntax: This is called a


class <class_name>: class variable

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

 We can declare a class variable inside an instance method also


also by prefixing the variable name with the name of the
class and dot operator

 Syntax: This is called a


class <class_name>: class variable

def <method_name>(self):
<class name>.<var_name>=<value>
self.<var_name>=<value>
.
.
.
Example

class Circle: We have shifted the


def init (self,radius): var decl from class
body to method body ,
self.radius=radius
but still it will be
def cal_area(self): treated as class
Circle.pi=3.14 variable because we
have prefixed it with
self.area=Circle.pi * self.radius ** 2 classnname
c1=Circle(10)
c2=Circle(20)
c1.cal_area()
print("radius=",c1.radius,"area=",c1.area,"pi=",Circle.pi)
c2.cal_area()
print("radius=",c2.radius,"area=",c2.area,"pi=",Circle.pi)
Output:
Obtaining Details Of
Class Variables

 As we know , class variables are owned by a class itself


(i.e., by its definition), so to store their details a class also
uses a dictionary called dict

 Thus we can see that Python has 2 dictionaries called


dict .

 One is <class_name>. dict and the other is


<object_ref>. dict
Guess The Output ?

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: Why the code is showing only 2 class


i=10 variables even though we have 4 ?
def init (self):
Sample.j=20 This is because the class variable k will
only be created when f1() gets called .
def f1(self):
Similarly the variable j will be created
Sample.k=30 when we will create any object of the
Sample.m=40 class . But since we didn’t create any
print(Sample.__dict ) object nor we have called the method
f1( ) so only 2 class variables are there
called i and m
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: Still only three class variables


i=10 will be created by the code
def init (self): called i,j and m because class
variables are not created per
Sample.j=20 instance basis rather there is
def f1(self): only 1 copy shared by all the
Sample.k=30 objects
Sample.m=40
s1=Sample()
S2=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

 We can delete/remove instance variables in 2 ways

 Using del classname .<var_name> from anywhere in the


program

 Using del cls.<var_name> from classmethod

 Special Note: We cannot delete a class variable using


object reference or self , otherwise Python will throw
AttributeError exception
Guess The Output ?

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

• Introduction To Object Oriented


Programming-IV

• Class Methods
• Creating Class Methods
• Accessing Class Methods
• Static Methods
• Accessing Static Methods
• Difference Between Instance Method , Class Method and Static
Methods
Class Methods

 Just like we can have class variables , similarly Python


also allows us to create class methods.

 These are those methods which work on the class as a


whole , instead of working on it’s object.

 For , example in our Emp class if we want to initialize the


class variable raise_per inside a method , then the best
way would be to create a class method for this purpose
Creating A Class Metod

 To create a class method we write the special word


@classmethod on top of method definition

 Syntax: This is called


decorator
class <class_name>:
@classmethod
def <method_name>(cls):
// class specific code
Notice that a class method
gets a special object
reference passed as
argument by Python
called as class refercnce
Important Points About
ClassMethods

 To define a class method it is compulsory to use the


decorator @classmethod

 ClassMethods can only access class level data and not


instance specific data
Important Points About
ClassMethods

 Just like Python passed self as argument to instance


methods , it automatically passes cls as argument to
classmethods

 The argument cls is always passed as the first argument


and represents the class object.
Important Points About
ClassMethods

 Recall , that for every class Python creates a special object


called class object , so the reference cls points to this
object.

 The name cls is just a convention , although we can give


any name to it.
Important Points About
ClassMethods

 To call a classmethod we simply prefix it with


classname followed by dot operator.

 Although we can use object reference also to call a


classmethod but it is highly recommended not to
do so , since classmethods do not work upon
individual instances of the class

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

 Write a program to create a class called Emp , having an instance members


called name , age and sal . Also declare a class variable called
raise_amount to store the increment percentage of sal and set it the
value given by the user
 Now provide following methods in your class
 init_ () : This method should initialize instance members with the parameter
passed
 increase_sal(): This method should calculate the increment in sal and add ot to the
instance member sal
 display(): This method should display name , age and sal of the employee
 Finally , in the main script , create 2 Emp objects , initialize them and
increase their salary . Finally display the data
Output:
PYTHON
LECTURE 42
Today’s Agenda

• Advance Concepts Of Object Oriented


Programming-I

• Encapsulation

• Does Python Support Encapsulation ?

• How To Declare Private Members In Python ?

• The object Class And The str () Method

• The Destructor
Encapsulation

 Encapsulation is the packing of data and functions


operating on that data into a single component and
restricting the access to some of the object’s
components.

 Encapsulation means that the internal representation of


an object is generally hidden from view outside of the
class body.
Is The Following Code
Supporting Encapsulation ?

class Emp: No , the following code is


violating Encapsulation as it
def init (self): is allowing us to access data
members from outside the
self.age=25 class directly using object

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 ?

 To achieve Encapsulation in Python we have to prefix


the data member name with double underscore

 Syntax:
self.__<var_name>=<value>
Achieving Encapsulation

class Emp: Since we have created the


data member as salary so
def init (self): it has become a private
self.age=25 member and cannot be
accessed outside the class
self.name="Rahul" directly
self.__salary=30000.0

e=Emp()
print("Age:",e.age)
print("Name:",e.name)
print("Salary:",e.__salary)
Output:
Achieving Encapsulation

 Now to access such private members , we must define


instance methods in the class

 From outside the class we must call these methods


using object instead of directly accessing data members

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

 Just like we have private data members , we also can


have private methods .

 The syntax is also same.

 Simply prefix the method name with double


underscore to make it a private method
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

 When we declare a data member with double underscore


indicating that it is private , Python actually masks it

 In other words , Python changes the name of the variable


by using the syntax _<classname> <attributename>

 For example , age will actually become _Emp age


So, What It Means To Us ?

 This means that private attributes are not actually


private and are not prevented by Python from getting
accessed from outside the class.

 So if they are accessed using the above mentioned


syntax then no Error or Exception will arise

 So , finally we can say NOTHING IN PYTHON IS


ACTUALLY PRIVATE
Accessing Private Data

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

 In Python , whenever we try to print an object reference


by passing it’s name to the print() function , we get 2
types of outputs:

 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 ?

 This is because whenever we pass an object reference


name to the print() function , Python internally
calls a special instance method available in our class.

 This method is called str () .


From where this
method came ?

 From Python 3.0 onwards , every class which we create


always automatically inherits from the class object

 Or , we can say that Python implicitly inherits our class


from the class object.

 The class object defines some special methods which every


class inherits .

 Amongst these special methods some very important are


init (), str (), new () etc
Can we see all the members
of object class ?

 Yes , it is very simple!

 Just create an instance of object class and call the function


dir( ) .

 Recall that we used dir( ) to print names of all the


members of a module .

 Similarly we also can use dir( ) to print names of all the


members of any class by passing it the instance of the
class as argument
Example

obj=object()
print(type(obj))
print(dir(obj))

Output:
The str () Method

 Now , if we do not redefine (override) this method in our


class , then Python calls it’s default implementation
given by object class which is designed in such a way that
it returns the class name followed by object’s memory
address

 However all built in classes like list , str , tuple , int ,


float , bool etc have overridden this method in such a
way that it returns the content of the object.
Overriding str ()

 So if we also want the same behaviour for our object then


we also can override this method in our class in such a
way that it returns the content of the object.

 The only point we have to remember while overriding this


method is that it should return a string value
Overriding str ()

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

 Just like a constructor is used to initialize an object,


a destructor is used to destroy the object and perform the
final clean up.

 But a question arises that if we already have garbage


collector in Python to clean up the memory , then why
we need a destructor ?
Destructor

 Although in python we do have garbage collector to


clean up the memory, but it’s not just memory which
has to be freed when an object is dereferenced or destroyed.

 There can be a lot of other resources as well, like


closing open files, closing database connections etc.

 Hence when we might require a destructor in our class for


this purpose
Destructor In Python

 Just like we have init () which can be considered like


a constructor as it initializes the object , similarly in
Python we have another magic method called del__().

 This method is automatically called by Python whenever


an object reference goes out of scope and the object is
destroyed.
Guess The Output ?

class Test: Since at the end of the code ,


Python collects the object
def init (self): through it’s garbage
print("Object created") collector so it automatically
calls the del__() method
also
def del (self):
print("Object destroyed")
t=Test()
Output:
How To Force Python
To Call del () ?

 If we want to force Python to call the del__() method ,


then we will have to forcibly destroy the object

 To do this we have to use del operator passing it the


object reference
Guess The Output ?

class Test:
def init (self):
print("Object created")

def del (self):


print("Object destroyed")
t1=Test()
del t1
print("done")
Output:
Guess The Output ?

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

• Advance Concepts Of Object Oriented


Programming-II

• Inheritance
• Types Of Inheritance
• Single Inheritance
• Using super( )
• Method Overriding
Inheritance

 Inheritance is a powerful feature in object oriented


programming.

 It refers to defining a new class with little or no


modification to an existing class.

 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

 It represents real-world relationships well.

 It provides reusability of a code. We don’t have to write


the same code again and again.

 It also allows us to add more features to a class without


modifying it.
Types Of Inheritance
Supported By Python
Syntax Of Single Inheritance
In Python

class BaseClass:
Body of base class

class DerivedClass(BaseClass):
Body of derived class
For Ex:
class Account:
pass
class SavingAccount(Account):
pass
Example

class Animal: duck=Bird()


duck.set_type("Duck")
def eat(self): print(duck)
print("It eats.") duck.eat()
def sleep(self): duck.sleep()
duck.fly()
print("It sleeps.")
Output:
class Bird(Animal):
def set_type(self,type):
self.type=type
def fly(self):
print("It flies in the sky.")
def str (self):
return "This is a "+self.type;
Using super()

 In Python , to call parent class members from the child


class we can use the method super( ).

 Using super() is required in 2 situations:

 For calling parent class constructor

 For calling overridden methods


How Constructors Behave
In Inheritance ?

 Whenever we create a child class object , Python looks


for init () method in child class.

 If the child class doesn’t contain an init () method


then Python goes up in the inheritance chain and looks for
the init () method of parent class
How Constructors Behave
In Inheritance ?

 If the parent class contains init () , then it executes it


.

 Now an important point to notice is that if child class


also has init () , then Python will not call parent’s
init () method.

 That is , unlike Java or C++ , Python does not


automatically call the parent class init () if it finds an
init () method in child class
How Constructors Behave
In Inheritance ?

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 ?

 So , what is the problem if parent constructor


doesn’t get called ?

 The problem is that , if parent class constructor doesn’t


get called then all the instance members it creates will
not be made available to child class
How Constructors Behave
In Inheritance ?

class Rectangle: Since , constructor of


def init (self): Rectangle was not
self.l=10 called , so the
expression self.l
self.b=20 produced exception
class Cuboid(Rectangle): because there is no
def init (self): attribute created by
self.h=30 the name of l
def volume(self):
print("Vol of cuboid is",self.l*self.b*self.h)
obj=Cuboid()
obj.volume()
Output:
How Can We Explicitly
Call init () Of
Parent Class ?

 If we want to call the parent class init () , then we


will have 2 options:

 Call it using the name of parent class explicitly

 Call it using the method super()

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( ) ?

 The method super() is a special method made available


by Python which returns a proxy object that delegates
method calls to a parent class

 In simple words the method super( ) provides us a special


object that can be used to transfer call to parent class
methods
Benefits Of super( )

 A common question that arises in our mind is that why to use


super( ) , if we can call the parent class methods using parent
class name.

 The answer is that super( ) gives 4 benefits:

 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

 It can be used to resolve method overriding

 It is very helpful in multiple inheritance


Method Overriding

 To understand Method Overriding , try to figure out the


output of the code given in the next slide
Guess The Output ?

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

 As we know , whenever we pass the name of an object


reference as argument to the function print( ) ,
Python calls the method str ().

 But since the class Emp doesn’t has this method , so


Python moves up in the inheritance chain to find this
method in the base class Person

 Now since the class Person has this method , Python calls
the str () method of Person which returns only the
name and age
Method Overriding

 Now if we want to change this behavior and show all 4


attributes of the Employee i.e. his name , age ,id and
salary, then we will have to redefine the method
str () in our Emp class.

 This is called Method Overriding

 Thus , Method Overriding is a concept in OOP which


occurs whenever a derived class redefines the same
method as inherited from the base class
Modified Example

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

 When we override a method of base class in the


derived class then Python will always call the derive’s
version of the method.

 But in some cases we also want to call the base class


version of the overridden method.

 In this case we can call the base class version of the


method from the derive class using the function super( )
 Syntax:
super( ). <method_name>(<arg>)
Modified Example

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

 Write a program to create a class called Circle having an instance member


called radius. Provide following methods in Circle class

 init_ () : This method should accept an argument and initialize radius with it

 area(): This method should calculate and return Circle’s area

 Now create a derived class of Circle called Cylinder having an instance


member called height. Provide following methods in Cylinder class

 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)

 volume(): This method should calculate and return Cylinder’s


volume(formula: πr2h)
Solution

import math obj=Cylinder(10,20)


class Circle: print("Area of cylinder is",obj.area())
print("Volume of cylinder is",obj.volume())
def init (self,radius):
self.radius=radius
def area(self):
return math.pi*math.pow(self.radius,2)
class Cylinder(Circle):
def init (self,radius,height):
super().__init (radius)
self.height=height
def area(self):
return 2*super().area()+2*math.pi*self.radius*self.height
def volume(self):
return super().area()*self.height

Output:
A Very Important Point!

 Can we call the base class version of an overridden


method from outside the derived class ?

 For example , in the previous code we want to call the


method area( ) of Circle class from our main script .
How can we do this ?

 Yes this is possible and for this Python provides us a


special syntax:

 Syntax:
<base_class_name>.<method_name>(<der_obj>)
Example

import math obj=Cylinder(10,20)


class Circle: print("Area of cylinder is",obj.area())
print("Volume of cylinder is",obj.volume())
def init (self,radius): print("Area of Circle:",Circle.area(obj))
self.radius=radius
def area(self):
return math.pi*math.pow(self.radius,2)
class Cylinder(Circle): By calling in this way
we can bypass the
def init (self,radius,height):
area( ) method of
super().__init (radius) Cylinder and directly
self.height=height call area( ) method of
def area(self): Circle
return 2*super().area()+2*math.pi*self.radius*self.height
def volume(self):
return super().area()*self.height

Output:
PYTHON
LECTURE 44
Today’s Agenda

• Advance Concepts Of Object Oriented


Programming-III

• MultiLevel Inheritance

• Hierarchical Inheritance

• Using The Function issubclass( )

• Using The Function isinstance( )


MultiLevel Inheritance

 Multilevel inheritance is also possible in Python like


other Object Oriented programming languages.

 We can inherit a derived class from another derived


class.

 This process is known as multilevel inheritance.

 In Python, multilevel inheritance can be done at any


depth.
MultiLevel Inheritance
Syntax

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

 Write a program to create 3 classes Person , Emp and Manager.


Desired Output
Solution

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

def str (self):


str=super().__str ()
return f"{str},Id:{self.id},Salary:{self.sal}"
Solution

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

 In Hierarchical Inheritance, one class is inherited by


many sub classes.
Hierarchical Inheritance

 Suppose you want to write a program which has to keep


track of the teachers and students in a college.

 They have some common characteristics such as


name and age.

 They also have specific characteristics such as salary for


teachers and marks for students.
Hierarchical Inheritance

 One way to solve the problem is that we can create two


independent classes for each type and process them.

 But adding a new common characteristic would mean


adding to both of these independent classes.

 This quickly becomes very exhaustive task


Hierarchical Inheritance

 A much better way would be to create a common class


called SchoolMember and then have the Teacher and
Student classes inherit from this class

 That is , they will become sub-types of this type (class) and


then we can add specific characteristics to these sub-types
Example

class SchoolMember:

def init (self, name, age):


self.name = name
self.age = age
print("Initialized SchoolMember:",self.name)

def tell(self):

print("Name:",self.name,"Age:",self.age, end=" ")


Example

class Teacher(SchoolMember):

def init (self, name, age, salary):


super(). init (name, age)
self.salary = salary
print("Initialized Teacher:", self.name)

def tell(self):
super().tell()
print("Salary:",self.salary)
Example

class Student(SchoolMember):

def init (self, name, age, marks):


super(). init (name, age)
self.marks = marks
print("Initialized Student:",self.name)

def tell(self): Output


super().tell()
print("Marks:",self.marks)
t = Teacher('Mr. Kumar', 40, 80000)
s = Student('Sudhir', 25, 75)
print()
members = [t, s]
for member in members:
member.tell()
How To Check Whether
A Class Is A SubClass Of
Another ?

 Python provides a function issubclass() that directly tells


us if a class is a subclass of another class.

 Syntax:

issubclass(<name of der class>,<name of base class>)

 The function returns True if the classname passed as


first argument is the derive class of the classname
passed as second argument otherwise it returns False
Guess The Output ?

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

 Another way to do the same task is to call the function


isinstance( )

 Syntax:

isinstance(<name of obj ref>,<name of class>)

 The function returns True if the object reference


passed as first argument is an instance of the
classname passed as second argument or any of it’s
subclasses. Otherwise it returns False
Guess The Output ?

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

• Advance Concepts Of Object Oriented


Programming-IV

• Multiple Inheritance
• The MRO Algorithm
• Hybrid Inheritance
• The Diamond Problem
Multiple Inheritance

 Like C++, in Python also a class can be derived from


more than one base class.

 This is called multiple inheritance.

 In multiple inheritance, the features of all the base


classes are inherited into the derived class.
Multiple Inheritance
Syntax

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

class Person: class ScienceStudent(Person,Student):


def init (self,name,age):
def init (self,name,age,roll,per,stream):
self.name=name Person.__init (self,name,age)
self.age=age Student. init (self,roll,per)
def getname(self): self.stream=stream
def getstream(self):
return self.name return self.stream
def getage(self):
return self.age ms=ScienceStudent("Suresh",19,203,89.4,"maths")
class Student: print("Name:",ms.getname())
print("Age:",ms.getage())
def init (self,roll,per): print("Roll:",ms.getroll())
self.roll=roll print("Per:",ms.getper())
self.per=per print("Stream:",ms.getstream())

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 ?

 In languages that use multiple inheritance, the order in


which base classes are searched when looking for a
method is often called the Method Resolution Order,
or MRO.

 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 ?

 Yes, Python allows us to see this MRO by calling a method


called mro( ) which is present in every class by default.
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
Another Way To See MRO ?

 There is a tuple also called


mro made available in
every class by Python using which we can get the same
output as before

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

 This form combines more than one form of inheritance.


Basically, it is a blend of more than one type of inheritance.
Example

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

 The “diamond problem” is the generally used term for


an ambiguity that arises in hybrid inheritance .

 Suppose two classes B and C inherit from a superclass A,


and another class D inherits from both B and C.

 If there is a method "m" in A that B and C have


overridden, then the question is which version of the
method does D inherit?
Guess The Output

class A:
obj=D()
def m(self):
print("m of A called") obj.m()

class B(A): Why m() of B was called ?


def m(self):
print("m of B called") As discussed previously , Python
uses MRO to search for an
class C(A): attribute which goes from left to
def m(self): right and then in depth first.
print("m of C called") Now since B is the first
inherited class of D so Python
class D(B,C): called m( ) of B
pass
Output:
Guess The Output

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 ?

 Exception are errors that occur at runtime .

 In other words , if our program encounters an abnormal


situation during it’s execution it raises an exception.

 For example,the statement


a=10/0
will generate an exception because Python has no way to
solve division by 0
What Python Does When
An Exception Occurs ?

 Whenever an exception occurs , Python does 2 things :

 It immediately terminates the code

 It displays the error message related to the exception in a


technical way

 Both the steps taken by Python cannot be considered user


friendly because
 Even if a statement generates exception , still other parts of
the program must get a chance to run

 The error message must be simpler for the user to understand


A Sample Code

a=int(input("Enter first no:"))


b=int(input("Enter second no:"))
As we can observe , in the
c=a/b second run the code
print("Div is",c) generated exception because
Python does not know how to
d=a+b handle division by 0.
Moreover it did not even
print("Sum is",d) calculated the sum of 10 and
0 which is possible
Output:
A Sample Code

a=int(input("Enter first no:"))


b=int(input("Enter second no:"))
c=a/b In this case since it is not
possible for Python to covert
print("Div is",c) “2a” into an integer , so it
d=a+b generated an exception . But
the message it displays is too
print("Sum is",d) technical to understand

Output:
How To Handle
Such Situations ?

 If we want our program to behave normally , even if an


exception occurs , then we will have to apply
Exception Handling

 Exception handling is a mechanism which allows us to


handle errors gracefully while the program is running
instead of abruptly ending the program execution.
Exception Handling Keywords

 Python provides 5 keywords to perform Exception


Handling:

 try

 except

 else

 raise

 finally
Exception Handling Syntax

 Following is the syntax of a Python try-except-else block.

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=int(input("Enter first no:"))


b=int(input("Enter second no:"))
try:
c=a/b
print("Div is",c)
except ZeroDivisionError:
print("Denominator should not be 0")
d=a+b
print("Sum is",d)
Output:
Exception Hierarchy
Important Exception Classes

Exception Class Description

Exception Base class for all exceptions

ArithmeticError Raised when numeric calculations fails

FloatingPointError Raised when a floating point


calculation fails
ZeroDivisionError Raised when division or modulo by
zero takes place for all numeric types
OverflowError Raised when result of an arithmetic
operation is too large to be represented
ImportError Raised when the imported module is not
found in Python version < 3.6
ModuleNotFoundError Raised when the imported module is not
found from Python version >=3.6
Important Exception Classes

Exception Class Description

LookupError Raised when searching /lookup fails

KeyError Raised when the specified key is not


found in the dictionary
IndexError Raised when index of a sequence is out
of range
NameError Raised when an identifier is not found
in the local or global namespace
UnboundLocalError Raise when we use a local variable in a
function before declaring it.
TypeError Raised when a function or operation is
applied to an object of incorrect type
ValueError Raised when a function gets argument of
correct type but improper value
Important Exception Classes

Exception Class Description


Raised when a non-existent attribute is
AttributeError referenced.

OSError Raised when system operation causes


system related error.
FileNotFoundError Raised when a file is not present

FileExistsError Raised when we try to create a directory


which is already present
PermissionError Raised when trying to run an operation
without the adequate access rights.
SyntaxError Raised when there is an error in Python
syntax.
IndentationError Raised when indentation is not specified
properly.
Handling Multiple Exception

 A try statement may have more than one except clause for
different exceptions.

 But at most one except clause will be executed


Point To Remember

 Also , we must remember that if we are handling parent


and child exception classes in except clause then the
parent exception must appear after child exception ,
otherwise child except will never get a chance to run

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

 Write a program to ask the user to input 2 integers and


calculate and print their division. Make sure your program
behaves as follows:

 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

 If we want to write a single except clause to handle


multiple exceptions , we can do this .

 For this we have to write names of all the exceptions


within parenthesis separated with comma after the
keyword except
Example

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

 We can write the keyword except without any exception


class name also .

 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

 Following is the syntax of a Python handle all


exception block.

Notice , we have not provided


try: any name for the exception
You do your operations here;
......................
except :
For every kind of exception this block will execute
Example

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

 Now we know how to handle exception, in this section we


will learn how to access exception object in exception
handler code.

 To access the exception object created by Python we can


use the keyword as and assign it to a variable.

 Finally using that variable we can get the details of the


exception
Example

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

 Sometimes , we need to print the details of the exception


exactly like Python does .

 We do this normally , when we are debugging our code.

 The module traceback helps us do this


Obtaining Exception Details
Using traceback module

 This module contains a function called format_exc( )

 It returns complete details of the exception as a string.

 This string contains:


 The program name in which exception occurred
 Line number where exception occurred
 The code which generated the exception
 The name of the exception class
 The message related to the exception
Example

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

 We can force Python to generate an Exception using the


keyword raise.

 This is normally done in those situations where we want


Python to throw an exception in a particular condition of
our choice

 Syntax:
 raise ExceptionClassName
 raise ExceptionClassName( message )
Exercise

 Write a program to ask the user to input 2 integers and


calculate and print their division. Make sure your program
behaves as follows:

 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

 If we have a code which we want to run in all situations,


then we should write it inside the finally block.

 Python will always run the instructions coded in the


finally block.

 It is the most common way of doing clean up tasks , like,


closing a file or disconnecting with the DB or
logging out the user etc
Syntax Of The finally Block

 The finally block has 2 syntaxes:


Syntax 1
try:
# some exception generating code
except :
# exception handling code
finally:
# code to be always executed
Syntax 2
try:
# some exception generating code
finally:
# code to be always executed

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

 Python has many built-in exceptions which forces our


program to output an error when something in it goes
wrong.

 However, sometimes we may need to create our own


exceptions which will be more suitable for our purpose.

 Such exceptions are called User Defined Exceptions


Creating User Defined
Exception

 In Python, users can define such exceptions by creating a


new class.

 This exception class has to be derived, either directly or


indirectly, from Exception class.

 Most of the built-in exceptions are also derived form this


class.
PYTHON
LECTURE 48
Today’s Agenda

• Operator Overloading

• What Is Operator Overloading


• How To Perform Operator Overloading
• List Of Operators Which Can Be Overloaded
• Reverse Arithmetic Operators
What Is
Operator Overloading?

 Operator overloading means redefining existing


operators in Python to work on objects of our classes.

 For example, a + operator is used to add the numeric


values as well as to concatenate the strings.

 That’s because operator + is overloaded for int class


and str class.
What Is
Operator Overloading?

 But we can give extra functionality to this + operator


and use it with objects of our own class.

 This method of giving extra functionality to the


operators is called operator overloading.
Guess The Output ?

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?

 There is an underlying mechanism related to


operators in Python.

 The thing is when we use operators, a special function


or magic function is automatically invoked that is
associated with that particular operator.
How To Perform
Operator Overloading?

 For example, when we use + operator, the magic


method add is automatically invoked in which the
operation for + operator is defined.

 So by changing this magic method’s code, we can give


extra meaning to the + operator.
Example

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

def str (self):


return f"x={self.x},y={self.y}“
p1=Point(10,20)
p2=Point(30,40)
p3=p1+p2
print(p3)
Output:
Explanation

 When we wrote p1 + p2, then Python did the following:

 It searched for the magic method add () in our Point class since
the left side operand i.e. p1 is of Point class.

 After finding add () in our class Python converted our


statement p1+p2 to p1. add (p2) which in turn
is Point. add (p1,p2).

 So p1 is passed as self and p2 is passed to other

 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

def str (self):


return f"x={self.x},y={self.y}"
p1=Point(10,20)
p2=Point(30,40)
p3=p1+p2
print(p3)
p4=p1+p2+p3
print(p4)
Output:
Exercise

 Write a program to create a class called Distance having 2 instance


members called feet and inches . Provide following methods in Distance
class

 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

class Distance: d1=Distance(10,6)


def init (self,feet,inches): d2=Distance(8,9)
self.feet=feet d3=d1+d2
self.inches=inches print(d1)
print(d2)
def add (self,other):
print(d3)
feet=self.feet+other.feet
inches=self.inches+other.inches
if inches>=12:
feet=feet+inches//12
inches=inches%12
d=Distance(feet,inches)
return d

def str (self):


return f"feet={self.feet},inches={self.inches}“
Output:
Guess The Output ?

class Distance: d1=Distance(10,6)


def init (self,feet,inches): d2=Distance(8,9)
self.feet=feet
d3=d1+d2
self.inches=inches
print(d1)
def add (self,other): Why did AttributeError
feet=self.feet+other.feet print(d2)
occur ?
inches=self.inches+other.inches print(d3)
This is because Python is
if inches>=12: d4=d1+10 trying to use the int object
feet=feet+inches//12 print(d4) as Distance object and
inches=inches%12 since int class has no feet
d=Distance(feet,inches) data member the code is
return d throwing AttributeError

def str (self):


return f"feet={self.feet},inches={self.inches}“

Output:
Solution

class Distance: d1=Distance(10,6)


def init (self,feet,inches): d2=Distance(8,9)
self.feet=feet
d3=d1+d2
self.inches=inches
print(d1)
def add (self,other):
if isinstance(other,Distance):
print(d2)
feet=self.feet+other.feet print(d3)
inches=self.inches+other.inches d4=d1+10
else: print(d4)
feet=self.feet+other
inches=self.inches+other We have used isinstance()
if inches>=12: function to determine
feet=feet+inches//12 whether the argument
inches=inches%12 other is of type Distance or
d=Distance(feet,inches) not . If it is of type Distance
return d we perform usual addition
def str (self): logic , otherwise we simply
return f"feet={self.feet},inches={self.inches}“ add the argument other to
self.feet and self.inches as
Output: int value
List Of Arithmetic Operator
For Overloading

Operator Expression Internally


Addition p1 + p2 p1. add (p2)

Subtraction p1 - p2 p1. sub__(p2)

Multiplication p1 * p2 p1. mul__(p2)

Power p1 ** p2 p1. pow (p2)

Division p1 / p2 p1. truediv (p2)

Floor Division p1 // p2 p1. floordiv (p2)

Remainder (modulo) p1 % p2 p1. mod__(p2)


Exercise

 Write a program to create a class called Book having 2 instance members


called name and price . Provide following methods in Book class

 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

class Book: b1=Book("Mastering Python",300)


def init (self,name,price): b2=Book("Mastering Java",500)
self.name=name
print(b1)
print(b2)
self.price=price
print("Total price of books is:",b1+b2)

def add (self,other):


totalprice=self.price+other.price
return totalprice

def str (self):


return f"name={self.name},price={self.price}"

Output:
Guess The Output ?

class Book: b1=Book("Mastering Python",300)


def init (self,name,price): b2=Book("Mastering Java",500)
self.name=name
b3=Book("Mastering C++",400)
print(b1)
self.price=price
print(b2)
print(b3)
def add (self,other): print("Total price of books
totalprice=self.price+other.price is:",b1+b2+b3)
return totalprice

def repr (self):


return f"name={self.name},price={self.price}"

Output:
Why Did TypeError Occur ?

 TypeError occurred because Python evaluated the statement


b1+b2+b3 as follows:

 At first it solved b1+b2 , which became b1. add__(b2).

 So Python called add () method of Book class since the left operand
is b1 which is object of class Book

 This call returned the total price of b1 and b2 which is 800.

 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 .

 So the code threw TypeError


What Is The Solution To This
Problem ?

 The solution to this problem is to provide reverse special


methods in our class.

 The standard methods like add__(), sub () only


work when we have object of our class as left operand .
What Is The Solution To This
Problem ?

 But they don’t work when we have object of our class on


right side of the operator and left side operand is not
the instance of our class.

 For example : obj+10 will call add__() internally,


but 10+obj will not call add ()
What Is The Solution To This
Problem ?

 Therefore, to help us make our classes mathematically


correct, Python provides us with reverse/reflected
special methods such
as radd (), rsub (), rmul (), and so on.

 These handle calls such as x + obj, x - obj, and x * obj,


where x is not an instance of the concerned class.
Reflected Operators
Modified Example

class Book: b1=Book("Mastering Python",300)


def init (self,name,price): b2=Book("Mastering Java",500)
self.name=name b3=Book("Mastering C++",400)
self.price=price print(b1)
print(b2)
def add (self,other):
print(b3)
totalprice=self.price+other.price
print("Total price of books
return totalprice is:",b1+b2+b3)
def radd (self,other):
totalprice=self.price+other
return totalprice
def str (self):
return f"name={self.name},price={self.price}"
Output:
List Of Relational Operator
For Overloading

Operator Expression Internally

Less than p1 < p2 p1. lt (p2)

Less than or equal to p1 <= p2 p1. le (p2)

Equal to p1 == p2 p1. eq__(p2)

Not equal to p1 != p2 p1. ne (p2)

Greater than p1 > p2 p1. gt__(p2)

Greater than or equal to p1 >= p2 p1. ge (p2)


Exercise

 Write a program to create a class called Distance having 2 instance


members called feet and inches . Provide following methods in Distance
class

 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

 eq () : This method should compare 2 Distance objects and return True if


they are equal otherwise it should return False
Solution

class Distance: d1=Distance(0,12)


def init (self,feet,inches): d2=Distance(1,0)
self.feet=feet print(d1)
self.inches=inches print(d2)
if d1==d2 :
def eq (self,other):
print("Distances are equal")
x=self.feet*12+self.inches
else:
y=other.feet*12+other.inches print("Distances are not equal")
if x==y:
return True
else:
return False
def str (self):
return f"feet={self.feet},inches={self.inches}“
Output:
List Of Shorthand Operator
For Overloading

Operator Expression Internally

-= p1-=p2 p1. isub__(p2)

+= p1+=p2 p1. iadd (p2)

*= p1*=p2 p1. imul (p2)

/= p1/=p2 p1. idiv (p2)

//= p1//=p2 P1. ifloordiv__(p2)

%= p1%=p2 p1. imod (p2)

**= p1**=p2 p1. ipow (p2)


List Of Special Functions/Operator s
For Overloading

Function/Operator Expression Internally

len( ) len(obj) obj.__len (self)

[] obj[0] obj.__getitem (self,index)

in var in obj obj.__contains (self,var)

str( ) str(obj) obj.__str (self)

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

• Database Programming In Python-I


• What Is Data And Database ?

• What Is DBMS ?

• What Is SQL ?

• How To Configure Our System For Database


Programming In Python ?
Introduction

 Before we learn about Database Programming In


Python, let's first understand -

 What is Data?

 What is Database ?
Introduction

 What is Data?

 In simple words data can be facts or information.

 For example your name, population of a country , names of


political parties in your country , today’s temperature etc

 A picture , image , file , pdf etc can also be considered data.


Introduction

 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 discuss few examples.


 Your mobile’s phone book is a database as it stores data pertaining to
people like their phone numbers, name and other contact details etc.

 Your University uses database to store student details like enrollment


no, name , address , academic performance etc

 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 ?

 Most of the databases store their data in the form of tables

 Each table in a database has one or more columns, and each


column is assigned a specific data type, such as an integer
number, a sequence of characters (for text), or a date.

 Each row in the table has a value for each column.


How Databases
Store The Data ?
Components Of A Table
What Is A DBMS ?

 A DBMS is a program or a software that allows users to


perform different operations on a database.

 These operations include:

 Creating the database/tables

 Inserting records into these tables

 Selecting records from these tables for displaying

 Updating / Deleting the records


What Is A DBMS ?
Some Popular DBMS

 Some of the most popular DBMS are:

 Oracle

 MySQL

 MS SQL Server

 SQLite

 PostgreSQL

 IBM DB2

and many more


The Market Leader
What Is SQL ?

 SQL is an abbreviation for “Structured Query


Language”.

 It is a language used by EVERY DBMS to interact with the


database.

 It provides us COMMANDS for inserting data to a


database, selecting data from the database and
modifying data in the database
Pictorial View Of SQL
Database Programming
In Python

 Python is wonderfully able to interact with databases,


and this is what we will learn in this chapter.

 Advantages:

 Platform-independent

 Faster and more efficient

 Easy to migrate and port database application interfaces


How Python Connects
To Database?

 Python uses the Python Database API in order to


interact with databases.

 An API stands for Application Programming


Interface.

 It is a set of predefined functions , classes and


methods given by the language for a particular task
and the programmer can use it whenever he wants to
perform that task in his code.
How Python Connects
To Database?

 The Python Database API allows us to handle


different database management systems (DBMS) in
our Python code.

 However the steps at the code level remain


altogether same.

 That is using the same steps we can connect to Oracle or


MySQL or SQLite or any other DBMS
PYTHON
LECTURE 50
Today’s Agenda

• Database Programming In Python-II


• Introduction To SQLite

• Steps Needed For Connecting To SQLite From Python

• Exploring Connection And Cursor Objects

• Executing The SQL Queries

• Different Ways Of Fetching The Data


Introduction To SQLite

 SQLite is an Open Source Database developed in C


programming language.

 It stores data to a text file on the device and is a


popular choice for application softwares such as web
browsers as well as mobile platforms like Android and
iOS.
SQLite Features

 Extremely light-weighted (not more than 500 KBs)

 No complex setup

 Fully transactional.

 It supports all standard relational database features like


SQL Queries, Joins , Constraints etc
Who Uses Sqlite ?

Following are well known companies/products that use


SQLite:
Adobe
Apple
McAfee
Microsoft
DropBox
Facebook
Google
Python
PHP
SQLite Limitations

 SQLite supports neither RIGHT OUTER JOIN nor


FULL OUTER JOIN. It supports only LEFT OUTER
JOIN.

 With ALTER TABLE statement in SQLite we can only


add a column or rename a table or column.

 However, we can't do the following:

 DROP a column.

 ADD a constraint.
SQLite Limitations

 GRANT and REVOKE commands are not implemented in


SQLite.

 VIEWs are read-only – we can't write INSERT,


DELETE, or UPDATE statements into the view.

 SQLite only supports FOR EACH ROW triggers, and it


doesn't support FOR EACH STATEMENT triggers.
SQLite Installation

 Installing and setting up SQLite takes a matter of a few


minutes.

 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.

 This is called DB Browser for SQLite.

 We can download it from


https://sqlitebrowser.org/dl/ with respect to our OS
platform.
SQLite Installation

 On Windows platform, the interface for DB Browser for


SQLite looks like this –
Steps Required For
Connecting Python Code To SQLite

 Connecting our Python app to any database involves


total 6 important steps.

 Also remember that these steps will always remain


same irrespective of the database we are trying to
connect

 The only difference will be the change in the name of


the module
Steps Required For
Connecting Python Code To Sqlite

 For connecting to SQLite , the steps are:

 Import the module sqlite3

 Establish a connection to the database.

 Create a cursor to communicate with the data.

 Execute the SQL query

 Fetch the result returned by the SQL query

 Close the cursor and connection to the database.


Step 1-
Importing The Module

 Since we are connecting to SQlite , so all the functions


and classes we will be using will be supplied by the
module called sqlite3.

 So the first step will be to import this module by writing


the following statement:

import sqlite3
Step 2-
Establishing The Connection

 After importing the module ,we must open the connection to the
SQlite.

 This can be done by calling the function connect( ) of sqlite3


module having the following syntax:

sqlite3.connect( “path to the db file”)

 Following is the description of this function:


 It accepts a connection string as argument mentioning the path to the db
file

 If a connection is established, then a Connection object is returned.

 If there is any problem in connecting to the database , then this function


throws the exception called sqlite3.DatabaseError
Important Attributes/Methods Of
Connection Object

 When the connection is successful , we get back the


sqlite3.Connection object.

 This object provides us some important methods which are


as follows:

 cursor() : Return a new Cursor object using the connection.


 close(): Closes the connection
 commit(): Commits any pending transactions to the database.
 rollback(): Rollbacks any pending transactions.
Step 3-
Creating The Cursor

 Once we have a connection, we need to get a cursor

 A Cursor allows us to send all the SQL commands from our


Python code to the database.

 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.

 To get a Cursor object we call the method cursor( ) of the


Connection object as follows:

cur=conn.cursor()
Important Attributes/Methods Of
Cursor Object

 A Cursor object provides us some attributes and methods to execute


the SQL query and get back the results

 Following are it’s important attributes:


 rowcount: Returns the number of rows fetched or affected by the last operation,
or -1 if the module is unable to determine this value.

 Following are it’s important methods:

 execute(statement) : Executes an SQL statement string on the DB


 fetchall(): Returns all remaining result rows from the last query as a sequence of tuples
 fetchone(): Returns the next result row from the last query as a tuple
 fetchmany(n): Returns up to n remaining result rows from the last query as a sequence
of tuples.
 close(): Closes the cursor
Step 4-
The execute( ) Method

 Syntax:

execute(SQL statement, [parameters], **kwargs)

 This method can accept an SQL statement - to be run


directly against the database. It executes this SQL query
and stores the result.

 For example:
cur.execute('select * from allbooks')
The execute( ) Method

 It can also accept Bind variables assigned through the


parameters or keyword arguments.

 We will discuss this later


Step 5-
Fetching The Result

 Once we have executed the SELECT query , we would like


to retrieve the rows returned by it.

 There are numerous ways to do this:

 By iterating directly over the Cursor object

 By calling the method fetchone()

 By calling the method fetchall()

 We will discuss each of these methods after step 6


Step 6-
Fetching The Result

 The final step will be to close the cursor as well as


close the connection to the database once we are done
with processing.

 This is done by calling the method close() on both the


objects.

 Example:
cur.close()
conn.close()
An Important Point!

 During communication with Sqlite , if any problem occurs


the methods of the module sqlite3 throw an exception
called DatabaseError.

 So it is a best practice to execute sqlite3 methods that


access the database within a try..except structure in order
to catch and report any exceptions that they might throw.
Directly Iterating
Over The Cursor

 The Cursor object holds all the rows it retrieved from the
database as tuples.

 So if we iterate over the Cursor object using the for loop


, then we can retrieve these rows
Exercise

 Assume you have a table called Allbooks in the database


which contains 4 columns called bookid, bookname,
bookprice and subject.

 Write a Python code to do the following:

 Connect to the database

 Execute the query to select name of the book and it’s price from the
table Allbooks

 Display the records


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")
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

 Modify the code so that values are displayed without tuple


symbol i.e. without the symbol of ( )
 Sample Output
Solution

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( )

 Sometimes we may want to pull just one record at a time


from the table .

 As a result Cursor object provides us a method called


fetchone( ) .

 This method returns one record as a tuple, and if there


are no more records then it returns None
Exercise

 Modify the previous code to display the name and price of


the costliest book from the table Allbooks

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)

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 fetchall( )

 Syntax:
cur.fetchall()

 The method fetches all rows of a query result set and


returns it as a list of tuples.

 If no more rows are available, it returns an empty list.


Sample Code

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

 Modify the previous book application so that your code asks


the user to enter a record number and displays only that
book .

 Make sure if the record number entered by the user is


wrong then display appropriate error message
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")
booklist=cur.fetchall()
recnum=int(input("Enter the record number(1 to
"+str(len(booklist))+"):"))
Solution

if recnum <1 or recnum>len(booklist):


print("Record number should be between 1 to
"+str(len(booklist)))
else:
row=booklist[recnum-1]
print(row[0],row[1])

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 51
Today’s Agenda

• Database Programming In Python-III


• Executing INSERT Command

• Executing Dynamic Queries

• Concept Of Bind Variables

• Executing Update Command

• Executing Delete Command


Inserting Record

 To insert a new record in the table we have to execute the


INSERT INTO command.

 It has 2 syntaxes:

 Insert into <table_name> values(<list of values>)

 Insert into <table_name>(<list of cols>) values(<list of


values>)
Inserting Record

 To insert a record in the table from our Python code we simply


pass the insert query as argument to the execute( ) method of
cursor object.

 It’s general syntax is:


cur.execute(“insert query”)

 Two important points:

 After executing insert if we want to get the number of row inserted we can
use the cursor attribute rowcount

 Unless we call the method commit( ) of connection object , the record we


insert does not get saved in the table
Steps Required For
Inserting Records

 For inserting record the overall steps are:

 Import the module sqlite3

 Establish a connection to the database.

 Create a cursor to communicate with the data.

 Execute the Insert query

 Commit the changes

 Close the connection to the database.


Example

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

 Dynamic queries are those where we set the values to


be passed in the query at run time.

 For example , we would like to accept the values of the


record to be inserted from the user and then pass it to
the insert query.

 Such queries are called dynamic query


Executing Dynamic Queries

 Dynamic queries for Sqlite can be set using the concept


of bind variables

 Bind variables are like placeholders used in a query ,


represented using :some_number, and are replaced with
actual values before query execution.
Using bind variables
By Position
In this Insert query :1,:2,:3 and :4
import sqlite3 are called bind variablesand they
conn=None will be replaced with the values of
try: the actual variables id,name,price
and subject before the query is
conn=sqlite3.connect("d:/mysqlitedb/library.db") sent for execution.
print("Connected successfully to the DB") Also , parenthesis is required
cur=conn.cursor() because these values are sent as a
tuple
id=int(input("Enter bookid:"))
name=input("Enter bookname:")
price=int(input("Enter bookprice:"))
subject=input("Enter subject:")
cur.execute("Insert into allbooks values(:1,:2,:3,:4)",(id,name,price,subject))
n=cur.rowcount
print(n," row inserted")
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")
Sample Output
Updating Record

 To update a record in the table we have to execute the


UPDATE command.

 It has 2 syntaxes:

 Update <table name> set <col name>=<value>

 Update <table name> set <col name>=<value> where


<test condition>
Updating Record

Updating a record through Python code is same as inserting a


new record. .

 We call the method execute( ) of cursor object passing it the


update query.

It’s general syntax is:


cur.execute(“update query”)

 If the query is dynamic then we can use bind variables for


setting the values at run time.
Example

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

 Write a program to accept a subject name and an


amount from the user and increase the price of all the
books of the given subject by adding the amount in the
current price. Finally display whether books were
updated or not and how many books were updated

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()

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")
Deleting Record

 To delete a record from the table we have to execute the


DELETE command.

 It has 2 syntaxes:

 Delete from <table name>

 Delete from <table name> where <test condition>


Deleting Record

Deleting a record through Python code is same as


updating/inserting a record. .

 We call the method execute( ) of cursor object passing it the


delete query.

It’s general syntax is:


cur.execute(“delete query”)

 If the query is dynamic then we can use bind variables for


setting the values at run time.
Example

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()

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

 Write a program to accept a subject name from the user


and delete all the books of the given subject .Finally
display whether books were deleted or not and how many
books were deleted

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 ?

 File handling is the process of accessing data files stored


in the secondary memory of our computer.

 It allows us to perform various operations on these


files through our program like renaming files,
deleting file, moving file and above all reading and
writing the contents in a File
What Is File Handling ?
Real Life Examples Of
File Handling

 Mobile’s Phonebook

 Computer/Mobile Games

 Call Logs

 Gallery In Mobile

 User Accounts In Operating System

 Windows Registry
Steps Needed For File Handling

 Broadly , file handling involves 3 steps:

 Open the file.

 Process file i.e perform read or write operation.

 Close the file.


Step -1 : Opening The File

 Before we can perform any operation on a file, we must


open it.

 Python provides a function called open() to open a file.

 Syntax:

fileobject = open(filename, mode)

 The filename is the name or path of the file.

 The mode is a string which specifies the type operation we want to


perform on the file (i.e read, write, append, etc). Default is read
File Opening Modes

Mode Description

Opens the file for reading. If the file doesn't


"r" already exists we will
get FileNotFoundError exception

Opens the file for writing. In this mode, if


file specified doesn't exists, it will be
"w" created. If the file exists, then it's data is
destroyed. If the path is incorrect then we
will get FileNotFoundError exception

Opens the file in append mode. If the file


doesn't exists this mode will create the file.
"a" If the file already exists then it appends new
data to the end of the file rather than
destroying data as "w" mode does.
File Opening Modes

Mode Description

“r+” Opens file for both reading and writing.

Opens a file for both writing and reading. If


“w+” the file exists then it will overwrite it
otherwise it will create it.

Opens file for appending and reading. If


the file already exists then pointer will be
“a+”
set at the end of the file otherwise a new
file will be created.
Examples Of Opening File

 Example 1:
 f = open("employees.txt", "r")

 This statement opens the file employees.txt for reading.

 Example 2:
 f = open("teams.txt", "w")

 This statement opens the file teams.txt in write mode.

 Example 3:
 f = open("teams.txt", "a")

 This statement opens the file teams.txt in append mode.


Examples Of Opening File

 Instead of using relative file paths we can also use


absolute file paths.

 For example:
 f = open("C:/Users/sachin/documents/README.txt", "w")

 This statements opens the text file README.txt that is


in C:\Users\sachin\documents\ directory in write
mode.
Examples Of Opening File

 We can also use something called "raw string" by


specifying r character in front of the string as follows:

 f = open(r"C:\Users\sachin\documents\README.txt", "w")

 The r character causes the Python to treat every character


in string as literal characters.
Step -3 : Closing The File

 Once we are done working with the file or we want to open


the file in some other mode, we should close the file
using close() method of the file object as follows:

 f.close()
The TextIOWrapper Class

 The file object returned by open() function is an object of


type TextIOWrapper.

 The class TextIOWrapper provides methods and


attributes which helps us to read or write data from and
to the file.

 In the next slide we have some commonly used methods


of TextIOWrapper class.
Methods Of
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.

tell() Returns the current position of the file


pointer.
close() Closes the file
Exceptions Raised In
File Handling

 Python generates many exceptions when something


goes wrong while interacting with files.

 The 2 most common of them are:

 FileNotFoundError: Raised when we try to open a file that doesn't


exist

 OSError: Raise when an operation on file cause system related error.


Exercise

 Write a program to create a file called message.txt in d:\ of


your computer .

 Now ask the user to type a message and write it in the file .

 Finally display how many capital letters, how many small


letters , how many digits and how many special
characters were written in the file.

 Also properly handle every possible exception the code can throw
Sample Output
Solution

fout=None print("File saved successfully!")


print("Total upper case letters are :",upper)
try: print("Total lower case letters are :",lower)
fout=open("d:\\message.txt","w") print("Total digits are :",digits)
text=input("Type a message:") print("Total special characters are :",
len(text)-(lower+upper+digits))
upper=0
except FileNotFoundError as ex:
lower=0 print("Could not create the file: ",ex)
digits=0
except OSError:
for ch in text:
print(“Some error occurred while writing”)
fout.write(ch)
if 65<=ord(ch)<=90: finally:
upper+=1 if not fout is None:
fout.close()
elif 97<=ord(ch)<=122: print("File closed successfully")
lower+=1
elif 48 <=ord(ch)<=57:
digits+=1
Exercise

 Write a program to open the message.txt created by the


previous code.

 Now read and display the contents of the file.


Click to add text

 Also properly handle every possible exception the code can


throw

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

 Write a program to create a file called message.txt in d:\ of your


computer .

 Now ask the user to continuously type messages and save them in the
file line by line.

 Stop when the user strikes an ENTER key on a new line

 Finally display how many lines were written in the file.

 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()

print("File saved successfully!")


print("Total lines written are :",lines)

except FileNotFoundError as ex1:


print("Could not create the file: ",ex1)

except OSError as ex2:


print(ex2)

finally:
if fout is not None:
fout.close()
print("File closed successfully")
Exercise

 Write a program to open the message.txt created by the


previous code.

 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:
fin=open("d:\\message.txt","r")
lines=0
while True:
text=fin.readline()
if text=="":
break
lines+=1
print(text,end="")

print("Total lines read are :",lines)

except FileNotFoundError as ex:


print("Could not open the file: ",ex)

finally:
if fin is not None:
fin.close()
print("File closed successfully")
Using for Loop To
Read The File

 Python allows us to use for loop also to read the contents


of the file line by line.

 This is because the object of TextIOWrapper is also a


kind of collection/sequence of characters fetched from
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

 Write a program to open the message.txt created by the


previous code.

 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
Solution

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)

except FileNotFoundError as ex:


print("Could not open the file: ",ex)

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

 To reset the internal file pointer we use the seek() method.

 Syntax:
seek(offset, whence).

 whence is optional, and determines where to seek from.

 If whence is 0, the bytes/letters are counted from the beginning.

 If it is 1, the bytes are counted from the current cursor position.

 If it is 2, then the bytes are counted from the end of the file.

 If nothing is put there, 0 is assumed.

 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

 Write a program to create the file message.txt in d:\ of your


computer

 Now ask the user to continuously type messages and save them in the
file line by line.

 Stop when the user strikes an ENTER key on a new line

 Finally display how many lines were written in the file.

 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()

print("File saved successfully!")


print("Total lines written are :",lines)
print("Press any key to read the data:")
input()
fobj.seek(0)
lines=0
Solution

while True:
text=fobj.readline()
if text=="":
break
lines+=1
print(text,end="")

print("Total lines read are :",lines)

except FileNotFoundError as ex1:


print("Could not open the file: ",ex1)

except OSError as ex2:


print("Error in file I/O: ",ex2)

finally:
if 'fobj' in globals():
fobj.close()
print("File closed successfully")
Appending Data In a File

 We can use "a" mode to append data to end of the 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.

 Moreover if the file is not present it gets created.


Example

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="")

except FileNotFoundError as ex:


print("Could not open the file: ",ex)

finally:
if fobj is not None:
fobj.close()
print("File closed successfully")
Using with Statement

 Python also provides a nice shortcut for file handling


using the with statement.

 The following is the general form of the with statement


when used with files.

with open(filename, mode) as file_object:


# body of with statement
# perform the file operations here
Important Points
About with Statement

 It automatically closes the file without requiring any work


on our part.

 The scope of file_object variable is only limited to the


body of the with statement.

 So , if we try to call read() or write() method on it outside


the block we will get NameError.
Example

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 ?

 Python modules are .py files that consist of Python


code.

 So all the Python programs that we have written can be


called a module.
From Where These Modules
Come ?

 Modules are available in 3 ways:

 Some modules are available through the Python Standard


Library and are therefore installed with our Python installation.
Examples of such modules are: math, sys,random etc

 We also can install modules developed by other programmers using


Python’s package manager called pip.

 Additionally, we can create our own Python modules since


modules are comprised of Python .py files.
What A Module Can Contain ?

 A Python module can contain any valid Python element


like:

 variables

 functions

 classes
Defining A Module

def greet(name):
print("Good Morning ",name,"!")

 Save the above code in a file called welcome.py

welcome.py
def greet(name):
print("Good Morning ",name,"!")
Using A Module

 To use a module we must import it in our program which


can be done in 4 ways:

 Using import

 Using aliasing

 Using from

 Using wildcard
First Way
(Direct import)

 Create another Python file called test.py and import the


module welcome.py in it.

 Now we can call the function greet() by using the syntax as


shown below:

 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)

 In the previous example we had to prefix the name of the


module called welcome before the name of it’s function
greet()

 In order to shorten this syntax , Python allows us to alias


the module name using the keyword as

 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

 If we do not want to prefix the module name at all with any


prefix then we must import specific members of a
module

 To do this , Python provides us from keyword

 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

 It is also possible to import all names from a module


into the current file by using the wildcard character *

 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

 It is also possible to define a class inside a module


containing attributes and methods

 It can be accessed in the same way like we can access


functions
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__’

 Now after learning basics of modules , let us discuss


another very important concept in Python.

 All programmers who write standard code in Python


always include a test condition in their module which is
something like :

if name==‘ main ’:
Some code

 So let us understand what it is all about


The Concept Of
name ==‘ main__’

 Before we start the discussion , guess the output of the


following code:
Why did the code not
produce any output?
calculate.py
def add(a, b): This is because add()
print("Sum of",a,"and",b,"is",a+b) and subtract() are
functions and
functions are
def subtract(a, b): executed only when
print("Diff of", a, "and", b, "is", a - b) they are called .

But since we didn’t


Run:
python calculate.py call any of these
functions so no
Output: output was produced
The Concept Of
name ==‘ main__’

 Now , guess the output:


calculate.py
def add(a, b): As expected the code
print("Sum of",a,"and",b,"is",a+b) is showing the
results of both add()
and subtract()
def subtract(a, b): functions as we have
print("Diff of", a, "and", b, "is", a - b) called both of them

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__’

 Now suppose we import the previous calculate module in


another file and call only the add() function.

 Can you guess the output then ?

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 ?

 Whenever we import a module , Python immediately


executes it.

 So as soon as Python found the statement:

import calculate

 It imported the module calculate and executed all the


global statements in it.

 And since our module calculate contained 2 function calls


add(10,20) and subtract(10,20) so the overall output
contains outputs of these calls also
How To Overcome
This Problem ?

 This is where the concept of a special variable called


name comes into picture.

 For every module , Python creates a variable called


name , which contains the name of the module.

 But the point to understand is that:

 When we run a module as a stand alone file then this variable


has the value “ main ”

 Otherwise this variable has the name of the file as it’s value
The Concept Of
name ==‘ main__’

 To understand the concept look carefully at the output of


the code:
demo.py
print("demo.py module name is:", name )

Since we are running


the file demo.py as a
stand alone module
Run: so the variable
python demo.py
name has been
Output: set to the value
demo.py module name is: __main “__main ”
The Concept Of
name ==‘ main__’

 Now consider the code below and it’s output:


demo.py
Now the output is
print("demo.py module name is:", name ) different because we
are importing the
module demo in
another module.
sample.py

import demo As mentioned


previously in this
case the value of the
Run: variable name
python sample.py is the name of the file
Output: so the output is demo
demo.py module name is: demo
The Concept Of
name ==‘ main__’

 Now , we can solve our problem , so that if we run the


module calculate as a stand alone module then both the
functions , add() and subtract() , should run and if we
run it as a part of another module then only that function
should run which we have called.
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 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.2 Does computer really work on 0 and 1

1.3 Hardware

1.4 Files

1.5 Program and process

1.6 Software and their types

1.7 About Operating System

1.8 How a program executes?

1.9 How to develop software in C?

1.10 History of C

1.11 IDE

1.12 Technical Terms

1.13 First C Program

1.14 Understanding Program Structure

1.15 Execution of C Program

1.1 What is a Computer?


Computer is an electronic device that takes input, process it and gives output.
Laptops, Desktop Computers are just one form of computer. Mobile phone, Calculator,
Digital Watch, Digital Camera, Washing Machine etc are also computers as they also work
on the given input. The difference is in their capabilities.
1.2 Does computer really work on 0 and 1?
There is no physical significance of 0 and 1 in computer system. 0 and 1 are just
representation of two states of voltage levels in digital circuits. If there is a supply of high
volt in the circuit it is termed as 1 and for low volt it is 0. Computer understands only the
binary language in forms of 0’s and 1’s. Whatever input we are given it converts to 0’s and
1’s, process the input and results the output in binary which is converted to human readable
form.
These encoding help us to handle any sort of information through digital circuits.
1.3 What is Hardware?
Hardware is a physical device consists of machine, wires, and circuits. In Computer world,
hardware is a comprehensive term for all of the physical parts of a computer, as distinguished
from the data it contains or operates on, and the software that provides instructions for the
hardware to accomplish tasks.
Below are the few common physical parts in a computer:
· Mother Board
· Central Processing Unit(CPU)
· Random Access Memory(RAM)
· Hard Drive
1.4 Files
A collection of data or information that has a name to identify is called a File. A computer
file is a data bundle, created by a program used to refer back to saved work or support the
operations of the program. There are many different types of data files:
· Text File
· Audio File
· Video File
· Program File
· Directory File
File name and extension are separated by a dot operator. File extension tells about type of the
file. For example track1.mp3 is a file with extension mp3 which means it is an audio file.
Among the several file formats, we are concern about a special file format with extension
exe. These files are called executable files.
Software are programs (or a collection of programs) developed by writing instructions (that
need to be executed during execution) in certain programming language.
So the abstract is, you are here to write code in C language which then converted in to an exe
file.

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.

1.9 How to develop software with C language?

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)

1.10 History of C language

· C language was developed by Dennis Ritchie in 1972 at AT & T’s Bell Labs, New Jersy, USA.

· C language is inspired from B language which was developed by Ken Thompson.

· 80% code of UNIX operating system is written in C language.

· C is a middle level language that is a combination of high level and low level language.

· C follows procedure oriented programming approach.

· C follows top down approach.

1.11 IDE

Integrated Development Environment is a software application that provides comprehensive


facilities to computer programmer for software development.

An IDE normally consist of:

· A source code editor

· 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.

1.12 Technical Terms

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.

Syntax: Grammar for computer language

Turbo: Software (IDE) developed by Borland Inc.

Turbo: Software (IDE) developed by Borland Inc.


1.13 First C program
Before begin the actual journey of learning C language, let us have a look on how handsome
our C program is.
/* Program to add two numbers*/
#include<conio.h>
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf(“Enter two numbers\n”);
scanf(“%d %d”,&a,&b);
c=a+b;
printf(“Sum of %d and %d is %d”,a,b,c); // printing the result
getch();
}
1.14 Understanding the Program structure
1) The very first two lines of the program are used to include statements written in
specified files. Statements starts from # symbol are known as pre-processor directives.
Symbol # is followed by command include which tells to include content of specified
files.

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

5) Which of the following is not a job of an operating system


a. Process Management b. Memory Management
c. Compilation of C program d. File Management
6) What is the full form of IDE?
a. Internet Data Editor
b. Integrated Development Environment
c. Internal Data Editor
d. Integrated Development Engine
7) When C language was developed?
a. 1966 b. 1972
c. 1979 d. 1983
8) C is a….. (more than one answer correct)
a. Middle Level Language
b. Procedure Oriented Language
c. Block Structured Programming Language
d. Object Oriented Programming Language
9) Which of the following is not a part of processor
a. ALU b. RAM
c. Registers d. Control Unit
10) What is the job of linker?
a. Compile the source code
b. Execute program
c. Link header files with source code
d. Link object codes and library code
Explore and Answer the following
1) What is the difference between Compiler and Interpreter
2) What is file?
3) Why C is called middle level language?
4) Name any five well know software written in C Language
5) Explain IDE.
Chapter 2: Start Learning C
Content
2.1 Start Learning

2.2 Constituents of C

2.3 Identifiers

2.4 Constant

2.5 Variable

2.6 Keywords

2.7 Instructions and its types

2.8 Data type declaration instruction

2.9 Data type Modifiers

2.10 Input / Output Instruction

2.11 Escape Sequence


2.12 Input Instruction

2.1 Start Learning


As a matter of fact any language whether it is natural language (like Hindi, English, French,
etc) or computer programming language, one has to learn basic constituents first.

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.

The order of our journey contains:

Basic Letters - > Identifiers - >Instructions - >Program


2.2 Constituents of C
Language writing includes letters as:

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.

Constants can be categorized as Primary and secondary constants

2.4.1 Primary Constant:


Primary constants are also known as fundamental constants or basic constants. They are of
three types:
1. Integer constant
2. Real constant
3. Character constant

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.

Rules for constructing variable name:


1. Variable name may contain alphabets, digits or underscore.
2. No other symbol or blank is allowed.
3. A valid variable name never starts with digit.
2.6 Keywords
Keywords are predefined words. They are also known as reserved words. Their meaning is
known to the compiler.
ANSI (American National Standards Institute) announces 32 keywords in C language, but it
may vary with compilers.
Keywords are predefined and we will see their meaning in subsequent chapters.
Here is the list of keywords:

Auto break case char continue const int


Do default enum extern for float register
double else goto long near Return struct
Huge far if sizeof union unsigned while
static short signed

These keywords cannot be used as variable or function names as they already have some meaning
known to compiler.

2.7 Instructions and its types

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.

2.7.1 Types of Instructions:

Data type declaration instruction


Input/Output instruction

Arithmetic instruction

Control instruction

2.8 Data type declaration 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

int, float, char, double, void

Here we are only concern with variable declaration. Declaration of functions will be deal in later
chapter.

Consider the following statements

int x=5, y;

float k=2.34;

char a=’y’, ch;

These are examples of data type declaration instruction. Compiler when read these instructions, it
would get aware of four things:

1) Name of the variables

Here names are x ,y, k, a, ch

2) Size of memory block

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

x contains 5, k contains 2.34 and a contains ‘y’.

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.

2.9 Data type Modifiers


Modifiers are the keywords used to modify the properties of data type.
Modifiers are short, long, signed, unsigned.

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)

Type Size Format Content Range


specifier Type

unsigned char 8 bits %c Character 0 to 255

Char 8 bits %c Character -128 to 127

unsigned int 16 bits %u Integer 0 to 65,535

short int 16 bits %d Integer -32,768 to 32,767

Int 16 bits %d Integer -32,768 to 32,767

unsigned long 32 bits %lu Integer 0 to 4,294,967,295

Long 32 bits %ld Integer -2,147,483,648 to 2,147,483,647

Float 32 bits %f Real 1.1754*(10^-38) to 3.4028* (10^+38)

Double 64 bits %lf Real 2.2250 * (10^-308) to 1.7976 * (10^+308)

long double 80 bits %Lf Real 3.4 * (10^-4932) to 1.1 * (10^4932)


2.10 Input / Output Instruction
2.10.1 Output Instruction
User interaction with a program on machine required input/output device. Here, we
preferably use keyboard as input device and monitor as output device.

printf()

printf() is a pre-defined function used to display messages on monitor. Wherever function


name is used it must be suffixed with ( )

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 1: Save this program as first.c

Step 2: Compile it

Step 3: Run

Your program executes in a flash and you would not able to see its output.

Press ALT + F5 to see output window or modify your program as:

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().

Call to function clrscr() erase content of output screen.

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.

We can write expressions in place of variable list.


main()
{
int a=3,b=56;
clrscr();
printf(“%d %d %d”,a,b, a+b);
getch();
}

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.

Here is the list of escape sequences:

Escape Name Meaning


Sequence
\a Alert Produces an audible or visible alert.
\b Backspace Moves the cursor back one position (non-destructive).

\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).

Consider the following program

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

Explore and Answer the following:


1) Write a program to print \n on the screen.
2) Write a program to print %d on the screen
3) Write a program to print “SCA”
4) Differentiate between getch() and getche()
5) Write a program to input a character from keyboard and display that character. Use
getch() in place of scanf().
6) Write a program to print your name at the centre of the screen
7) Write a program to check whether the action statement can be written before
declaration statement.
Chapter 3: Arithmetic Instruction

Content
3.1 Arithmetic Instruction

3.2 Unary Operators


3.3 Arithmetic Operators
3.4 Bitwise Operators
3.5 Relational Operators
3.6 Logical Operators
3.7 Conditional Operators

3.8 Assignment Operators

3.1 Arithmetic Instruction


Arithmetic instruction is used to manipulate data using operators

Here is the list of operators

Operator Description Associativity


() Parentheses (grouping) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer

++ -- Prefix, Postfix increment/decrement right-to-left


+- Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (change type)
* Dereference
& Address
sizeof Determine size in bytes
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

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

x=sizeof(23.67); // sizeof returns 8 and assigned to x


x=sizeof(‘a’); // 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.

Regular ASCII Chart (0 to 127)

Extended ASCII Chart (128 to 255)


3.3 Arithmetic Operators (+,-,*,/,%)
+,- and * operators are same as they are in mathematics. + is used to add two numbers, - is
used tosubtract two numbers and * is used to multiply two numbers.

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 (%)

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.

Precedence of *, / and % is same but higher than + and -.


Precedence of + and – is same.
Associativity rule for arithmetic operators is left to right.

3.4 Bitwise operator ( &,|,^,~,>>,<<)


Bitwise operators work on binary numbers that is bits. You should know how to convert a
number from decimal to binary and from binary to decimal.

Nature of operators

Bitwise AND (&)


0&0 is 0
0&1 is 0
1&0 is 0
1&1 is 1

Bitwise OR ( | )
0|0 is 0
0|1 is 1
1|0 is 1
1|1 is 1

Bitwise XOR (^)


0^0 is 0
0^1 is 1
1^0 is 1
1^1 is 0
Bitwise NOT (~)
~0 is 1
~1 is 0

main()
{
int x;
x=5&12;
printf(“%d”,x);
}

Output is:
4

Bitwise AND applies on 5 and 12. We need to convert them in binary.


5 =00000000 00000101
12=00000000 00001100
& ————————————
4=00000000 00000100

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

3.5 Relational Operators (<, >, <=, >=, ==. !=)


Relational operators are always evaluated as true or false. True is 1 and false is 0.
main()
{
int x;
x=5<3;
printf(“%d”,x);
}

Output is:
0
As the relation 5<3 is false, x will contain 0 as a result of relational operator.

Priority of <, >, <=, >= is higher than


== and !=
Associativity is left to right.
3.6 Logical Operators ( &&, ||, ! )
Logical operators (&& and ||) are used to combined two expressions.
They work as:

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.

3.8 Assignment operators (=, +=, -=, *=, /=, %=)


Assignment operators are used to assign values to variable

main()
{
int x;
x=4;
}

In the above code we used assignment operator to store 4 in x.

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.

Other operators -=, /= and %= are works in a similar fashion.


Check Yourself
Objective Questions
1) Which of the following is not a unary operator?
a. ! b. ++
c. sizeof() d. %
2) Operator with highest precedence is
a. > b. ?:
c. == d. & (bit wise)
3) Find the output of the following program
main()
{
int x=257;
x=x/100 +x/10%10+x%10;
printf(“%d”,x);
}
a. 0 b. 14
c. 2 d. None of the above
4) Find the output of the following program
main()
{
int a;
a=31&14+5*sizeof(6.4);
printf(“%d”,a);
}
a. 22 b. 54
c. 34 d. 0
5) Find the output of the following program
main()
{
int a;
a=5>4>3;
printf(“%d”,a);
}
a. 0 b. 1
c. 5 d. 3
6) Find the output of the following program
main()
{
int x=3,y;
y=++x*++x*++x;
printf(“x=%d y=%d”,x,y);
}
a. x=5 y=60 b. x=6 y=216
c. x=5 y=125 d. x=6 y=120
7) Find the output of the following program
main()
{
int x=3,y;
y=3 + sizeof 4*x+5;
printf(“x=%d y=%d”,x,y);
}
a. x=3 y=5 b. x=3 y=14
c. x=3 y=10 d. x=3 y=2
8) int a=10, b ;
b=a++ + ++a;
printf (“%d,%d,%d,%d”,b,a++,a,++a);
What will be the output of the above code when executed?
a. 12,10,11,13 b. 22,10,11,13
c. 22,11,11,11 d. 22,13,13,13
9) What is the output of the following program?
void main()
{
int c=08;
printf(“%d”,c);
}
a. 8 b. 0
c. Compile time error d. 10
10) The statement printf(“%c”, 100); will print?
a. prints 100 b. print garbage
c. prints ASCII equivalent of 100 d. None of the above
Write following programs
1) Write a program to swap two numbers.
2) Write a program to display last digit of a number. Number is entered through
keyboard.
3) Write a program to calculate sum of the digits of three digit number.
4) Write a program to calculate square of a number
5) Write a program to print profit and profit percentage. Selling price and cost price is
given by user.
Explore and Answer the following
1) Write a program to swap two numbers without using third variable.
2) Write a program to swap two numbers without using third variable and arithmetic
operators.
3) Can we calculate the sizeof void?
4) What should be the result of 3.5%2 ?
5) What should be the result stored in variable x after execution of the statement x=~21
a. x*=3+4;
b. x=x*3+4
Chapter 4: Control Instruction

Content:
4.1 Control Instruction
4.2 Decision Control Instruction
4.3 If
4.4 if-else
4.5 Conditional operator

4.6 Nested if else


4.7 else if ladder

4.1 Control Instruction


Program is a set of instructions. We know that each instruction of the program is executed by
processor. Processor executes instructions one by one. Whatever we write in our program
will be executed in the same order as they appear in the program. So we can say processor
executes instructions in a sequential manner. At a particular instant processor is executing
some line of code, we say control of processor is on that line. Processor’s control moves from
one line to another. We say this movement of processor control goes in sequence
Types of control instruction
⚫ Decision control instruction
⚫ Iterative control instruction
⚫ Switch case control instruction
⚫ goto instruction
4.2 Decision control instruction
Decision control instruction is also known as selection control instruction. As the name implies the
job is selection control instruction is to select a set of code for execution on the basis of some
condition.
We can implement decision control instruction in three ways:
⚫ if
⚫ if-else
⚫ conditional operator (Ternary Operator)
4.3 if
Syntax:
main()
{
..…
…..
if(some condition)
{
Statement1;
Statement2;
….
}

}

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:

Program to find greater among three numbers:


main()
{
int a,b,c;
printf(“Enter three numbers: “);
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if( a>c)
printf(“%d is greater”,a);
else
printf(“%d is greater”,c);
}
else
{
if( b>c)
printf(“%d is greater”,b);
else
printf(“%d is greater”,c);
}}

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

10) Find the output of the following program


main()
{
int a=210,b=120,c;
c=a>b?1,2,3:2,5,6,7;
printf(“%d”,c);
}
a. 1 b. 3
c. 2 d. Error
Write following programs:
1) Write a program to find greater between two numbers.
2) Write a program to check whether a given number is divisible by 5 or not.
3) Write a program to check whether a given number is even or odd.
4) Write a program to check whether a given number is positive or non positive.
5) Write a program to check whether a given number is positive negative or zero.
6) Write a program to find the greatest among 3 numbers.
7) Write a program to find greatest among 3 numbers (use ternary operator)
8) Write a program to check whether a given character is digit, uppercase alphabet,
lower case alphabet or any other character
9) Write a program that takes marks of five subjects from user. Display result as PASS
or FAIL. If candidate is passed then print its percentage and division.
10) Write a program check whether a given year is a leap year or non leap year.
Explore and Answer the following:
1) Write a program to print your name without using semicolon (;).
2) Write a program to check whether a given number is even or odd without using
modulo (%) operator.
Chapter 5: Iterative Control Instruction

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

5.7 The keyword continue


5.8 Switch case control Instruction
5.9 Menu driven Programming
5.10 Goto control Instruction

5.1 Iterative Control Instruction


Iterative control instruction is also known as repetitive control instruction or loop.
Sometimes it is desirable to executed same statement again and again. This can be done with
the help of loops

There are three ways to implement loops in C language:


⚫ while
⚫ do-while
⚫ for

5.2 while loop:


Syntax of while
main()
{
….
….
while(condition)
{
….
….
}

}
Syntax of while is similar to if. In the case of if, when the condition is TRUE control moves
inside if block and execute statements of if-block. After executing if-block control moves to
the statement written immediately after if-block (outside if-block).
In the case of while, when the condition is TRUE control moves inside while-block and
execute statements of while-block. After executing while-block control does not moves to
the statement written immediately after while-block rather it goes back to the condition of
while block. This condition will be checked again and if it is again TRUE control moves
again inside while-block. This repeats till the condition becomes FALSE. while loop executes
the set of statements until the condition is true or non zero value. Condition can be any valid
expression also.

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.

5.3 do-while loop:


Syntax of do-while 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.

for(initialization, condition, increment)


{
……
……
}

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.

Example: Program to calculate factorial of a number


main()
{
int n,i,f=1;
printf(“Enter a number “);
scanf(“%d”,&n);

for(i=1 ; i<=n ; i++)


{
f = f * i;
}
printf(“Factorial is %d”, f);
}

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

break in loop body


The keyword break is used in loop body to terminate loop. When break executes, it transfers
the control out of loop body without checking any loop condition.
Whenever you are not sure with when the loop should stop, you can use break to terminate
loop.
Example:
main()

int x,i=1;

while(i<=5)

printf(“Enter an even number”);

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.

5.8 switch case control Instruction


We studied earlier in decision control that how and when to use if, if-else.

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;

while(1) // condition is always true, thus an infinite


loop
{
clrscr();
printf(“\n1. Addition”);
printf(“\n2. Subtraction”);
printf(“\n3. Multiplication”);
printf(“\n4. Division”);
printf(“\n5. Exit”);
printf(“\n\nEnter your choice”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
result=a+b;
printf(“Sum is %d”, result);
break; //it is used to move control out of switch
body
case 2:
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
result=a-b;
printf(“Difference is %d”, result);
break; //it is used to move control out of switch
body
case 3:
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
result=a*b;
printf(“Product is %d”, result);
break; //it is used to move control out of switch
body
case 4:
printf(“Enter two numbers”);
scanf(“%d%d”,&a,&b);
result=a/b;
printf(“Quotient is %d”, result);

break; //it is used to move control out of switch body


case 5:
exit(0);
default:
printf(“Invalid Entry”);
}
getch();
}
}
Explanation:
There are few things to discuss about above program.
1) Notice while loop which executes infinite times till you select 5 from the menu.
2) In case 5, we use a predefined function exit. The job of this function is to terminate
program. Argument 0 in the function depicts the normal termination. Argument could
be 1 passed in the function in the case of abnormal termination.
3) The keyword break is used in each case as it transfers the control outside switch body.
4) Whenever wrong selection from menu (other than value from 1 to 5) switch moves
the control to default segment.
5) No need to put keyword break after default statements as it is already at the end of
switch body.

Rest you can understand the flow of program by executing it.


5.10 goto controlInstruction
The goto statement is used for unconditional jump from one part of the program to another
part of the program. It is always suggested not to use goto statement as this reduces the
readability of the program. Use of goto statement is considered as poor programming
approach.

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.

More points about goto


1) goto can move control in forward as well as backward in the program.
2) goto works only within the same function body.
3) Labels are names but no need to declare them as variables.

Check Yourself:

Objective Questions

1) What is the output of the following code?


main()
{
int a=0,k=1;
while(a<10)
{
k++;
a++;
}
printf(“%d %d”,a,k);
}
a. 9 10 b. 10 10
c. 10 11 d. 99
2) What is the output of the following program?
main()
{
int a=0,k=10;
while(a<k)
{
k=k-a;
a++;
}
printf(“%d %d”,a,k);
}
a. 3 7 b. 44
c. 9 10 d. 4 10
3) Find the output of the following program
main()
{
int k=1,x=3,y=4,a;
for(a=y;a>0;a—)
{
k=k*x;
}
printf(“%d”,k);
}
a. 81 b. 729
c. 27 d. 0
4) Find the output of the following program
main()
{
int a,b=5,count=0;
for(a=4;a>0;a—)
{
for( ;b<10;b++)
if((a+b)%2==0)
count++;
}
printf(“%d”,count);
}
a. Error b. 2
c. 8 d. 5
5) Find the output of the following program
main()
{
int a=0,k=10;
while(1)
{
k=k+a; a=k-a; k=k-a;
if(a<k) break;
else a++; k-=2;
}
printf(“%d %d”,a,k);
}
a. -2 11 b. 44
c. 0 11 d. 2 11
6) Find the output of the following program
main()
{
int a=0;
while(a<10)
{
if(a%3==0) {a++; continue;}
if(a%4!=0) {a+=2; }
if(a%5!=0) { a++; break;}
}
printf(“%d”,a);
}
a. 0 b. 2
c. 4 d. 5

7) Find the output of the following program


main()
{
int a=3;
switch(a)
{ case 1: printf(“Hello”);
case 2: printf(“Hilo”);
case 3: printf(“Mat Hilo”);
default: printf(“Khub Hilo”);
}
}
a. Mat Hilo b. Mat Hilo Khub Hilo
c. Khub Hilo d. Error

8) Find the output of the following program


main()
{
int a=2;
switch(a)
{ case 1: printf(“Hello”); break;
case 2: printf(“Hilo”); continue;
case 3: printf(“Mat hilo”); break;
default: printf(“Khub Hilo”);
}
}
a. Blank Screen b. Mat Hilo
c. Khub Hilo d. Error

9) Find the output of the following program


main()
{
int a=2;
while(a>=-5 && a<=5) {
switch(a)
{ case -1: a+=2;
case 2: a-=3; break;
case 3: a+=4; break;
default: a-=5;
}
printf(“%d “,a); }
}
a. -1 2 -7 b. -1 -2 -7
c. 1 -2 -7 d. None of these

10) Find the output of the following program


main()
{
int a;
for(a=2;a<=10;a++) {
switch(a%3)
{ case 0: a+=2;
case 1: a-=3; break;
case 2: a+=4; break;
default: a-=5;
}
printf(“%d “,a); }
}
a. 6 4 9 7 12 b. 6497
c. 6 4 9 7 10 d. Error

Write the following programs


1) Write a program to print first 10 natural numbers.
2) Write a program to print first 10 natural numbers in reverse order.
3) Write a program to print first 10 odd natural numbers
4) Write a program to print first 10 even natural numbers
5) Write a program to print first N natural numbers. Value of N is given by user.
6) Write a program to print first N odd natural numbers in reverse order. Value of N is
given by user.
7) Write a program to calculate sum of first N natural numbers. Value of N is given by
user.
8) Write a program to calculate product of first N natural numbers. Value of N is given
by user.
9) Write a program to calculate factorial of a number.
10) Write a program to calculate xy. Values of x and y are given by user.
11) Write a program to count number of digits in a given number.
12) Write a program to calculate sum of the digits of a given number.
13) Write a program to reverse a number.
14) Write a program to check whether the two given numbers are reverse of each other or
not.
15) Write a program to check whether a given number is Prime or not.
16) Write a program to print all prime numbers between two given numbers.
17) Write a program to print all prime numbers in first 1000 natural numbers.
18) Write a program to find LCM of two numbers.
19) Write a program to find HCF of two numbers.
20) Write a program to print N numbers of Fibonacci series. Value of N is given by user.
21) Write a menu driven program for addition, subtraction, multiplication and division
(Hint: use switch case)

Explore and Answer the following


1) Write a program to print all prime factors of a given number.
2) Write a program to move your name with arrow keys
3) Write a program to move your name horizontally until user presses any key.
4) Write a program to print all ASCII characters and corresponding ASCII codes.
5) Write a menu driven program to display user’s name in selected colour. Following
colours should be in the choice list: RED, GREEN, BLUE, YELLOW. Repeat the
menu till he choose exit from the choice list.
Chapter 6: Functions and Storage Classes

Content
6.1 Functions

6.2 Modularization

6.3 Technical Terms

6.4 Function Types

6.5 Defining Function

6.6 Recursion

6.7 Storage Classes

6.8 Automatic Storage Class

6.9 Register Storage Class

6.10 Static Storage Class

6.11 External Storage Class

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.

Step Required To Develop A Function:


To develop a User Defined Function we need following steps.
1. Function prototype/Function declaration
It is the first step of designing a function to tell the compiler that what is our function
name and what will be it return type and what type of values it will take.

Syntax of function declaration :


<return type> <function name>(<list of arguments>);

Components of function declaration:


1.Return type : A function can return a value to the place from its being called using return
keyword.
2. Function Name: We must give a proper name to a function and remember that it should not
be any reserve keyword of c nor any standard function.
3. Function parameters/Function arguments: the values which we pass inside a fuction to
operate on it.

Eg. float average(int,int,int)


2. Declaration of some standard functions:
3. void clrscr();
4. double sqrt(double);
5. int strcmp(char[],char[]);
6. double pow(double,double);
7. Using Delay()/sleep(): declared in <dosh.h>

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:

On the basis of return type and parameters function has 4 types.

1.Take something, Return Something.


pow(),sqrt(),strlen(),strcmp() etc.

2. .Take something, Return nothing.


fflish(),delay().sleep(),textcolor(),gotoxy()

#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();
}

3. Take nothing, Return something.


getch();

4. Take nothing ,Return nothing.


clrscr();

User Define Function Example:


Function take something and return something
#include<stdio.h>
#include<conio.h>
int sum(int,int) /*int,int are signature in prototype declaration*/
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 call
printf("sum of x and y is=%d",n)
getch();
}
/*function definition*/
int sum(int p,int q)//p and q are formal parameters. Values of actual args are copied to formal
args.
{
return(p+q);
}

Exaple of funtion take something but return nothing

#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);
}

Exaple of funtion take nothing but return something

#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);
}

Exaple of funtion take noththing and return nothing

#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

6.5 Defining function


There are four ways to define a function:
1) Takes nothing return nothing
2) Takes something returns nothing
3) Takes nothing returns something
4) Takes something and returns something

1) Takes nothing returns nothing


main()
{
void sum(void);
clrscr();
sum();
getch();
}
void sum()
{
int a,b,c;
printf(“Enter two numbers:-”);
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“Sum is %d”,c);
}

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();
}

int sum(int x,int y)


{
int c;
c=x+y;
return(c);
}

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.

At last x would contain 5


6.7 Storage Classes
Data type declaration instruction depicts following characteristics of a variable:
1) Name of the variable
2) Size of memory block
3) Type of the content that it can store

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

Following are the four storage classes:


1) Automatic Storage Class
2) Register Storage Class
3) Static Storage Class
4) External Storage Class

6.8 Automatic Storage class


⚫ Keyword used is auto
⚫ Storage in main memory (RAM)
⚫ 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

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;

printf (“%d”, ++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

10) Find the output of the following program


#include<stdio.h>
main()
{
extern int a;
a=3;
printf(“%d “,++a); }
}
a. 3 b. 4
c. 0 d. Error

Write following programs


1) Write a function to calculate area of circle. (Take something, return something)
2) Write a function to calculate factorial of a number. (Take Something, Return
Something)
3) Write a function to calculate LCM of two numbers. (Take Something, Return
Something)
4) Write a function isPrime() to check if a number is prime or not. Function should take
an integer as an argument and should return 1 if the number is prime, otherwise return
0.
5) Write a recursive function to calculate sum of N natural numbers. (Take something
return something)
6) Write a function to find greatest among three numbers. (Take something return
something)
7) Write a recursive function to calculate sum of squares of first N natural numbers.
(Take something return something)
8) Write a recursive function to calculate sum of cubes of first N natural numbers. (Take
something return something)
9) Write a recursive function Fibo to print n numbers of Fibonacci series. (Take
something return nothing)

Explore and Answer the following


1) Write a program to display n rows Pascal triangle. The value of n is given by user. To
accomplish the task define functions fact() to calculate factorial, combi() to calculate
combination.
2) Write a recursive function to calculate greatest common divisor of two numbers
3) Write a program to run dos command. Demonstrate few of the dos commands.
4) Write a program to change your text color. Use predefined functions to change color
of the text.
5) Write a program to play a number guessing game with three chances given to user,
give hint on each chance as whether the secret number is greater or smaller from the
guessed number. Secret number should be any number from 1 to 25.
6) Write a program to calculate sum of N natural numbers without using loop.
7) Explore the use of functions: delay(), kbhit(), gotoxy(), sound(), nosound(), rand(),
randomize()
8) Write a program to print system date and time
9) Write a menu driven program to demonstrate the use of functions from math library
such as, sqrt, pow, sin, log, exp, abs, etc
10) Write a program to implement Tower of Hanoi
Chapter 7: Array

Content
7.1 Arrays
7.2 Array Declaration
7.3 Initializing Arrays
7.4 Memory allocation in an array

7.5 Two dimensional and Multi-dimensional Arrays

7.6 Initialization of two dimensional 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 roll[10]/*roll is an array of 10 integers


char grade[5]/*grade is array of 5 characters
float per[15]/* per is array of 15 float values structure of an array in memory
int arr[5];
i int takes 2 bytes and size of array is 5 means total 5*2=10 , bytes will be reserved in
memory for arrray. also array elements are indexed in memory and this index starts from 0 to
array size-1

Addres in memory Arr elements Index no


1000 3 0 arr[0]
1002 4 1 arr[1]
1004 8 2 arr[2]
1006 9 3 arr[3]
1008 22 4 arr[4]

7.3 Initializing Arrays


• int a[5]={34,56,78,99,12};

• 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]);

printf(“Enter 9 numbers for second matrix\n”);


for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&b[i][j]);

for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];

printf(“\nSum of matrix is: \n”);


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(“%d “,c[i][j]);
printf(“\n”);
}
getch();
}

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

7.6 Initialization of two dimensional Array


int b[2] [3] = {12,65,78,45,33,21};
int b[ ] [3] = {12,65,78,45,33,21};
int b[2] [ ] = {12,65,78,45,33,21};
int b[ ] [ ] = {12,65,78,45,33,21};

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

2) What is the output of the following program?


#include<stdio.h>
main()
{
int a[ ]={1,2,3};
printf(“%d %d”, a[0],1[a]);
}
a. 1 2 b. 11
c. Error d. 21
3) Find the output of the following program
#include<stdio.h>
main()
{
int k,x,y,a[ ]={21,2,13};
for(x=0;x<2;x++)
for(y=x+1;y<3;y++)
if(a[x]>a[y])
{ k=a[x]; a[x]=a[y]; a[y]=k; }
printf(“%d%d%d”, a[0],a[1],a[2]);
}
a. 21 2 13 b. 2 21 13
c. 13 2 21 d. 2 13 21
4) Find the output of the following program
#include<stdio.h>
main()
{
int x,y=0,a[ ]={11,34,21,2,13};
for(x=0;x<5;x++)
if(y<a[x])
y=a[x];
printf(“%d”, y);
}
a. 34 b. 43
c. 2 d. 21
5) What will happen if in a C program you assign a value to an array element whose
subscript exceeds the size of array?
a. The element will be set to 0
b. The compiler would report an error.
c. The array size would appropriately grow
d. The program may crash if some important data gets overwriten.
6) Find the output of the following program
#include<stdio.h>
main()
{
int x[4];
printf(“%d %d”,sizeof(x), sizeof(x[0]));
}
a. 8 2 b. 22
c. 8 8 d. Error
7) Which is the correct declaration of two dimension array
a. int a[3][ ]={2,3,4,6,7,8,9}; b. int a[ ][ ]= {2,3,4,6,7,8,9};
c. int a[ ][4]= {2,3,4,6,7,8,9}; d. All are correct
8) Consider the following declaration
int a[3][4][5]={22,34,5,6,1,0,55,4};
Which of the following statement is incorrect?
a. Total memory occupied by array is 120 bytes
b. There are 3 two dimensional arrays, each is an array of 4 arrays of 5 int
blocks.
c. Value of a[0][1][2] is 0
d. Value of a[0][1][1] is 55

Write following programs


1) Write a program to find greatest among 10 integers. Use array to store integers.
2) Write a program to find smallest among 20 integers. Use array to store integers.
3) Write a program which takes 10 numbers from user; store them in one dimension
array. Display the sum of all even numbers. Also display the sum of all odd numbers
4) Write a program to sort an array of 10 integers. Use bubble sort.
5) Write a program to sort an array of 10 integers. Use selection sort.
6) Write a program to calculate value of a determinant of third order.
7) Write a program to add two matrices of order 3x3 each.
8) Write a program to multiply matrices of order 3x3.
9) Write a program to calculate inverse of matrix of order 3x3.
10) Write a menu driven program to demonstrate working of QUEUE. Define insert(),
delete() and View() functions to implement basic functionalities of QUEUE.

Explore and Answer the following


1) Write a menu driven program to demonstrate working of STACK. Define Push(),
Pop() and View() functions to implement basic functionalities of STACK
2) Write a program to generate magic square.
3) Write a program to implement quick sort

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

8.5 Two dimensional char arrays


8.1 Strings and Null character
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character ‘\0’
The following declaration and initialization create a string consisting of the word
“Bhopal”. To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word “Bhopal”
• char city[7]={‘B’,’h’,’o’,’p’,’a’,’l’,’\0’};

Another way to initialize a string in an array is as follows:


• char city[7]=”Bhopal”;

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.

8.2 About format specifier %s


Example:
main()
{
char text[6] = “Hello”;
printf(“%s”,&text[0]);
}
Explanation:
Here is another program depicting the use of format specifier %s.
This is used only for strings.
Observe that in printf we write &text[0] and not text[0]. This means with %s format specifier,
one should always use address of first block of array.
You can write text in place of &text[0], both have the same meaning. The name of the array
always represents address of the very first block of an array, so text is same as &text[0].
8.3 User Input
main()
{
char text[20];
printf(“Enter your name”);
scanf(“%s”,&text[0]);
printf(“hi, %s”,&text[0]);
}
Explanation:
In this program, user can input his name as we used scanf().
Notice %s is used in scanf for string input. Again remember, if you are using %s in printf
or scanf always pass address of the first block of array.
Run this code to understand the limitations of scanf().
If you input Amir, it will get stored in the array and null character is automatically
appended by compiler.
If you input Amir Khan, only the first word of the input string will be stored in character
array and nul is automatically appended.
Scanf() is not capable to input multiword string. The solution to this problem is a function
gets()
Example:
main()
{
char text[20];
printf(“Enter your name”);
gets(&text[0]);
printf(“hi, %s”,&text[0]); //or puts(&text[0]);
}
Explanation:
No need to mention format specifier in function gets() as it is dedicated only for string input.
The function gets() is declared in stdio.h header file.
Function gets() can input only one string at a time.
As gets() can be used for input, function puts() can be used for output in place of printf().
The function printf can print multiple strings in a single statement; on the other hand the
function puts can only output single string at a time.

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);
}

2) Function name: strrev()


Usage:
main()
{
char str[20];
printf(“Enter a string”);
gets(str);
printf(“You entered %s”,str);
strrev(str);
printf(“Reverse is %s”, str);
}

3) Function name: strlwr()


Usage:
main()
{
char str[20];
printf(“Enter a string”);
gets(str); //sample input is SCA
strlwr(str);
printf(“String in lower case is %s”,str); //sample
output is sca
}

4) Function name: strupr()


Usage:
main()
{
char str[20];
printf(“Enter a string”);
gets(str); //sample input is sca
strupr(str);
printf(“String in upper case is %s”,str); //sample
//output is SCA
}

5) Function name: strcpy()


Usage:
main()
{
char str1[20], str2[20];
printf(“Enter a string”);
gets(str1); //sample input is Computer
strcpy(str2,str1);
printf(“String1=%s and String2 = %s”,str1,str2);
}
Output:
String1=Computer and String2=Computer

6) Function name: strcat()


Usage:
main()
{
char str1[20], str2[40];
printf(“Enter two strings”);
gets(str1); //sample input is Computer
gets(str2); //sample input is Education
strcat(str2,str1);
printf(“String1=%s and String2 = %s”,str1,str2);
}
Output:
String1=Computer and String2=ComputerEducation

7) Function name: strcmp()


Usage:
main()
{
int r;
char str1[20], str2[20], str3[20];
printf(“Enter three strings”);
gets(str1); //sample input is Hello
gets(str2); //sample input is Hello
gets(str3); //sample input is hello
r=strcmp(str2,str1);
printf(“%d”,r); //output is 0
r=strcmp(str1,str3);
printf(“%d”,r); //Output is -32
}
8.5 Two Dimension character array
This is similar to two dimension array that we studied in previous chapter.
main()
{
int i;
char str[5][10];
printf(“Enter 5 strings”);

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

Write following programs:


1) Write a program to count the occurrence of a character in a given string. String and
character is taken from user.
2) Write a program to find number of vowels in a given string.
3) Write a program to count number of words in a given string
4) Write a program to check whether a given string is palindrome or not.
5) Write a program to calculate length of string.(with and without strlen())
6) Write a program to reverse a string. (with and with and without strlen()).
7) Write a program to convert string into lower case (with and without strlwr())
8) Write a program to convert string into upper case (with and without strupr()).
9) Write a program to copy a string into another char array ( with and without strcpy()).
10) Write a program to concatenate a string to another string (with and without strcat())
11) Write a program to compare two strings (with and without strcmp()).
12) Write a program to perform case insensitive comparison of two strings.
13) Write a program that takes 5 strings from user, store them in two dimension char
array, now find the number of occurrence a specific character (entered by user) in 5
entered strings

Explore and Answer the following:


1) Write a program to search a pattern in a given string.
2) Write a program that takes 5 strings from user, store them in two dimension char
array, now display them in dictionary order
3) Write a program to abbreviate the name of a person. Example Rohit Kumar Bhargav
should become R. K. Bhargav
4) Write a program to convert digits of a number into words. [For example 234 should
becomes Two Four Three]

Chapter 9: Pointers

Content
9.1 Pointers

9.2 Address of operator


9.3 Indirection operator
9.4 Declaration of pointer
9.5 Size of pointer
9.6 Concept of base address
9.7 void pointer
9.8 Extended Concept of pointers

9.9 Pointers Jargon


9.10 Pointers arithmetic
9.11 Application of pointers
9.12 Call by reference
9.13 Pointer and Arrays
9.14 Pointers and strings

9.15 Array of pointers


9.16 Dangling Pointers

9.17 Const pointer and pointer to const

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.

Consider the following statement

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:

• Addresses are always in the range 0 to 65535.


• Every byte will have some address number
• Address number is always an integer, even if the variable is not of type int.
• We cannot decide address number of any variable.
• Addresses are also known as references.

9.2 Address of Operator (&)

You are already use to of address of operator as you have been using it in scanf()
function. Now let us examine its characteristics:

• & is called address of operator, also known as referencing operator.


• It is a unary operator, thus requires only one operand.
• Operand must be a variable.
• & returns the reference number of variable specified as the operand.

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.

9.3 Indirection Operator (*)

Another important operator is indirection operator (*).

• Indirection operator is also known as ‘value at’ operator or ‘dereferencing


operator’.
• It is also a unary operator that is single operand is needed.
• Operand must be a variable address.
• It gives a representation to the block whose address is specified in the operand.

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.

Important point to note:

We cannot assign anything to block by just writing address to the left of assignment
operator.

&x=25; //Error

&x is not a variable. It is a way to represent address of variable x.


&x in itself is a constant and we cannot assign anything to constant.

9.4 Declaration of Pointers

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

j =&x; // Valid statement

This is the correct way as variable is in the left side of assignment operator.

Here j is a special variable, it contains address of another variable, it must be declared in


a special way.

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

9.5 Size of pointer

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.

An important point to understand

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.

We can call such pointer as float pointer.

9.6 Concept of Base Address

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.

Consider the following declarations:

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.

9.7 void Pointer

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));
}

9.8 Extended Concept of Pointers

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

Consider the following example

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:

6048 6048 6048

3276 3276 5140

333
9.9 Pointer jargons

int i; // i is an int

int *j; // j is a pointer to an int

int **k; // k is a pointer to a pointer to an int

9.10 Pointers Arithmetic

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.

Rule 1: Take care for the compatibility

Example

main()
{
int i=3;
char *j;
j = &i; //Error as incompatible assignment
printf(“%d %u”, i, &i);
}

Error: cannot convert ‘int*’ to ‘char*’

(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);
}

Error: cannot convert ‘long*’ to ‘int*’

Example

main()
{
int k, i=3, *j;
j = &i;
k = j; //Error as incompatible assignment
printf(“%u”, k);
}

Error: cannot convert ‘int*’ to ‘int’

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.

Rule 2: We cannot add two addresses.

Example

main()
{
int *k, i=3, *j;
j = &i;
k = j + j;
printf(“%d”, k);
}
Error: Invalid pointer addition.

Similarly, we cannot multiply, divide two addresses.

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.

9.11 Application of pointers

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.

9.12 Call by reference

When a function is called by passing addresses of variables, it is known as call by


reference.

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:

Enter two numbers

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*);

9.13 Pointers and Arrays

Remember two things about pointers and arrays:

1) Whatever is the size of an array it always stored in contiguous memory locations.


2) When pointer is incremented it always points to immediately next location of its type.

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().

Handling two dimensional array via pointers

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

The following example illustrates the first way.

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

Second way is to create a pointer to an 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

Expression Meaning Expression Meaning


P 1000 *(*(p+0)+0) 3
p+1 1006 *(*(p+0)+1) 5
*(p+0) 1000 *(*(p+0)+2) 1
*(p+1) 1006 *(*(p+1)+0) 6
*(p+0)+1 1002 *(*(p+1)+1) 7
*(p+0)+2 1004 *(*(p+1)+2) 8
*(p+1)+0 1006 *p 1000
*(p+1)+1 1008 **p 3
*(p+1)+2 1010

9.14 Pointers and Strings

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.

Example:Define a function to calculate length of string

int stringlength(char *p)


{
int i=0;
while(*(p+i)!=’\0’)
i++;
return(i);
}

9.15 Array of pointers

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.

9.16 Dangling pointer


A pointer becomes dangling when memory of the block is released whose address is still reside in
pointer. It is much like wild pointer. The only difference in wild pointer and dangling pointer is, wild
pointers are un-initialized pointers thus containing invalid address. Wild pointer points to unknown
location which can be dangerous from programming point of view.

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

9.17 Const pointer and pointer to a const

Const pointer is a pointer whose value cannot be altered.

Pointer to a const is a pointer that stores an address of const variable thus we cannot modify
variable data using pointer.

Declaration of pointer to a const:

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:

*p=6; //error: cannot modify const variable


p++; //valid:

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

const int x=4;


int *p;
p=&x;
x++; //error: cannot modify const variable
*p=3; //undefined behavior, should be an error
p++; //valid

Example for const pointer

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

3) Find the output of the following program


#include<stdio.h>
main()
{
char str[ ] =”Hello”;
char *const p = str;
*p=’M’;
printf(“%s”,str);
}
a. Mello b. Hello
c. Error d. MHello

4) Find the output of the following program


#include<stdio.h>
main()
{
static char *s[ ]={ “black”, “white”, “pink”, “violet”};
char **ptr[ ] = { s+3, s+2, s+1, s }, ***p;
p=ptr;
++p;
printf(“%s”, **p+1);
}
a. ink b. ack
c. ite d. let
5) Point out the error in the following code
#include<stdio.h>
main ()
{
int a[ ] = {10, 20, 30, 40, 50 };
int j;
for( j=0; j < 5; j++)
{
printf(“%d “,a);
a++;
}
}
a. 10 20 30 40 50 b. 20 30 40 50
c. Error: LValue required d. 50 40 30 20 10

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)

7) Find the output of the following program


#include<stdio.h>
main()
{
int a=10,b-20;
int * (*fp)(int*,int);
fp=fun;
printf(“ %d %d”, *fp(&a,b),a);
}
int* fun(int *p,int q)
{
*p=*p+q;
q=*p-q;
*p=*p-q;
return(p);
}
a. 10 10 b. 20 10
c. 20 20 d. 10 20

8) Find the output of the following program


#include<stdio.h>
main( )
{
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
printf( “\n%u %u %u”,a[0]+1,*(a[0]+1),*(*(a+0)+1));
} //Assume address of a[0][0] is 1000
a. 1008 1008 1 b. 1008 1008 2
c. 1006 2 2 d. 1006 1006 1
9) Find the output of the following program
#include<stdio.h>
main()
{
char *p=””;
char s[]=””;
printf(“%d %d”,sizeof(p),sizeof(s));
}
a. 21 b. 22
c. 12 d. 11

10) Find the output of the the following program


int * fun(int*,int);
main()
{
int a=10,b=20;
printf(“%d %d”, *fun(&a,b), a);
}
int fun(int *p, int q)
{
*p=*p+q;
q= *p-q;
*p=*p-q;
return(p);
}
a. 10 20 b. 20 10
c. 20 20 d. 10 10

Write following programs


1) Write a program to print address of variable.
2) Write a program to perform input output operations on a variable and should be
handled only by pointer.
3) Write a program to swap content of two variables. Variables should be created in
main() and should be swapped by function swap(). (hint: Use call by reference)
4) Write a function to calculate area and circumference of a circle but results should be
printed in main() function
5) Define functions input(), display() and sort() for the following program:

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.

Explore and Answer the following


1) Write a program to sort a two dimensional array with a pointer to array
2) Write a program in which a pointer to array is used to handle a two dimensional
array(4x4) containing all zeros except any one block which contains 1. Display values
of array in row column fashion. Allow user to move this 1 in the matrix with arrow
keys.
3) Write a function to convert a string to a number without using predefined function.
4) Write a program to print all permutations of a given string
Chapter 10: Structure and DMA

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.12 Program to input any length string

10.1 Structure

Structure is a collection of heterogeneous data. Just like an array it is also a group of


variables but can be of dissimilar types. Using structure we can create data type known
as user defined data type. Such data types are also known as non primitive data types.

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.

10.2 Defining a structure


Defining a structure means telling a compiler about this new data type.

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.

10.3 Using structure

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;

10.4 Accessing members of structure

Accessing structure members is possible via membership operator (.).

Defining a structure doesn’t mean creating a variable. No memory will be occupied by


the structure until it is used to create variables.

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);
}

10.5 Structure and function

We can pass a structure variable in a function just like we pass values of primitive types.

Similarly we can return a structure.

Following is a sample program to handle student data using functions

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 input()

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);
}

10.6 Structure and pointer

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.

struct student *p;


struct student s1;
p=&s1;

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.

Following is the changed version of input function that takes an address of s1 in


structure pointer. It inputs data and store them directly to the variable s1, so no need to
return any value.
void input(struct student* p)
{
printf(“Enter rollno of student\n”);
scanf(“%d”,&p->rollno);
printf(“Enter name of student\n”);
gets(p->name);
}

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);
}

void input(struct student* p)


{
printf(“Enter rollno of student\n”);
scanf(“%d”,&p->rollno);
printf(“Enter name of student\n”);
gets(p->name);
}

void display(struct student s)


{
printf(“Roll no: %d”,s.rollno);
printf(“Name : %s”,s.name);
}

10.7 DMA (Dynamic Memory Allocation)

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

The major disadvantage of static memory allocation is lack of flexibility in memory


consumption.Since the decision regarding amount of memory has already been taken at compile
time no change could be made during run time.

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

10.8 Function malloc()

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.

ptr=(cast type*)malloc(byte size);

10.9 Function calloc()


The calloc() function is used for requesting memory space at run time for storing derived data
types such as arrays and structures. While malloc() allocates a single block of storage space,
calloc() allocates multiple blocks of storage, each of same size, and then sets all bytes to zero.

ptr = (cast type*)calloc(n, element size);

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

10.10 Function free()

The free function is used to de-allocate the previously allocated memory using malloc or calloc
functions.

free(ptr);

10.11 Link List Program

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);
}
}

10.12 Program to input string of any length.

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();

printf("You have entered: %s",temp);


printf("\nLength of string is %d",strlen(temp));
getch();
}

Check Yourself:

Objective Questions:

1) Which of the following are themselves a collection of different data types?


a. string b. structures
c. char d. All of the mentioned

2) Which of the following cannot be a structure member?


a. Another structure b. Function
c. Array d. None of the mentioned

3) Which of the following structure declaration will throw an error?


a. struct temp{}s;
main(){}
b. struct temp{};
struct temp s;
main(){}
c. struct temp s;
struct temp{};
main(){}
d. None of the mentioned

4) What is the output of this C code?


#include <stdio.h>
struct student
{
int no;
char name[20];
}
void main()
{
struct student s;
s.no = 8;
printf(“hello”);
}
a. Compile time error b. Nothing
c. hello d. Varies

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

7) Number of bytes in memory taken by the below structure is


#include <stdio.h>
struct test
{
int k;
char c;
};
a. Multiple of integer size b. integer size+character size
c. Depends on the platform d. Multiple of word size

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);

Write following programs


1) Write a program to input some numbers from user and find the maximum value. (Use
DMA)
2) Write a program to add two complex numbers (a+ib), use structure to define complex
number.
3) Write a program to manage employee record. Use structure to define an employee.
Use functions to manage input and display functionalities.
4) Write a memory efficient program to sort n strings in dictionary order

Explore and Answer the following


1) Write a program to implement link list. Allow user to choose from following options:
(a) add new data, (b) delete particular data, (c) view all data
2) Write a program to implement circular queue using link list
3) Write a program to implement doubly link list
4) Write a program to traverse a tree. (a) In order (b) post order (c) pre order
5) Write a program to demonstrate working of stack using link list

You might also like