1.
Python Revision louo I
Tokens/Lezial Unit
The smallest individuol unit n a pMo9Marm is knovon s
Loken ox a leieal unit
Keyonds ( Tdentifiers (3 Litexas Operatos
(9 Punttuators
# Keyuoo ds
-TOords having specia meaning ocserved by pogamn
igangu
+ Tdeñtifiess
Names qiven to dif. paotts of the poegoam
Rules mut NoT be a keyoord
) can contain etters,numbers and
(h) can't start Loith a numbex
Igthan is
small le
case- sensitiveie., treats capital &
tters diffesently
# Literals
Ttems that have Aoxed aaluc
eaueee of ohoracters suaTunded by quotea
(i) Single Line- use
i) Multiline muse
Gbackse
2, Numerie Liteanals
(ay Integes LOo35,0 9)
i) Decima! L 2, 102 9)
COo35,Oo77)
oi) tlesadeaimo (Oz73, 0aAG2)
(6) floa tisg Föint oitten oih decimal Pint
Real obers
form> 0.17E5,3.E2 s6
(Enponent
(c) Cem ple
a b are litea Poaks. rpruen
3.Boolean itea
Tue and fal
A.None Litesad
Tndicale absence of alut
# Openatos A,2}, ")
i Anithmeie
(ä) Bitoise
iü ) ShPt (<<, >>),.
(is) Tdetity is ,is_not)
() Relahoac,<,>=,, l=)
(vi) Logical (ondo3, not)
oi) Azsignment (-)
(vii) Mem beship (in, notija)
(ix) Arithmelic-osighment (/=,t=,-, ,%5,"s,le
# funcfuatons
Symbols use d to oganize sentence stoue tued,
and indicate the onhythm &emphais o eapesr'bns,
state ments, and porsg1om tructure.
Saquence What it oes
Backslayh (y
Single quote ()
Dodble 'quo he (")
lacoatn
Bell (BEL)
\a ASCI
Asc Badspace (Bs)
AsCIl Formtee
fo d (EF)
New line chanacte
\n In
|Chaactex named name
Unicode database
Carmage Retn (CR)
Horizondal tab
Chaxactey oith Unigode
16 bit valu
Choaaete with Unicode
ax*2X
32 biE yalue
AscIL Yerical fab
Characte with octal
alue oo
\ooo
eharacter oith hen a e
lahh
# Baae bones
Epresiong-legal combination of symbols that
Tepesens aalue
Statementb - Proqoamming instuctia
Commeat eused
Func iory- Canbe de hined
state mentsinsde
/Suites - Goup of
Blocks anothe statements o a func Hon.
statements inside a block iat
All
same level
indentation
Dynamie Typing of aen tain bpe can
al
Aaiable poiting to asalue/object of dif tpe
be made to pointto a
O,end )
Default Se is blankspa
Delault eid isneolia
Sep pints bto each item
End prints atei the inpt
Datymbes
() Tateges
()Thteges ui) Bee
(6) Floaing point bumbe 15 diatp
(oComplex
-
numbes
boh pats saved a oah
4iveaea pat
zimag giesimaginay pat
sting
(Tud
#
ODictona
Mutahle data types
storee
mamey
Lists ,die tionas , seh
Tmmutable daa types
Tn Same memoy addeu, e r a e cannt
be sted
Ecample iat, flaad, complea, sting, tuple
For stang,
concatenaio
" andt me
epliahon
and" *2
>>> "andme" >andand
Evaluating Anithmehe Opeahos
* * Convension
Lmplicit type canvesion compilex oithout
petormed by
paognammers in terveni&n
TÆ eitheg aqument is complex, the
ther is convted t emther
T ei theá axqument is
1s corVerted to Ploa
bo th int ,no convesion
Some oher gulesi
aaay gves Ploat esut
*Opesation Precesence
Ois, is not
ne
and
4
# Evaluation of Logjical Opeaabs
ist toue veturns l t
i d ale, etusng 2nd
(9In AND,
if st true , eturny 2nd
> 2 on d 3
3
>)3and 2
- and3
Tpe Casting /Erdiit
Type convvsion
Type Goversion
by p0gHamme%.
>type(46)
<elas Flaat '>
>> type (int (4.0))
Lelay int'
Con Statemert
sate ment header
(mulliple simple /compound stake ments
slacate
Simple sfate ment
Single ezectable stotemet
statemert
-does no thing
used shere syataa nequires a statemert bt
logic deesnt
+Sequeafialy - Noxma
Selec lively Conditional
Ttesativelykoops
+ Condi Honal statements
( i el
Stoing Conditiong in sariable
cond= 2l= 10 an d l2== 0
if cond
paint"Candlton Palilled"
More eiciert'educes no of compani9N
Loops
Cor loop (3equence).
for Kaiab in <sequence
statements to ept
Rang
-jum
Cevluding Ccondikion)
(oile loop
ohile Clogicad eaprtion)
body lagial
Loop
# Jump Statements inLoops
Dbreak
-breaks the loep oubde the looe
-yumps to thestatement
(2continue to neat
-skips gest of the loop and pes
iteoration
# Loop els
els pat eeeuts oheA loopno tesmingtes
beak
normag ,ie, it entountes
Syntan
Dor <vasiablesán Kseguenct >i
statement
statements
shile <teut condiion
stakment
else:
statemenk
# Staings
Sting in gthon is sloed as individua
charaters in Cantiquals locatisrs
Sting indexing
Backward
-54-2
stLGIHI71
>st [2]
H
+ Item Assignment -NO T 3O PPO RTED
nam
name Lol =L"
ERRR
Traversing SUPPORTED
Opeatos
1. (oncatenaton
>a = m e A 2.Repica
a fonCool
S>at3
>cooleoolcool
megood"
3. Membeshp
me in "me time >>"me not in mekiE
Taue n me time"
fals
y nat in metime
ACoopanison
>> abe" "abt
Taue
Comp aison Rules
on the bais of lexogape
/e b>a l B>A
2. Uppey cases smales thon lowen wes,
b>B .
False
Drd )- Takes hanac
walu teY,etung Ascl
cha () - Takes AsCU value,
eay charaekr
Stzing Sliees
stop (exe lusive)
* N yalue
s[:31
>s=abede Mechans m
>>s [:3)
abe Ca,bc]
>s [3 :5)
de pints stulf,i b-l inde
not at a's ight pain
de
>>s 3 I0: noting
nothin
thing but goes lePt
# Staing fune tionN
1. leh U dont chang
2. Capitaliz U Syntoxi<staing lenU
Sutaa : <stingcapitalize
3.Capibaliz£
fin d
ld chaoate
Synte <sta),And st, tast,stop
ge tun t igtance
IÆ pot found where subst
A.<st) 0sanum
S.cstr. i9apha )oueif all hokat charactes
cKste>isdiqit(). eat
salnum, alpha &
3espeeivety dig1t
chavag te
Te
7. <sta). isspace ()
ar e ohitespace,
9. <st)isupper( ae louer case "pPeruL
titted
Tpectively
S>Queen'.islower)
Fals
>"2 g°e en'.islo uoe )
>"2 aUCENisupper()
sDum bo. isuppenl)
false
S>"Me coolistiHe
fals
s> "Me Coola' isHHe )
. str). lowwer (O)
str upper)
13.<strd, HHe ()
J4.st stasts with (prelelstantjLAnd)
pisna
ISstr.endsaoith
G. <sts oapase ()(preßislstant fsendJ])
7. <stbpasi thion (sep>)
> Mynarme is patihon ("is)
My name
Mynam is Aau".pahithor ('apple
My name is Auy
IS.<str) couat (sub lys kast C,endJJ)
19. <ston lstip (Cehr])
defaalt vale Dhilespace
Catl posible substoing are
emoved
pmegod Sstoip ('am)
20. <str stoip (Ccha)
2l. <str). stoip CchxJ)
22-<str ite
2. <sta> inde Ksublsstart L. end])
retu louet indea
23.streplace (cold), <neo>)
24. <str), split (Lstr)
defat vaue ahi tespace
>T Gm Aru sp lit("am"
# Lists
- Ia C
Mukable
#Creahng Listk
2. L= ht # ceates empy hst L
3.L-ist (seq>)
4L= i t linput ('Eater hst ") # takes jnp st k
Con vet to lis
euates data
type t the inrt
#List- len)
indening 2
embevhp opesaor
men
str
concatenatim t) oephation C)
#Sto List
ohje ck lge har sthers
So, ot cach jnden store a elerence
(unlike str Bat storey a character).
Tlem asiqnment -suPfoRTED
Taeveslng SUPPORTED
can uesliceg for ligt mod:frcahon
> L , 2,3,4,sJ
L [io,20,3,4, SJ
L lio, 2,3J
Deletng Elemenk ist
del <ie (<indeas]
del <ist> kslice
del et> # deletes wbole kt object
#L= [,2,3,4,5, 6J
shalbio
a L
(opt
> a = L-copy
# List funcions
1,<lst,indea leiemy) If not found, er
2. <st>.append (item >)
3. <Ist>, ea fend (Ist)
A htinset (KfosiLem)
5 t pop (2indea>) Deleles 2 netaons vabe
value - 1 d
6Clstemove(kvalue)
Tlst clean () Removes 1soceutn
3. <lst). count(<Item))
I0. < l t . sot
IL ltSo ted
12. min (<lst>)
1S. mat>)
4sum (Klt)
#Tuples
-Tmmutabe
-inO
#Creah.lC
T= i, 2,3)
Tupls
Cates
T tuple "aru)
T eval (inpudlEnter tuple
(inpu (Eatex tuple clement)
)
ndering
len()
membghp
concatenatn opeabr
replicaonaLk
acceming indiidu ement
THem assgnmenNor SurpoRrÉD
Note :
(3)-’ t eab a singke element
3,)teot a tuple
# 1len
Tuple Func tioy Melhoda
manTaple
3. min
4. indeelement
5. Count(element
6. buple ()
#DIC TiONARIES
-Unerdeed
- NOT
ollectior o pas.
3equence
Access ing Element na Detenang
<dict> Rkey if no such key ERROR
<dict). keys()
Ü) <dic t)valbes()
# Tnavensing ALLO ED
# Adding element
Kdidy Kr keu)} = Kaen) vaue)
#Updating a dic
ietony element
ne vale
# Deleing element in a dicionary
) de <dict> kkey
kdiei>pop (key deletes lretung
alue too
IfBOTno Oesuchcankeye this
** <dict (kkey,<tert in case
dict=
dict
oPNoo2
popThaeeot found
Not found
#Checking for Eis ten ce of a
<key> in Kdict
<ke not in cdict
#Dictonany fune tions and me thods
1. len()
2. <dic y.aleax( ) d b
dict One:,To02
>> dict cleal)
>> dig t
3. <dict)
S>D= u:o,2: 20
t D. qet (3)
None
>D. qet (3,"not found")
no foud
4. <diet.items )
D{i0,220.
u, o), (2,2o)
5. Kdicd. keys)
SS> D { 2 2 0
,
G. <dict,valesl)
DfL:10, 2:20
» D.values ()
Cro, 20]
7.<dict>.update(<new_dict)
D1 = i:0,2:20
>> D2 = f1: to'o, 2: 200
DI. update (02)
DI = i10, 2:20,3: 30, 4 40
>01, update (D2)
i10,2.:200,3s30,4:4Do, 6:6oo
So ting
Aarandy element in specifis ondeN ascendin
desshding
4 Bubble Soat
Compazing
them
adjacent elemends
hof in correct oder.
Al ezchansing
578
36olst78
3ol6578Apred
30S7spped
3fo51673 ehang
no
change
Second
t o t 5 t 6TL& aith na chang
Codet
L= (2, 3,0,9,7,4J
n= len [L] becouy
fo (n):
fo
in ange (0,n-i-):
s topS posam
an soaps Scapped True
d false):
point ("oaignat t i t }
paint ('Sonted list L)
# Tnsention Sot
Sot an prsas by puting the element at
it coet poi
Inony pases hzoushaay bnce
Code:
L= [2,3, 0, 9,7AJ
n = len(L)
fon i in oange 1,n):
key = L E)
i- 1
while =0 and key&Li]:
point