0 ratings0% found this document useful (0 votes) 2 views27 pagesBook1 Python
This is also the pdf of questions answers of python programming for 1st year BE students who study engineering under VTU University
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
condcyrt of type conversior y
if 3 for with Farple,
) Gxplarin the typeof
Haale Pha taplctt, 6 exoltif cone
convenston means wemeoritig one (abel ype forfo
theo «
mene ae ee pes yan Re GaVveision te Python.
OO eer ae
: data-ypesont used fo an
EXPHESI1ON
Ws Python: tonvearts | po data- ‘pes fishen dato ype
Beompleie
re #iot-
BERS) # Float
C=ath
: ‘print Ce) # Obtpur 7.5
t poiotGypelc)) # Float.
|
% Hane tot is auctomaticalt converted to -fleat.
Beplictt = ype Goavenston Crype Costing) —
Dane manually by tre pxprommer.
Uses battate -fanchons tke ttt ftsot 5 eoEoplictt
V“TRis! ts. automatic «
Python handles “the convex
sslon op tts own without
aay help feo.
Qk Perfonned by : “The prograr
___ Python interpn eter
SS Risk { lowCno clata loss),
4S Example : Adding an inkegen
toa float.
# Inkgen
# $loat
SET+Y Python abtomat
cally makes 7 a float
Cis.5),
x=10
YESS
m Hes progrramensr os
won |2) Risk Performed by ;
Explicit
4irhis ts maoual=the prac
en mush u8@a specifi -funcs)
on -to change -the datatype
This 1S also callecl Fype cacting
Te preegrarmer
D> Risle? Highen Comay couse
Oreos if the data fs
| =p&hbley.
WS Brample + Govestting a string
Fo an token.
as"lo" sting
B=tatG) (Aranel conversion
efrbot Ch) yp oitenss 1S
torn
__ oh | Diffnechate bly syntox erm auntime enor.
_Syotor emt 2
ovefers
et
tule about that shucux%
° prom _if ths jam ts
Uy comect) -oHumwisé IR press fail ,
_ Pith con only
syntactialt
im and the
espa a
ocluans an ero _measage “This is caflalos Spyniax
Ceo
TF
x Tf tune Ts@ slogu ‘syntax esr anywhene in your
qran 3 Py Hon wrt cisptay-aremoy mesage-onct quits
jou will oot be abl ste Wo your png ram.Ruckine omwr x
mm | Spal ord-type--of Oren ts a avatinie erw7, So-called Because
th 46h erm cloes no¢ appean aotil you wud TEE" Gemgram
Fathi errs ane ils calle! exceptions because: -thny
i. usually indicate that something exceptional Cand bad) fa
4 4 {
<2 happend,
i. oe =
tS Syatex ee Gao
-—* Oceurs Whea Pythoo snes vules ane Violated
ected be fone eXEEHON, # Cause by wr00g Syrlax
Hene missing colon — S ar a er eee
$$ o-Fte— contrat _stater
ecrhme Pavia
© Ocaas dluning xearfon-
+ Program storts bur @ashes ——* rause by Logical Algal
_-eptacrtion
Beomple + ti
7 & =O
e— SRR pe as AE a Ae poco
__| pint Gi) f
| Btene division by zeno —» Runtime enor
+) falling a4Qs ad Descnibe
Gllate Gav) sequance:.%
Herat
00, & conditional sage.
Collate Sequnee én Vd
+ Storts with doy posthive ioteger n
+ Uf 9 is even 4 aivele by 2
* if 9 is) odel esi tulply Bea del ool ‘
__* Repeat votil n= 4
Example > Rynse;
& fs even thnefene dliviel if by 2 ¢ Ans is 2
3 iS oclel Smuttply by 3 & adel d= Aes is_10
urbl nei, a
G>3—4 10-4 S316 58> 4-50-54
ea Ee hee eo
Program :4) oy wy E
[re ae Goput (Eoten a aumben:"))
explain
{| N=OM2 —fevencose 2
im else: ' ‘
Ie a3 ene Pa iy é
_print C2) bs
«| C etn) a
+ “Frevafon(toop) + white Toop api s: hc
ondrHonayTy
'F-ebe checks evea/ooldl condition,
a Se
iat Sqaumee chmonstiates “mt Do) carson =
raking. fundamebitell tencepts tn , —yy
evdop Program -| stat prs
Ul numbers fromm A
that ane dlivisible by 3 ot S but mot bott bedi ciay
br Gleecle bruak statements whenever 6 aklable. “
We need numbers: jhus
+ divisible by 30% 5
* bat net both
#5 ==0) and Co 3=50 and n
eee Bese Ge ent
ania ge CL; lor):
TE TPSS=O and T7S ==07
~ comknae Fe skip aumbess divisib by tor
Te iE 3==0 oF tfs= = 7
pHata Saas a
saree pect
ell |Fooction die attonit aneans applying one nexenetles +o
as nesutt sof anathen.
Me PG) and g(x) ane functions :
| 9) @) = 4G0ca) baal Me
ple? q fs i
| } Saeed ce) = 2
796) a a
il a‘Then: 1
FOG) = £G’) Bo2 49
* _Pythoo Programa
clef £6):
“pied ae haat
cancers
Function composition Impves modulanihy & cocle Freus
posi De : ta op ele reuse.
Module —2 1 th a
9.3 a Slain teak operators to python P'S tei tog,
— | comtabenation,
xepchton ve Carepantson rth Sutter's
| examples.
* slant: Stamting a GrctisiSe
¢ end: Endin fdult
mans sea
sep Sime eaten} —Sa torbior
S=“Hello, World!” passes er
fiot(Bfo.s)) 4 Cwpet : Hello sad. anny
pint Corsa) db Output slot s f y af « ¢fficle
“ Hote Pe thines
Qk Concatencttion +
“| Gncatenation, joins -wo or mone sbiegs using thd
operator.
Ber
St = * Hello”
sl = wld $
sesult = sts ste
pat Gecult)— 4b Output Hellos World f
»
By _RepeHHon i= Repealition > pects @ seing jrulivle “Hees
asing the (# Jopenator.
EZ {
s="Hil”
pook(S* 3) H Ovlpurs Hil A Pe
4S Comparison Strings cao be compared using cormpaniston
opyrators €== s[= > 251%) € 9 9=)s Companisens ane
lexefeo graphical Celichonany orden). 7
st-=“apple”
$2_= ¢bamaa” ae
= 52) # Output : False
=52) df Ovlpct + True
print (sd <2) # Output : “True (econ
puotCsiss2) WOvlput tPalse
Se apple” comes before
‘beng oa. anoint:OP Baoke,
QR’ what & ao ANH CHE erpriesstdn OY that &
et put of the Shekeriiont
SSSR etter ttertoe eye THOU) coe your D7
Tarnty He oreason Uf he stacterneot frodiaces ar
erro 7
# He antthmetic expression 1S & Combination o£
Sperands Ganslamts | vantattes ancl spectre Sacha.
TH retes ed to prroctac’o-vertare-
a
>>‘ Hello World” + True ‘How one you 9!
“|e Python the + operator Te, wed fay
e | ngs. ede
el "aad “Hoar anetpsapr ane[the stakomert prlucesl ia, Typebmr becauce Python
does not support addon blu -incbimprodible lade
FY Pes Ching and boolean)
Uthat is python > List the alien -fectu
Py than frag iadming Hanguage
tist 2nd explaio different type of optvat
ython _ Winite the step by step ereust
| follnein 9) expmession, 10> Pytheo
> Gal e(GaN)/@-—-vy)
F ython isa Aishslevel intexpneted general — pumpose
programming language koown -fin Hs stmpl ity and
rocohite if gene. alk Se, da
% Salient Fertunes oF Python
th Simple aad Easy -fo learn
* Uses ‘simple English like sydtox
* Easy for beginners.
a Tr ian pncemia guage 7
* Gode fs exearted Wne-by-line
@ No need of compilation. iatee
[BS High-Level Language ee
__¢ No need oto manage memory manually:
_ AS Object=Ooriemtedl_ S
_|_$ Supports classes and objects 4°.
5} Posrtable bib iitbs it SN
'¢ Runs on di ffnent platforms (ialindows Linux, Mae) |
.@Dyoamically Typed
© No need -to declane vaniable “typeOT mn : val
aw Extensive Libvantes
* Pnovides man
handling icy
1a Source.
yh Reely_avaible. available wl
0c Phen 15 widely used clan to HS steipliethy Flexisry
-feertorves-———— “a.
builttin moctules (meth s-fle
ss
Us
and explain
in,
diffen cot types of opera s in
<* Operatind ane syanbole doc te ib
PeafOPn opertiin:
9 vaniables anol values |
Types of 0 ators:
S| Antthmetic 0 craters |
a S31 Ah) ee
Example :
rr as
I =
| prot (a+b) #13
nen[legtcal Operators
¢ jand, ov, not
ample
PROKCTwe-ancl-False)— 4 False
* Assignmert Operators:
| Biwise Operators CBs Ty Ws ees 37)
oh Muembeaship Operators :
© in, act in
Example :~ nay,
_| print Gaia Sapple') True
a Eh ott Operators Cis, is not)
= Operators felps i pesrforming vanious -compucterhions 1
| ancl Logical -operartions 1 Python,ch S$ Fe ~by ~$ tep execution _ of - the See este0
Give ex pness lot E
Cs-1) * (440 /@-1)
hs
Stepi? ea brackets
Step Qt Substitute values
Stp3i Division:
a2
Step 45 Muthplicathon
4% 4=l¢
Ee
Foal Answer?
Output =e
io -follows operajor
Buckels — Divisioo—s Multiplication,
eect ‘bowsWthat is a flow combol ‘statement 9
P| iP-else Stateierts with £.[Link]
* A ‘pS combol Statethem} corfols fie eaden jo
whlet statements “ane execstid irc. prrogron . hp
fo ctectsion marking ancl branching: basecl-o
S. . a
Disease PR ancl
P and if else ane Conditional shairaents.
EF Starmeck y ; a
The if stakment is used-to execuit a block of code only
_ when a condition 1s tre.
Syatax :
Lt condition + tVv _if-else Statements
The (fae ele stadtinent 18! used -to exec} one bloc|.
HE condition ts True anc aagthen: block -1#
‘ConcliHonsts: False tar
TF condition:
‘Stodemmen tt
else t
Statement 2
[bample he a= Saga 1
| 1$ 2% Iss Or 7
Pant Fever)
Print Odd")
Flowchart #=LQ -14S Develop a progvam te mead the name & bas
of a penson Display whether -thy pensoo 7
citizen ot not
___peot( Ntei_@ name of a pemiso0 :)
ame = fput() *
| print Niter yeon af bist of a persca:')
yob = Pnt(npust))
Loge 2 Q096- yok
if, age >= 6
mmnt(\aHello, My." name,” You asje a stoicy
‘ crfzen and"; age," yeant old")
» dse: MAD aos ——
7 pnot( \nHello, Mr. sname,” You ane Mot o
semios cifizen and age yer old")’
|
i SS o
aster Sratere te tiurs eine Mca
jo eaptate ercaptio handlag. Gat ad example! i
IS Explaio. exception’ handling wwilbion example,
_ Exception haodling to python fs a n¢ echaeisen_usecl to
ite hand ta rapintine errors: Ceiccaptings) so cthos ths 108
—-mal flow of dhe program is not Intvrusrpied - Sastea.
of -forminacto buptly , the: perogeram| ican. respond. +o |
i. Aj ts to 4
Ao exception is an emvy thot occu%s dusing the cet!’
-uhoo of a pmgpram.. :
Examples:
|. Division by zewo —y Jenn Bivision BROT
[+ TTavalicl foput —> Valuetemy
2° Ble not found = FileNetfound Ee le
Neecl for excystion handling a oe |
- Pneveots peogram | \ gla eas
« Moase-fasns oral perograc? Ffowo Te
po on rate aad
- Hutps ta dubuggiag mh Oh hn
|e Trngroves neliabi lity ‘of goffwane.— Keywords used ? to ere, Eption handing bets , ¢
ee TEN “eri et AO C0¢ epi ce
PEREPEMIEN 2s pee od tei Lyi
3. S u i ho ¢
—% (else o bbl
fi
CeUTS:
pueda if iff
+. Finally = fr ie at eteptba. Occurs or
nO
—Usecl to maoually fia ao a exapton
tpt A
S- vase —
fot Results “9 sesult) ?E _ Oecept ‘Zewo Division Grr +
{ Print Car» Cannot divicle by. erm }
Lexcept Valu Gory > 7
punt Gn: ‘Tavalid ioput -
else:
1pm at Cobian success! hin n
TEI A hs EO
tes pret Gaga ee fs: ices)
Explanation 9 Semple
2 eTThe try block takes. faput andl performs: clivision
se Tf. uses eters ze asi Zevon ionbooy Bandled
lle Tf tnvalicl to put Valw Err hondiad.
LS Ef ne err > dlserbluck exeirfes
Ile finally block always) 305.
JE Bui Hin Ex
__¢ Pnedefinecl. fo eae i
-| Bearple : Typebror , Tadaof prevgrams: iby
| Murtime oe r effecvely Et rmakes ferogcre
=ms bust and ese =ficedly,
WAIN arate 249
Noesleaned teat at rneplcec” - 29 a ay E a
i #4. iM Hs verse TUsiog < Goa OM
$2 cleaned text £3 - -i) !
—_ Same
pea aa ist aotea :palindrom e.")
ot wonks :
tet) is Python Iictng_ syerlarc “thas reverses
2 The perocpram scompanes ths ae bon et ny
F hs Deversed version |’ +,
* TF both au Same } |f4's dang ]
__Beample + rs
“al shieg’ : adam, +)
ON sli gh] eee A .| asa
Faoction is usect 4p Count “the -auerbey
The nesuly its displayect OS cursus.
om
of words,
Casual method Cathauy using split)
SO
re Program to count number
7
7 of words Manually
“Nock sloput CEnter ailine of tect 3")
tount——5 soa
Ht Check fib
IF ten Geet)y
count =U HEA (cost one aaee ects
Rig teat ciara ae
fchest
Cuneta eee AT
prick @ Number -of coords +", count) i
7 naa inriolng hing wage Pty)
[x Wop Freight sammie :
ee: Brery, Hime -a, space e ‘
Bl wet. iden
* Words =Spaces +21.
= [ncnease cardExample ,
Eoter a line of -text : Python is tary.
Number of words :
] en Hreetige
T This mediibel 3 “may give Vocornech esults if *
Fix ax mu Hipl 2as@S spaus.
Tene ane ne teadiag [trai Wing Spaces
ft} SY Se”!
= loput Chater a line cof tert:
count =oBasle Methods
fet fa Tn
Shae ewe = int Cop
_ aumbers , ter ‘ai
ven_aumbers = £}
Sor ww to fmbers >
iF nemyg ==0o8
even numbers, append Cumm ) i
pmeotC Gen ambers 3" ever_aumbers)...
Arothas loop chacks— each number z
Tif mum 7 2 == 0 Seen
= Add 40 aew tist.
wh tater a anes ef elements =
— rte —nmbes ty
Erte _num bea: 2.
Erta numbes 13
Ent aunba sy
pt umbea rs
Bren aumbes : £2, ¥]Q\ | &plato mutability fa Itste. Diustrate, the clif fen ence
ble” medifying a list &. corrating, o chonr-of fu "9 F
xamples,
; .
_Matability to Lists
; Mutobility means -thy abllity of an object tp be: ‘changed
k after THis cneated.
“In python, lists ane muurlable , which means !
* we can modify ements
+ Se can acld oF aemove Hens
|
1 ovina tisk gas = updated “witout sewertg o
tae bject
tambers =f 374] a
Pe. ee oat te igh = ee a
Jouspusn> C410, 3 +i Sa ee:
| Dare aniginal Uist is clineely changed.
eieareste ble - mmecly fying List -B corating: a clone
Fb ig tot Cone Berl a
Uist 1 4.3.4)
| Uist: 3) 5 lea
| Both is ists. change beet
tar CUst se: rep std.)a.2 Cee, eo een
—| ree tee | Pte.
eo Tes tocaton as
VisVs) Coeabiog A clive: ONuiv Hist)
3! " vy
Using slratng |
sty = C123)
Lista = Listf*] HH clone
i List 2s append (4)
_pmot Clist Lt
_protCusta:" Es
op tat Sh Ai
~ pam ist ay 14)
Now, sth mains Seas but) Usb2 is 0
Sepanake copy.
ect © Medyfying Game List) Coming CN list) |
Mumory, Same i _ DiPR nent =
[aange, |} —__ Affects bot _Indpendlert
Example List =UstL ! Lista = tists]
|
Nicks in -Pythob ort mutable, neaning thes wwoterts |
con be modified after coraton Hsigning -one list
‘onattft ccoeates -a_nefnence to tu same -object,
both - Sie ing slietag “aig
ati hon