0 ratings 0% found this document useful (0 votes) 24 views 77 pages Python Imp
The document provides an introduction to Python programming, highlighting its features such as simplicity, readability, and versatility for various applications like web development and machine learning. It covers fundamental concepts including variable types, input/output functions, and control structures like conditional statements and loops. Additionally, it discusses Python's dynamic typing and built-in functions for type conversion and arithmetic operations.
AI-enhanced title and description
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save Python.imp For Later e
PYTHON
\ PROGRAMMING
NOTES |
Choe
a
R
s
HIMANI SAINI = sae= Date ... jo
~~ EyrHoN._PROGRAMIMING
c- Into ducing Python - be:
i — ea &_a_high- level genus = purpose and ves.
it
opular progr tng. tanga : 2
a! uate veh usd tn Gwe development, Machine learn.
- -tag applied ete. eae
ee Pytflon fuegrame ae Cd Smaller than the othes
jin Hogrammin dong uages .
— Puogrammers VU have to type Helatively less and the
tadentation requirement of the Janguage makes tens a
eadable at ihe time.
+
i> Voi Simple Syntax. 2 fasy to learn,
t v oT Cv
~
a ooh ay |
paint (“ Helto”)
>
=
= General pusipose Janguage ( Simple yeh very powerful,
3 language)
s Console Applfcatfon & Scripts iw
C= f> Desktop Application :
= [> Web Applicatfon ‘ ;
* E> Game Development FE
f Ly.\Machine: learning iden: learning. AL, Bf dala ek-
= “4 P “t ot Z
— Muttinaradigen Support =
\
[= Pavcedural Style Programming _I?ke C - =
sl “s
L>. oofs ike Java, © g
Functional Programming (tke Usk.
f=> Portable or Platform Independent
= Puoqrams are typreally first compiled nto an
Utatermedfate cod¥, then the code Pe yun
Me interpseten .
—>_ Dynamically Typed.
nyna 4y---NP
~= 10 4
ys “qeeks™ 4
uv .
ace “python
J 7
This featuve %&_dffferent from Ctr b Tava. they ‘
ae stateally Typed i
In python we don't have to specify the vatable
PY
i
name.
But _the disadvantage & fm this the type & asstaned |
° i v
in the vun time" of the paogram , so there avd
f paeg
move chances of yun bme
evror.
— Automate Garbage Collectfon
‘
\t _medns when you
4 dynamically allocate memory
So you don't have fo worry: to yealfstng — th?s
memory . g u \
§
=> Popular Apolfeatfon Butlt tn Python
FF ~— +
Youtube y Nettlix',) Quora 2 Instagram ,
DoopBox x 4
=r__batat O tn thon — %
A__funclon & a sek of fnstructfons' that take x
some fnput Prom | diing..dose somehiwork on those -Date ....
io
~~
a quametes and
2
J ieample = patel Couette”)
pofot Welcome", “to, ee
= aint ©)
ee F pofot (“Hope qou—are enfe
zy
ae Output - Hello =
~ Weltome fo aE a
= as
Sy Hope you are safeytag Python. xX
Tos endgA end and sep parameters fn paint :
PP f
2 z
= int (“ wWeleome”, end =" 2) ra
paint (* fo GPa)
Outpuk- Welcome to GPG =
votre
End parameter __oteates _ space and {ft tells » shoutd ae
be printing after tks patating. -
And tn sep pavantetet. when we haveY multiple =
P—f
input parameters we use sep to separate” them. —
# f
By defoult they ame separated by space. a
o f
CAMS REL Ah
Per i
eae putnt (“10", “out , "2023", Sep ==
"y EE
Output -. 10-04-20a3 a=>
Nanfables fn Python =
Nawable & a name that oO
used fo. suefer to memory
Jocaton. Python vayfable also known a+
-fiex_and® used to_hold value. ’ :
Jn thon, we don't need bo specify the hype of
Notable because Python t& a in flew language and
i —__#
{__smant enough to _qet vanfable type. ie
| get_vontable typ +s
E z fee» 5
xample patce = loo ”
tax = (8 =
! °, s =
t total - pailce + ostee + tax
paint (total- putce) *
&
Output =o alts,
aq
How vantables wok 9 a
= 4
“= 10 Uo]<~ *
yee “geeks” qeeks |e~ f ‘
Zaid (go|—z €
it we say wez a §
When adolf 4
Nwx 4
bat TP w=: 30 Bol<— w :
4
aa OPocs 165 3
410)
f. : y) geeks 4
putat 2) 36 /
print (w) : 4
oO
q
a4
|~~»
ee
Pathan Dynamically Type
eee 5 a
Bo m% +10
$
J putat (>)
. nk: “geeks”
U
ya paint (>)
~
10
~ qeeks
~y 7
~ 3 Note - using a_vaniable without assfaning fk cause error.
~ &q- paint (x)
» oP- Name Exror : name ‘x' fs not assigned
~—
ut) tn Python -
4
3
This functfon ‘u__used to take fn put fiom the user
} t
Example - name = ‘input (“Enter the name >")
8 ”
psiink |" Welcome''+ name)
t
ole - Enter the name = Himanf
Welcome Himanf
Example - # Python program tor _additoa
' t | +t
= fnput (" Enter Fiect Number :")
4s input (" Enter Second Number : sy
m= fat (x)
We int (y)
Hes ney
F Spat print ("dm vee)
vy lvl aoe lyl e blew lelTyped) In Python ~
Outpul = Enter Pirsh Number
we
rom string .
Is d
Type & a _bullh-in_function that Hells
se h0
wherever we
have to A
you data lupe
of a “vavfable or a value. i
Eg a=10 :
a (type (a))
= 10'S
‘ re Ciypecay) r
C2 9437
puint (type Co) ;
O)P = dais, tints §
<= class, 'floatts
<= class, ‘Complex'>
T
=n python we use "None" Io
Whe value uel or we dfdn'h asstan any value fo thy
voufable > g :
é
4
indfeate that we don'h know §
“
\n_ python there 9%
h te
no chav ype you w wank ft a. aga, reuld
Eg - Sky_= “gtg" (Shing § fsa sequence of chav),
F
paint (type (atry)
J [.10, 20, 30) (_@tray and dynamfe ally
patol (type (19) add and vemove thee. st
Irems are stored fa conte.
~nuous locaHon)
Storae~
re eae
$= {10 30,30},
“difference
fy
modi
Sek_& a _collecHon of _
Ss pint (type(s). where all thems are _
= t and set UW dike mathematical
Set)
y “ w Oyu », as J
~ dz fio: "gfg’s 20%" ide" J dicfonaries ore uscd to_do
a paint (type (a)). ings. Jhe & a 7
3 J collecHton of key value pairs)
> Eq- thems : porices rollnot Name.
ai
>
p> Type conversion in Python -
Type conversion
> se
3 Implictt ExpltetF
a fat !0 €g- 4 "135"
os J= 1+ dnt (s)
> ‘it (0) f= float (4)
3 d= true patat (3)
es atd paint CL)
3 patat (e) : $
X opp = us ojp - 14s
» u 135-0
fg- d= " geeks”
wT SJ
» paint ( Jist (8)
> patnt (tuple (4))
Py pafot (sek (43) :
p= tigi. tet fet ht Mt] a
1's")Date .....
9-3 a= 20
patint ( bin (a) te =
palnt (hex (ay) aaa
+ b (oct (a)) a
| ¥ OP = Obio100_
| URIVE
H 0094
=> Comments fn Python ~ ate
1 We may with to deseuvbe the code we develop. We 5
might with~ to take nokes of why a
J
sechfon of sept p>, a
for _fnstance. Formulas , pocedures , and sophistcaled
business Jogtes ave
v
iypfeatly explained wfth comments, #
TH
4
Single -Jine_ comment - # a
Mult? -Jine comment - Hs. oe ie
# te a
Doc-stying - the string enclosed fn trfpte quol-es 4
that contes _ tmmedfatel after the dettned fm ane
catied Python DoestYing, @
¢ v E
=P ib else and eli? in Python - ig
a pans %e
Shee come _sthuabous in sea) Jife when we need to
do some Specific fask and bated on some Speci pte, é
onditfons and, we declde whak should we do next. 7
Similarly, — there Come a. sthuatfon Ph potoqvammeng =
whee a ‘pectpfe tak & te be performed if O spectPhe ie
conditon _& true. &
Seat
LhMe &
~~ Date .
in quth_ care, cond?Honal . slatements can be us
condivvonal statements ave 2
So
~ ig. elie
= Nested if s
SF. tp nig. statements. cee
s ement ~ tn Ist
¥ R= stat t th ip the condition & true thea
pout executes else the elie pout executes .
3 " Syntax - if conditfon +
% H Statements to execute ff
# condition &_tHue
+
Flowchaxt —
> aS
Fi Test False
¥
Tue
% x.
Body F FI
s —S
y Statement fust below
) Ce ey
+
Example - if lo 75+
y puink ("10 & greater than 8")
F
i paint (“ puogram ended)
O[P - 10 U__greatty tan S-
v
Program ended
ia J
btDate on.
fe (
if-else statement ~
block of code te
when If tend
ip: Statement the additonal =
slalement -whfch perfame!
recutes this “block if
condiNon & true
ele: 7
# Executes thts block if
# conditon & false
Flowchant ~ 3S
t
a
zy
q
Example = a= 3 a
: ip we=4: eh! 4
pafok (yes) ‘s ;
else: J
paint (“No") 4
Fxample- You can also chain ifelse statement with more than”
one _conditfon. : ¢
Jettey = "An" i “4
BP dettey 22 "a":
pint (" JeHor & 9" a
else 3
TE deter = ="c",
paint (CY detter ey
SeeatSy
™~
we
elses
Sp iettes = :
Span Craton ba") fi dneiu Sue
‘ ele
; Jette unk: AS and ce” it es cao
= 3
Fo? - deter UA
Nuled_Y Statement - if statement _can_alte be checked inside
FY othen_ if statement. Thu _tondiHonal statement G called a
—~J_nested if statement. thuu_means that tnnen if condition will
be checked only iP outer it condition %& true and by thu,
we ean ste _mullple condone fo be sahisffed
> gyntoe - if Ceonattion 1):
~~ i, # Executes when condiHonl W_fuue
. ip (condttion 2):
~~ Executes when condition 2. true
~~ # Wf Block t end here
~3- # if Block &_end hee
Example = num = 10
it num > § :
J putnt ("Biagen than Ss")
ae it num 2= 18
5 paint (* Between § and (5")
— ole - Bigqet than §
+ oetween § and iS
ite eltf Statement - shortcut of theelse chatn, while using if -elff
> statement at the end else block & added which “&
_ S_peitormed ip none of the above iL- elf ctatement tb __frue.
Y SpnatDate .... .
Syntax - i? (conditfon) t
= Statement
elif (condtHfon) :
stalement 4
4 ; =
L . =
Bs) elses «
a statement a
Et Example - —Jettey = "A" 3
ip dettem ss em:
_paint (“Jeter & 9")
elif JeHea == “ct:
putok ("“JeHer uc”)
elit Jette == SA":
paint (" Jeter & A")
elses
pint (“ Jeter isn't A, 8 orc)
OP - Jeter GA
> Aulthmetfe opetators - They
gHe | uted to peiform mathem-_.
=aHea) operations Jtke. additonal, subtrackon, muthip.
-Itation, division. ; _&
That axe 1 onithmetfe operators tn_. Python - =
O Addition _® subtraction “_@ Muiiipixation
@_divteton @_Modutes © _Exponentiatton
@_Floor _diviston i“ay Date
I Onevator -_In__python, + 4 the addilfon operator. It
TW y
5 0 tet odd 2 values: si 2
~~ Example > voll = 2
val2 = 3
SS ess vol dt val 2
SF _puint (tt)
—j_ fh + £
Sos SubtracHon Opevalor_- used fo subtract the second value from
he fick value.
5 on -_ vod 3
val a2 2
Ss des = vobl- vad
~~ paiat ( He)
So as Modulus Operator - sJo u_the mod ulus. opuigtor used to find
~yhe_Yemainder when {fest operand t_divided by the
~~) second
4. Example — vol 1= 3
vol? = 2
J dea = val l Yo val 2
~S_ __ paint 9)
> 0) Pace h
+O Exponeatfatfon Operator — _** used to raise the finch
_y operand to power of steond.
x Example = voll +2
> vab2= 3
> ves = voll ** v2
a. prtat (ts)
= oe - 8
SpnratDate ...
+ ® Floor diyfifon - // Ss used fo find tne floor of _the ustinh
when first optyand te divided by the second.
Example - vall = 3 as dis Eps pe a
b Nald = 2 ib
Uh Mes = val t// val 2 ie
bh patot (es) ge bs 7
pee ojp - Pa es __ #
i=> Puth logit 0, ith Example ~
3 ‘ython ogica) Opevators with ample -
Operators aye used fo pot opeiaiions on values and
vawiables. These ave the silat symbols that 0 and b>O:SS ,
ne
ees piel. (ome oe
WE es fparons and b> d 6 70% es ie :
SF pata [2 oe mabe ou ane aye _guieator than")
elves.
~ tol Tepmeast one number & 4 riot greatut thanso°}
are greater than 0
FP = The numbers
Aileost_one_ number U_nok geal than o.
~-
~¥ Example > a=to
Se eR
i cz 0
if a and b and c: i
paint (“ALL the numbers have boolean value as True”)
Sy
3
— >> else:
Ss
~~
puta (“Atkast one number has boolean value _as False
O]P - Atleast one number has” :boolean value _as False.
=e ~~ Falte Output Tue Output
~ > Example - azto
:
pS be -10
es eae c20™
if a>o or boo z .
then of the _numbew i agrestet than 0"). na
ben ts
ps s
th b>o or emo: me: : z
_puind ("ef Mhey of the numben gusset than 0")
else
—-paint_{"No_number lu greaten than 0)
DIP = Eifhey of the number _U Greater_than o :
No_umber i _greaten than 0
— Example - a=to
+. brie
4 =o
}
iP aorb ore:
pufot (“Atleast one number has
#
Tue") _
boolean value at
else:
pink (“AN the numbers have boolean
. False")
Value at
S/P- Alleast one number has
boolean value as True.
| = Logieal Not operator —
wouks with a _ Python Membership and Adentthy Operators -
validate
the _memberthiy
ina sequence such at Shing Afsts or tuples .
im_opevatoy = Jhe Mn!
Python offers wo membership operators fo_check es
of a_value, It tests for membersh,
operator ‘u_used to check it « thera
/ substring | element
Evaluate fo “true jf th finds. the apuitfied clement fra
existe tna sequence or not,
Sequence otherwise False. For eq -
U
| “Gy in_* Geksforqeeks! tt Checking. 'G! fn_shein
| “Laue g d
LL 4! Greksfor Geeks! %# Checking ‘9! fn strtng sfnee pythe
tk case~ senuthive, veturn fale g ig
False
"
Example diskt = J1,2,3,4 23] 4
isha = [6,7,8,9]
them tn Jct:
bs
if fem tn Stet: i
— paint (" oveilapping”) ;
v
elses
paint (" not overlapping’) i *
4
nok 100
i
nok
Te a
not a
nok
4oh t int opevalor =
no!
J Vasfable inthe
does not fie
J false other
Example >. R224 ts a id _—
ys 20 wt a ie
“Yet = [10,20, 30,40, 50) _ =
E(x nol fn dist): a
ft NOT nt tn ven disk
_pulat (. ats passe gf sk”)
elses ace
i 4 fs + in ven Jfst"
int ( xis paesen i gis fs ‘)
ety tn Wt):
aint (“y fs puesent fa given Afr")
-s
else:
~~ patnt ( iy is Not puiesent fn given Ate")
= °, ©. ° 2,
OP - _% fs_NOT paresint In_given_Iist.
~ y fe present fn _afven_Itet
SS wt v
- \dentity operators - Thy ane used fo compane the object
woh’ the obfeds ave actually of the same data type and
shove the same memory Jocatfon. a
There ote dif wank identity operators such ad
Nis operator - Evaluate to True ff the vanfables on efther side
of the operator joint to fhe same object and false
a} f
othutuice.
Example - me S
43.5:
portnt (oc & 4
fd)
fa
Sport }OJP = 1407045 86672032
—— isin SENS
Ie, both the vay
Hore, tn_the
S asttgned to th fi “and
which? why eure Ty
Ss rot’ opwator - Evaluates fo folie ff the vaxfables on _effhen | stde :
of the opwiator _pofnh te a ditfount objeck_and te othuwise, 4
Example. ~ KES
S2a0p
4
iE (type (oc) fe nob int): |
a putnk ("true") .
a elses
= paint ("fale") =
b # Patnts Taue =
& Ke Sb iy
3 It (type (x) fs not int):
i . “ " =
paint (“true”)
i else: &
t punt ("false") a
. '. : > 1 ¢ 7
i ofP- False a
Taye) 2
=> Python Bihwise Operators: — &
Operators are used to perform opeialt e4__ gS
ie ea an perfo peatons. on vafu
axiables . ese ane the Spectal tymbols that cawiy
out _anfthnee and loatea) computaifens. he value ahd
operator opevales on is_known as Optrand .
i
:
i wy~S Date ween
oo Siu operators ~ “
SJ = Slhtce AND () ~ Return | tf both the bits ae I
else_O. "
Example = £102 1010 (Binary) |
=I
he ee be Y= 0100 (Binary)
~~
~3-
¥
a
a&Sb=lolo
b
ol00
= 9000
= 0 (decimal)
STG Bitter OR (J) — Returns Lip velther of the bik & 1 else 0.
~ Example - _@=10= 1010 | Binary)
=3 e b= 4 = 0100 (Binary)
alb = lolo
~ vac ol
> o100
= Ilo
7 = (4 (Decimal)
¥
5 e)- Bitwhe Not operator (o) - Returns one's complement of the no
> Example = Q=1to= tolo ( Binary)
waz sl0lo
3 = -(lolott)
4S > (1011)
“5 = -11 ( beefmal)
> d)- Bitwise (XR) (A) = Rebun | ip one of the bis fs tand the
5 other & 0 else return O-
W” SenalDate wee.
=lu (Decimal) +
‘
Example - a= io —
= bey Ss
i # Puint bitwise AND operatfon EO
wink (“ab b! arb)
# Puint bttwhee OR operation =
print (“alb="y ale) 2
# Putnk bitwise Not operation Ke
paint (“wa =", ~a)
# Patot bitule YOR operation -
paink ("a 4b =", a Ab) e
op - at b=o 2 afb=1y 2 hae -t =
atb=ty G
&
@__Shitt Optrators — These Operators ate used fo SWrPE the ¢
bits of a number Jef or sight thereby multiply én “
ox dividing the no Sy—two resp. they oth be used Yoheg WG
we_have Vig multiply” or divide a Wimber by two, &
9)- Bitwise Right &p Shith (>>) — Shifks the bik of ime no,
fe the _sifght and fille 6 on _votd. det p (fs tn the 6
case of a _ntoative Humbe) iat a sesult, Similan effeck as &
of dividing i no. with some power of two. ae :
Senae J : ay
Date
Example = azlo = 0000 1010 ( Ginar
ee a>>| 0000 Ohl = S_ ?
az-1o + Mtl oo ( Binary)
~ o>> a Vit tos 2$
yas
“Ty. _gitwise Legh shift - (<4)
art shifts the bits of the number to the left and fills 0
on void vight as vesull, Similar efPeck a of multiplying
a the _no- at some _power of two.
SS Examplt - az§ + 0000 O10! (sinary)
3 acs] 20000 lolo = 10
“6: azn > 0004 0100 = 20
~e Example - b=-10 = UNE oto (Binary)
~» bec f= M10) 100 =-20
=a bee 2 = Ol tooo =-40
28 Bitwise Operator Overloading - . Optrator Overloading means
nt extended meaning beyond their. predefined operat
-ona anin For example operator tote used fo add two
integers
it © ochtevable because the ‘+!
“S_by int clase and sty dats. You might have noticed that
~ the” same _builk-in_ operator or funclton shows different _beha-
7 vise for objects of dfpferent classes, this ic called Operator
as thet as join two sting and merge two _Ifsts.
perator is v overloaded
~ > pverloading.
=
3 Example - class Yeek():
def- init — (self, value):
i self. value > value
A def and. (self, obj):
paint (And operator overloaded")
SperatDate ween. 4
if isinshance (objs Geeky ES
ditturn self.value be obf.value
operator overloaded”)
ity fsfnstance (bjs Geek):
seturn_self. Value | obf. value : a)
else:
Mase Value€rror
def - xox - (sttP obj):
paint (“XOR operator overloaded”)
(Must be o Objeck of class Geek’)
tI ip isinstance (obj Geek):
4 velurn selP. value 4 obj. value
i else
ratse ValueEvror ("Must be a object of dass Geek”)
def. Ishitt- (sel, obf):
paint (" Ishipt operator overloaded")
if fsfnstance (obf, Geek)
Seburn SelP. value ce obj. value
else:
Yatse Value Error ("Must be a obfect of class §
Geek")” ;
dep - tnverk. ( selp):
paint ("Invert Operator overloaded") 4
Heburn ~selP. value 7
# Duiver's code
iP— name ==" main": 4
= Geek (10) 4
be Geek (12)
sit {asb) ‘
‘i 4paint Cal b) eS s te
ppt Cat)
r~ paint (aces) ae ees wad
3s paint (a>>b) is us te
pata (x9) een
[= - p- And operator overloaded =
OQ
Pa 8
Or operator overloaded
Ww
Xor optrator averloaded
eat
\shift operator overloaded
p>
~~
j= 40960
>
is
wishttk operator overloaded
i
8g
Invert _operalor overloaded
=H
—~* loops in _Pythou_-
U
— while Loop - It & used to execulke a block of stakements
sepeotedly until o given conditions tb Latislied . And whee the
oldie beioma false , tin Hue frimedialely olen He loop
im_the pucgrave uassexeated “43 Gre
Syntax __while_expstessiow :
statement (8)Flowehant
Exits while loop
a indeffntte thetahon.
While Joep falls unda the cig tn i
ladefinite etalon means that _ ih numben of Himes the
executed sin't specified ex; Weil fn_advante. :
Statements _uepuesents ‘all Jina atatemenk indented by the
Same_oumbey of chayacke space, oa Pegrenaaatg
—tonstrud oe considered tot be pant of a sinVie blo of
Li tode. Python uses indentalfon
loop &
f
as th methods of souping
1 _shatemess. When awhile coop hk execuked exph & (for
4 fvaluated fn_a Boolean context and if TEER bette He loop ‘
body U executed. Then the expat checked again, ff fp
St at taue then the body | executed — agai and the
continua until the expsieaston becomes false J 7
lr
Example - | tount 20
while (count < 3):
count = count +}
pink ("Hello Geek"),
OJP - Hello Geek
Hello Geek
Hello Geek
| nd ol bly.— [20 fos Le
|
|
=)
<=
SF yin wun until there &_an__element
Joop over _a_Jisk thak
this, we have Hun ao while
potesent fn the Jct
t
\n
I : 7
Example -3 gfngle statement while block
yr U
YFust_Jike the
py statement we can
thert_ ane multiple
tt block, ip the while block consists of single
declare the entfre Joop fn_a_ single Sink. 1
f
statements fn the block that make up the
l body, th tan_be sepanaled 6 Peol sh
% loop _bedus ey p xy semPeolons (4)
_s_ count = 0
5 while (counk' <5): counl+=13 patnk( “Hello Geek")
—¥ t
J: olf - Hello Geek
5: Hello Geek
Hello Geek
i Hello Geek
aw Hello Geek
>
3
>
*
SparatDate ...
eC) in Python - s
e__puthon nm swehwan ence numbeu
sa sequence of umbeu
thon _stange () £7 webu
7 fe & to Pherate -
it i range. Ihe most common use of tk J a
ina _gwen nge.. Ihe most ¢c
4 Python
scquiotss onal! scquinee of numbers _using fy
Syntax - range (stot, slop, step)
a ;
Paxamelen - stax}: LopHonal] ‘
Stop + .
t 3
Sheps
} cs
Return : os
Example - for _f fn _range(5): .
t ° Os &
paint (“ty end
=
puink() f
OP 4 f One 3y4 : ~~
"what the use_of the Sange() tn Puthon ? é
Oo
% : =
t tn__simple berms Hange() allows the usey to qenewake a
t F i.
i Seifes of no. within a given range. Depending ‘on how é
|_mani aagumenl the usd patting fo the Sr, the wey &
f
| can arte where thay seniks | of “numbers wits begin 2 en
(Bas well a how a the dif Peuence will be between one no.
and the next. Pf range() $M takes: can. be infltalfeed
| fn 3 ways — g
= wane {stop)_ fakes one anaqumuenk.
=_wange (stant stop) fakes Arqurueuk.
zi alge (stout, slop, step) taker Wee angumear
gDate
when
al
Fae will _qet_a_sentes of
Sadudts every whole number up toy bul nol including Wee
T
number tral Ihe user nas patovided as the slop ‘
wr Example -
Python range (6)
Teh ilstels T_T
for i tn range (6)%
puink (1 Gnd ="")
paint)
p= ola 34'S
Stop
{lo
siange (stant, Stop) -
Tv ohen the user call ange) with — two anquncents ,
decide not only Oyhore the sente of no.
he _usey gets bo
lope bul Valse where it stasis, so Me users don't have to
©
shaut at O oll the Himes Users can use nange() to qenerake
3a susies_of numbers fiom _X toy. S %
i v
Python vtange (046)
= J
>
5;
= Tor Toh: [sTsfst Te
=—+t
pas -
> Stat ced
+
¥, SperalDate ....
2 tok, sto}
Exomple- Drmonsinatfon of fyihon stage (shat, step)
# pataling a natural >
# cianbi rom 5 to 20 di
fou i in ange (8:20): ad zt
. . iy
part (ty ene"
f
0) P $6724.10 Woes ty te ett 1819
Tig wange ( stant. stop, step) ;
ie) When the us called ange) with three angumenty
the usey tan choose nok onky whee the scene of
“___numburs will staat and slo’ butsatio” haw ba the a
; 7 f
diffuince will be between the one. no. and th¥ Oexbeg
Wf We usey doesn't puovide Hhe step, Hhen stange ()
will automatically behave ay if the sep & 1. In ney
i txample we axl pitnites even no, between Q and lo e
i 2
So_we chosse our stoVitng paint Prom O[ start-o) and a
: He —$
stop the sewfes at tor ( stop)» for pyinting an even
f =
number the . difference between one. number and the ©
fext number must be 2 (skp) afte. providing. a Step: $e
° i r Z
t oth Ut
we a e fo owing output (0 2,4,6, 8), “6
Stout Python ange (0, 10,2) oS
4 gd yer s
oh EW Tebpelapol ~
; or
Ser , =
See
ofal4 8 2
eee EE ee
Sperat — =
iDate .
trample - Demonstration of _fython sarge _( stant, step,
Jon ‘in songe (8.10.8)
paint (1, Send = © "y
v :
paint) et
Oe 0,9,4,6,8
Ty fox Loop in Python -
foe ae ae
ie ri
ts used for sequential biaveisal tee, th fs used
aa Sterating over_an orable dike Staing Tuple , dist,
~ Set ox _D¥eHonary.
= In python , Were ts no _¢ style for Joop ‘ bes —for
iO; tong ttt). There isa “for Joop which ts similar
fo cach oop. in other Janquages.
SS UU
* NOTE - In Paria fous Joops ronly_itmplements the
collection based. theWatfon.
> i
5 Syntax - for_vow in__iterable::
aL oe #_ statements
~3 1 Flowchart of. for Joop
For each ikem in
_ 4 :
4 equeace
= -
True
> ;
>
¥ t Ext for JoopDate .
once for each ikem. in’ an Tae fe
vwoiable vor takes the value the next ikem. o| the
Heable
ty tach Hme throw hi meat a
a eg ae
thon pogram fo. fllustrate {
Le # “iterating “over a dist e
aa Ve ("qedls, "Por", “quake”
[“qedks", "for", geeks ] :
i lov Tin Ls a
sF or *
sp ees
|
le -
| r Loop fa Sonne J
@ "7 i ie ©
k ‘heating over dichionar
o Oy .
i int (“dfeHonay Ihevefon" ;NS |
py
PPT cacak_ ia pyttion - Vt fs used to baing
“FT of tne loop _whtn tome external _cofdition is tyfqqer
buco statement is pul inside the Joop body en Way
_oftes it tondition). tk terminates _ the tureint oop , ta
a the loop _in_whrch_ Tk appears and resumes _txecutfon ‘an
\ statement Hmmeat ately afer the end of that loo
Inside oa nected Joop , the rt
f =
_tontrol_ouk |
i
Tene
If Wie break _shakement fy
Ireak will Hyminale the innermost Joop .
}
{oop lesb
expression
be
j
| Lal
False
}
4
U Exit loop
Lalo Hal a [a
aloe
4 b
4 owe |e
Example - 2 S= ‘qeeksforgeeks!
# using for Joop
T——
for_leter th s:
prtak leHer)
#4 break Hie
gov 's'
HE letter = = ‘ec? oF leney ="! =
break 3) ~ —
paint ("Out of for loop”
: ae ae ass
iro
# Using ushile
7 while True:
1 pink (s[1])
1 "# break the
1 # or 's!
se,
an
loop
{
loop as soon ih sees 'e!
t
if SUTS =e" og SUJs='s's
+
pufok (tour of white loop")
Out of for loop
+} }
e
Oub of while oop
* Continue Stakemen}
nlasgla a Hilal e@ & Js! at i: 3 foi
in_fython Ih fe
Statement that forces” to
a loop contro]
I casate the nex) thera fot
of the: loop while skipping the vesk of the fode
inside the loop for the currenk Skeratfon only y he,
d
See
n> |!»
v Date
2 The coniinue txeuted in the Joop ,
ihe tode__ inside __tonifnue slater
oh el ‘ i
et wil ‘evalton and the
> "_tonttnue
paint (x)
T
Howrhart of Continue _Stakement =
g
fonditforN. True
fe continue = ‘
EX neni Continue |
Teale
False
Erecuke the remaining
zi
part of Joo
for vai in" Greeksforgeeks":
if van = = "e"s
4 .
continue
pint (var)
iS
IS
+ + la eld HEL4 4 4 E14
'
whale
'
;
iDate ...
en_you need fo wrtke a
#
patale fhe number fvom 1 fo 10, but not 6.
} A '
+a slualion
= = 3
akipping. the psitnt of charach
ore _ skipping paint of
x _Joop from | to lo
for i th range (1,11)
# ip tts “equal to 6)
# continue to_next Steratfon
2 without _pyintin
tp tee: d
“tontfoue
else: i
# otherwise paint the: value
# of 7 ; »
pata (7, end =" *)
n checking and _contPnue__ states,
of- 12 3 4 578 4 10
J+ Nett Loop - With - for and while
NOTE- THE CONTINUE STATEMENT CAN BE USED WIT ANY
OTHER LOOP ALSO LIKE WHILE LOOP” simiLaRLy AS IT 1g
UsEb WITH ‘FoR LOOP” ABOVE.
loops we. can
{
‘
a create nested Joop. Nested loop means Joops
inside a Joop. For example, while loop "tnifde the ®
for _eop, for loop fnside the fox loop eke. é
ie
Searat
faLJ,
= Syntax = Quley -loop Expression :
a ' ye
Nyy Inner- loop. Expression +
“= Statement Inside ‘nner. loop
ne t :
Statemenl Inside _ Owter-loop
Example - m= £12]
y= (4,5)
for fin x
for | fay:
+
patak (tf)
i $
Sige 1
\s
24
25
Example -2
# Mullpltcation Table
# Running ouler loop from 2 to 3
fort tw range (2.4):
# Puinting! inside the outer Joop
f
# Running jnner loop prom | te 10
° 6 U0 " *
for {_in_vange (1,1):
# Painiing! fnstde the inner loop
paint (2, Wanye te bey)
bea Se ta] 4 Ha] 4 fol Hal G LG
ae # | Pataling aside the. outer loop
oe paint OW
f
1% oP - Des geek WS a 10 + 0.
2 Se eS oe ee CR WE Sie Oe 8
a; =
i
Speoratculty for Joop to
through _o_lish
tem fa Ih
# Painking outside toner Joo
pint (“stort outer for loop")
# foiblaltee couler | with 0
0
# Running fnney while loop fo
# MNevole through a Isha
while (fz Jus 2S dee):
# talating Inside tnner loop
pyint (them © dist 2017) :
es ncrementing the Nala of i
je i+]
E:3 patniing aie inner loop
paint ind for loop")
f)P- short outer fox loop
!_am healthy
oN
| om fine
| am geek
end for: Joop
slort_oulty for Joop
You are healing
You ave fine
SteratYou one geek
———t =
end fox Joop
niftalizing two Iists with some
a In_Ints example we aye z
ching: Store the size _o} Jeska in ‘Wish 2- size’ using Vent)
“Syondlion and using tt in fhe while loop _as a counten,
J Afier_thar_vun Son outer for loop _to__ iterate over WstI_
ond inside that loop un _an inner» Joop _to__iterate over
rid using _list_indexing inside that oe avers puinbta
Teach val sof st 2 fSy every value of tisht. d
“a _Fanctions_ in Python -
SF Python funcHons ts. a block of statements that veturn
the _sperifie task. ;
: The ‘idea is fo pul some commonly or repeatedly done
Tasks _fogether and make a puncton Go thal tnttead of
wailing Vthe some code again _and again for different
“SF inputs? we can do the _funclfon calls” to weuse code
t *
wontotned in tk over and oven again.
= say
= =
~ Syntax - Python functions
; J
a
Keqword Function name Parameters,
« t
> + ——. +
e det functfon- name Cparameteus):
. iy ‘ T
a # statement | ————> 8edy of j
Statement
——) =
jucturn_expresston
7 f
= f
x fuaclion xetorn
+
SpaatDate ....
Example = def fun:
wink ("welcome fo GF Gr” 3
ve Dsitver code to calt_a function
fun |
off - Welcome fo GFA.
Defining and calling a funetfon with parameters: < aa
Defining: ‘ 1
Syntax - def Punctfon- name ( paraniele : data. bypr).33
Aehurn fy et 5
"DS vtng i
# body of the funchon *
q a
aidturn expression >
{ =
si
Example -_ # some more functfons
f a
def fs- pate Cn): =
Spo in [a37: 5
Mehutn Tae a
if (né=1) or (nm Jo a=-0); nial
Achurn False %y
3123 Anquments of a _ Python Funckfon -
rs Auquments ave the values passed — inside the
me payanth hfs of the function . A function can__be
r “have any number of arguments separated by a
I comma. <
may Example - # A simple Python Functfon to check
ti P= }
ve whether % is _even_ov odd
“def evenOdd (x):
my paint ( “even”
yy else?
paint Codd")
~ # Duiver code to call_the functfon
~ even Odd (2)
ay evenOdd (3)
4 o]P - even f
= odd
J
eT ESiiz
Ha es of fagsrnenls
=H Defoult argument - It fs a parameben that assume
pal a default” value it a value. {snot provided ta
= the functfon call for that. argument.
a 3 g
Ly frample de eng tan (9 (aS ge So):
f patat (“as x)
- paint (“4:", y)
# bulvey code “(We call my Func) Sie
# only aqum ent)
my Furie)
O[P- x10
450MY Roe aL a Ma ace te ii)
| @) Keyword angumeatt =
the am
the argument name - with
dors Wt need lo semember thé order
Parameters.
Example =
# Keyword arguments
Studenl( firstname = ‘Greeks', lastname =
values) So that —
Jef _shudent (firstname, lastname)
puink ( firstname, lastname)
Student (lastname =! for', firstname = 'qeeks') |
opp - Geeks for
Geeks fox
_@__Van?able- length arquments —
we can passa vanfable number of.
sents fo a Punchfon using _Specfal :
art _hwo speefal symbols-J |
Sumbol.
T
U
¢ * args (” Non-keyword Arquments)
+ +e Moavas ( keythord Arguments)
g g dg
Example: - def “my Fun (% argv)
for arq in’ argu $
print (arg)!
MayFun (‘Hello's ‘Weleome’, “ho!, Geeks tow
Geeks ge.
oP - 5 Hello
Welcome -
fo =
GecksPor Geeks =