a) Type tunchons in pyihon?
Eaplain with
with
Ont Suitable eample in PyHhen
Ans nTn pthon, a tunthon is a 4rmup of related
Stateme nts that pcrfovms Speciht Aask.
funchons hdp brtak ouy pro Vam into Smalley qnd
Modeculav chunkS As ouv progyam grois lavsw
nd ayYge funcHavn make t more Yganie d nd
M anageable
There are thu type Of fynchiony in Pyton
Built in funchons Suth a help() to ask for help,
m in ) t get tn minimum value, pvint (O to prinf
an object tv t tewminal, on Can nd en Ovw vi ew
wim ort of he se FuncHorns
3. User- defined Funchons (UDFs) which are funchanj
h at u sers Crt t to hlp e m
OntAnd
3 Anonymous Funchons whih ave alyo (all ed
Lanbda Fun chany becaue he qre not dedared
wih He Standara def
kewprd.
Eampu of ca
tunc1o.-
def greet (name).
This fun chon gecs to
Hhe perso paSscd Mas
apavamete
pYInt Hello, "
+ nqme +". Good ovninq ")
How to Call afun th an in Pynon
One w havt ufind a Funchon wt Can (all it
om qno thw fqnchovm, pvo qyam o eNtn th py hon
Simply pe th funchi aon
Prompt. To Cal a
hunchon we
name wmppropitu pavawkws
> qreet ( Paul')
Hello, Pa. G000 mornina |
ull campleusin undton.
Here is m
def r u t (nama)
he
thi tuncHon geh
in as parameky
per&on passed
name +". Good moniaml
print"Hello,"
q reet ('Paul')
Qa.
h a is a Palindvome?
A Pulindyome is nouinq bat an numbe ov Shin
which reMouru unallwd when eversed .
Ample 2 32-
opuct ,
a palindvome Numbe
Ample RACE ECAR
otput- Yes, a palin/vom Sing
Palindvome Pro vam using l l e
lo op
loap
num int (input EnBew a numbev
2 tmp = num
33 Yev0
while num > 0).
dig = num , 10
eV =ev* lo + dig
num num 10
Ctemp == YevN)
print C The numbev is palindome |")
el SC
Pint Not a palincdome | ')
Ondpu
Ente a numben121
The nun bey is a palindronme
Palindme sin using inbult mehod.
sthin: "))
Shing= input
CEnte a
2 16 shiny == striny C: : 11):
Print ( The stinqis a palindrom" ")
else
print
p nt Not a pålindome")
Onkpu
Enttv Shing s1
The shmny is a palindrime
Q.3.a)
let He given twe ily be le 1, txt l e 2. tet
OuY tayk to mene both Ale into third ile Say file.3tet
Pile 2 het (onain
Suppot the text frlel.tt and
tel lowing data
file 1. txt
E file Hokpl
Ale Edit Format
Content fvomflle?
This isth
Hetlo There,
This is in filel.
l e 2.ht
-x
le-Noepad
File Edit Format vie
Hello Geeks.
This is in file 2
Below is he impt menfutjon.
#phon pogram to
t diMos r t i murginj
t 0f two files
data - ata2=
Fom file 1
tRiadin datu
Cile.txt ) as fp:
Wi open
data fpvead()
file 2
+Readin ata from
wih Optn (file 2. tt)
ao fp*
Yead O
ata l fp
#mugim files
the data of fle2
#to add
line
+ From nect
n
data t =
data += ata 2
with Open ( Hle 3. t t .
W')as fp:
f p wte (data)
Otpt
Filc3 Nokpad
File EdtFovmat Jitw
is +h (ontent fm file
This
Hello thure.
Thi's is in ile
Hello Gecks
2
Tis i in file
elow is tmpnetation.
#Python progvam to
# demos rat murging
t hwo ile
+rtating a lut f ftlename)
filename L'file1. tt'. file2.4xt']
+Open file 3 in uvie mo de
with Open Hle 3. tur '. 'w') as outfilc
+1tertu through list
Fov names in Hlehame)
*0 pen {ach file in ead Mole
wih open (nanes ) as infile
trrad te data from ilc 1 ant
+ read 2 an wne it in fil
Owtfile. wvite Cinfile. read O)
+ Addn' to entev data af fAle 2
from ner line
ont ile wrt "|n'")
Otpu
Hle 3- notepad
hle tdut Fomat view hlL
This ish Conkrt from ile|.
Hello Thurt
This is n filci
Hello Gek
This is in file 2.
import YC
2 Import requess
3 fmm url lib pqrje impov uYlsplit
4 from (ollectons import deque
m bs4 impovt 6eauHFul Soup
impovt panda as pd
colqb impovt Hles
7 rom g00gle.
input C Enlev tu websik uvl " )
Oriqinal- url
un Stvape d deque( Coviginal- urI])
1
13 SCraped Set (O
4
emauls Set )
6
7 while len uns(Yaped )
ur 4ns(Yaped. popleft ()
19 ScYaped. a4d (url)
0
(url)
parts urlsplit
"o, Scheme / {o.nctloc".format
33 abase -
b uvl =
ats
4 if ' in parts path:
L :ur. YHnd ( Y ' ) +1J
S Path- url
else
Pah url
7 " 7, uvl)
pvint ("Crawlin5 URL
3
31 pon s=reuests. 9et (url)
request
33 eept Crequeshs. teptions. issing Schena
eetcpty. (onnechon Eyvov)
33 Conhnuae
34 Cra-20-9\.-t 7 t@
J3 new emails= (re.tindall
Set
9 . \ t -Jt\, Com ", Yesponse. text, re .1))
a zO -
(neud-emauly)
36 emauls. update
37
eautiful Soup (response. toxt, Ixm'
38 Sup
Soup
31
40 for anchod in Soup. find- all ('a"):
f hef" anhol.attys
42 link an chov. atrs ' hvef"]
43 else
ink
4
f link. Stats with (''):
link base -uvl+link
47
48
link. stars with (http'):
elif not
49
link path t |ink
R1 not link. endswith (". q2"):
S3 TF not link. endswith in unS(Yaped and
S4 not link in Scaped
link)
uns
(Yaptd. append
S6
sT df pd. Data Fyane (Cmals, Co lumn =["Cmail"
df. to-CSVemMail.Csu, indet =falye)
60 files. download Cemaul,csv").
Q.6
b) Dichionan
PHhon dictjonany IS an unordurcd Co llech on
0fitmj. Eadh Ie m ofa duch onay has a key/val ue
Pai
Dichonavies are apm|2el to rehvieve ver val ue
when te key is known.
Crecuhng Python Dichonany .
Cenhna honam i a Simpk as placinn t
insd Curly bral AS Sepavattd b1 Gmmas
An itm ha key
a
kiy an omes poding volu
4hat is enpvesyed as a pai (keyvalue).
whrle val Can be of a ny Aota pe iCan
reptat kjs Mut be immuabe type shing
numbe OV tuple with immut able element) muut be uniqu
emphy diiinary
duchonay wth inttyen keys
m1-d = {1 apple, 2 'ball" }
Mixed
# dictonamywith iatt kyu
my-Aict > { 'name' 'Juhn',1 [1,4,3]
# using elict ()
my-didt dict I : 'apple ", 2:
ba )
from
tfrom Sequnu haying each kmn as a
paiv
m-dict dict (C, 'apple'), (2,'ball' J )
Q.6
Tuple
A tupl in Pyhon is Similar ta a
(ist. Th
Atttnt behween the two is hat we (annot changc
etme nts of a
tuple on ce i+ s assgned whert ay
we Cqn the eluents
Change a list
Creatay a Tupl
A hupuis Creted b plaCAnA au Hh ikms ingile
iniel
PaYent heses ( , Sepavate4 by omray.
The pavant heyes art Ophanal .
tuple Can have ay number ttn ho May
be
oe a differend bype» (intge flont, lüt, shing, ele. )
+Diffement hpts of tuples
tEmpy tuple
my-typle =O
pind my-tuple)
Tuple havin 1nte gevs
my-tuple (1,3,3
ointmj -tuple)
+Tuple with mixed datatypes
"Hello", 3. 4)
mj-euple 1, =
print My- tuple)
t ntske d tuple
my-tple -
(t, ""Mous", C8,4,61, C1, 2, 3) )
Print (My-tuple)
Owtpu
1,2, 3
1Htello 3.4)
Mouse', L8,4, CL,2,3))