0% found this document useful (0 votes)
241 views

PDF

The document contains Python interview questions and answers related to basic Python concepts. Some key points covered include: - Python is an interpreted, interactive and object-oriented programming language. Code is executed directly without compilation. - Indentation is used to identify blocks of code in Python. - Python is dynamically typed but strongly typed, meaning types are determined at runtime but inappropriate operations on different types will fail. - List comprehensions can be used to create lists, sets and dictionaries from other iterables based on conditional logic.

Uploaded by

vamsi591
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
241 views

PDF

The document contains Python interview questions and answers related to basic Python concepts. Some key points covered include: - Python is an interpreted, interactive and object-oriented programming language. Code is executed directly without compilation. - Indentation is used to identify blocks of code in Python. - Python is dynamically typed but strongly typed, meaning types are determined at runtime but inappropriate operations on different types will fail. - List comprehensions can be used to create lists, sets and dictionaries from other iterables based on conditional logic.

Uploaded by

vamsi591
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

PythonInterviewQuestions&AnswersBy

fromdev.com
PythonInterviewQuestions&Answers
By
FromDev.com



Basic

1. Whattypeofalanguageispython?InterpretedorCompiled?
Ans .BeginnersAnswer:
Pythonisaninterpreted,interactive,objectorientedprogramminglanguage.
ExpertAnswer:
Pythonisaninterpretedlanguage,asopposedtoacompiledone,thoughthe
distinctioncanbeblurrybecauseofthepresenceofthebytecodecompiler.Thismeans
thatsourcefilescanberundirectlywithoutexplicitlycreatinganexecutablewhichis
thenrun.

2. Whatdoyoumeanbypythonbeinganinterpretedlanguage?(Continues
frompreviousquestion)
Ans .An
interpretedlanguage isaprogramming language forwhichmostofits
implementationsexecuteinstructionsdirectly,withoutpreviouslycompilingaprogram
intomachine language instructions.IncontextofPython,itmeansthatPythonprogram
runsdirectlyfromthesourcecode.

3. Whatispythonsstandardwayofidentifyingablockofcode?
Ans
.Indentation.

4. Pleaseprovideanexampleimplementationofafunctioncalledmy_func
thatreturnsthesquareofagivenvariablex.(Continuesfromprevious
question)
Ans.
defmy_func
(
x
):
returnx
**2

PythonInterviewQuestions&AnswersBy
fromdev.com
5. Ispythonstaticallytypedordynamicallytyped?
Ans.Dynamic.
Inastaticallytypedlanguage,thetypeofvariablesmustbeknown(andusually
declared)atthepointatwhichitisused.Attemptingtouseitwillbeanerror.Ina
dynamicallytypedlanguage,objectsstillhaveatype,butitisdeterminedatruntime.
Youarefreetobindnames(variables)todifferentobjectswithadifferenttype.Solong
asyouonlyperformoperationsvalidforthetypetheinterpreterdoesn'tcarewhattype
theyactuallyare.

6. Ispythonstronglytypedorweaklytypedlanguage?
Ans.Strong.
Inaweaklytypedlanguageacompiler/interpreterwillsometimeschangethe
typeofavariable.Forexample,insomelanguages(like
JavaScript)youcanadd
stringstonumbers'x'+3becomes'x3'.Thiscanbeaproblembecauseifyouhave
madeamistakeinyourprogram,insteadofraisinganexceptionexecutionwillcontinue
butyourvariablesnowhavewrongandunexpectedvalues.Inastronglytyped
language(likePython)youcan'tperformoperationsinappropriatetothetypeofthe
objectattemptingtoaddnumberstostringswillfail.Problemsliketheseareeasierto
diagnosebecausetheexceptionisraisedatthepointwheretheerroroccursratherthan
atsomeother,potentiallyfarremoved,place.

7. CreateaunicodestringinpythonwiththestringThisisateststring?
Ans .some_variable
=u'
Thisisa test
string'
Or
some_variable
=u
"
This
isa test
string"

8. Whatisthepythonsyntaxforswitchcasestatements?
Ans .Pythondoesntsupportswitchcasestatements.Youcanuseifelsestatements
forthispurpose.

9. Whatisalambdastatement?Provideanexample.
Ans .Alambdastatementisusedtocreatenewfunctionobjectsandthenreturnthemat
runtime.Example:
my_func
=
lambdax
:x
**2
createsafunctioncalledmy_functhatreturnsthesquareoftheargument
passed.
10. WhataretherulesforlocalandglobalvariablesinPython?
Ans.Ifavariableisdefinedoutsidefunctionthenitis implicitly
global
.Ifvariableis
assignednewvalueinsidethefunctionmeansitis local .Ifwewanttomakeitglobalwe

PythonInterviewQuestions&AnswersBy
fromdev.com
needtoexplicitlydefineitasglobal.Variablereferencedinsidethefunctionareimplicit
global
.

11. Whatistheoutputofthefollowingprogram?

#!/usr/bin/python

deffun1 (
a
):
print 'a:'
,a
a=
33;
print 'local a: '
,a

a =
100
fun1(
a)
print'a outside fun1:' ,a

Ans.Output:
a:
100
locala :
33
a outside fun1 :
100

12. Whatistheoutputofthefollowingprogram?

#!/usr/bin/python

deffun2():
globalb
print 'b: '
,b
b=
33
print 'global b:'
,b

b=
100
fun2()
print'b outside fun2' ,b

Ans.Output:
b:
100
globalb:
33
b outside fun2 :
33
13. Whatistheoutputofthefollowingprogram?

#!/usr/bin/python

PythonInterviewQuestions&AnswersBy
fromdev.com

deffoo(
x
,y):
globala
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)

Ans. Output:
4217
4
17
4215
3
4

14. Whatistheoutputofthefollowingprogram?
#!/usr/bin/python

deffoo (
x
=[]):
x.
append
(1)
returnx

foo()
foo()

Ans .Output:
[1]
[1
,1]

15. Whatisthepurposeof #!/usr/bin/python onthefirstlineintheabove


code?Isthereanyadvantage?
Ans.Byspecifying #!/usr/bin/python youspecifyexactlywhichinterpreterwillbe
usedtorunthescriptonaparticularsystem.Thisisthehardcodedpathtothepython
interpreterforthatparticularsystem.Theadvantageofthislineisthatyoucanusea
specificpythonversiontorunyourcode.

16. Whatistheoutputofthefollowingprogram?

PythonInterviewQuestions&AnswersBy
fromdev.com
list
=
[
'a','b',
'c'
,
'd'
,
'e'
]
printlist[
10]

Ans.Output:
IndexError. O r Error.

17. Whatistheoutputofthefollowingprogram?
list =
[
'a',
'b',
'c'
,
'd'
,
'e'
]
printlist[10
:]

Ans.Output:
[]
Theabove code will output [], notresult
andwill inan
IndexError.
Asonewouldexpect,attemptingtoaccessamemberofalistusinganindexthat
exceedsthenumberofmembersresultsinan .
IndexError

18. Whatdoesthislistcomprehensiondo:
[
x
**2
forx inrange (
10)ifx
%
2
==
0]
Ans .Createsthefollowinglist:
[0
,
4,
16
,
36
,
64]

19. Dosets,dictionariesandtuplesalsosupportcomprehensions?
Ans.Setsanddictionariessupportit.Howevertuplesareimmutableandhave
generatorsbutnotcomprehensions.
SetComprehension:
r={
xforx
inrange
(
2
,101
)
if notany
(
x%y
==
0
fory inrange
(
2
,x
))}

DictionaryComprehension:
{i:
jfori
,j
in
{
1
:
'a',
2
:
'b'
}.
items
()}
since
{1:
'a'
,
2
:
'b'
}.
items
()returns a list of 2
-
Tuple
.i
isthe first element
of tuple j isthe second.

20. Whataresomemutableandimmutabledatatypes/datastructuresin
python?
Ans
.

MutableTypes ImmutableTypes

PythonInterviewQuestions&AnswersBy
fromdev.com
Dictionary number

List boolean

string

tuple

21. WhataregeneratorsinPython?

Ans .Ageneratorissimplyafunctionwhichreturnsanobjectonwhichyoucancall
next,suchthatforeverycallitreturnssomevalue,untilitraisesaStopIteration
exception,signalingthatallvalueshavebeengenerated.Suchanobjectiscalledan
iterator.
Normalfunctionsreturnasinglevalueusingreturn,justlikeinJava.InPython,
however,thereisanalternative,calledyield.Usingyieldanywhereinafunctionmakes
itagenerator.

22. WhatcanyouusePythongeneratorfunctionsfor?

Ans .Oneofthereasonstousegeneratoristomakethesolutionclearerforsomekind
ofsolutions.
Theotheristotreatresultsoneatatime,avoidingbuildinghugelistsofresultsthatyou
wouldprocessseparatedanyway.

23. Whenisnotagoodtimetousepythongenerators?

Ans
.Uselistinsteadofgeneratorwhen:

1Youneedtoaccessthedatamultipletimes(i.e.cachetheresultsinsteadof
recomputingthem)

2Youneedrandomaccess(oranyaccessotherthanforwardsequentialorder):

3Youneedtojoinstrings(whichrequirestwopassesoverthedata)

4YouareusingPyPywhichsometimescan'toptimizegeneratorcodeasmuch
asitcanwithnormalfunctioncallsandlistmanipulations.

PythonInterviewQuestions&AnswersBy
fromdev.com

24. What'syourpreferredtexteditor?
Ans
.Emacs.Anyalternateanswerleadstoinstantdisqualificationoftheapplicant:P

25. Whenshouldyouusegeneratorexpressionsvs.listcomprehensionsin
Pythonandviceversa?

Ans .Iteratingoverthegeneratorexpressionorthelistcomprehensionwilldothesame
thing.However,thelistcompwillcreatetheentirelistinmemoryfirstwhilethe
generatorexpressionwillcreatetheitemsonthefly,soyouareabletouseitforvery
large(andalsoinfinite!)sequences.

26. WhatisanegativeindexinPython?
Ans.Pythonarraysandlistitemscanbeaccessedwithpositiveornegativenumbers.A
negativeIndexaccessestheelementsfromtheendofthelistcountingbackwards.
Example:
a
=
[
1 2
3]
printa
[- 3]
printa
[- 2]
Outputs:
1
2

Q27.Whatisthedifferencebetweenrangeandxrangefunctions?

Ans .Rangereturnsalistwhilexrangereturnsanxrangeobjectwhichtakethe
samememorynomatteroftherangesize.Inthefirstcaseyouhaveallitemsalready
generated(thiscantakealotoftimeandmemory).InPython3however,rangeis
implementedwithxrangeandyouhavetoexplicitlycallthelistfunctionifyouwantto
convertittoalist.

Q28.WhatisPEP8?
Ans.
PEP8isacodingconvention(asetofrecommendations)howtowriteyour
Pythoncodeinordertomakeitmorereadableandusefulforthoseafteryou.

Q29.HowcanIfindmethodsorattributesofanobjectinPython?
Ans.

PythonInterviewQuestions&AnswersBy
fromdev.com
Builtindir()functionofPython,onaninstanceshowstheinstancevariablesas
wellasthemethodsandclassattributesdefinedbytheinstance'sclassandallitsbase
classesalphabetically.Sobyanyobjectasargumenttodir()wecanfindallthe
methods&attributesoftheobjectsclass

Q30.WhatisthestatementthatcanbeusedinPythonifastatementisrequired
syntacticallybuttheprogramrequiresnoaction?
Ans.
pass

Q31.Doyouknowwhatisthedifferencebetweenlistsandtuples?Canyougive
meanexamplefortheirusage?
Ans.
Firstlistaremutablewhiletuplesarenot,andsecondtuplescanbehashede.g.
tobeusedaskeysfordictionaries.Asanexampleoftheirusage,tuplesareusedwhen
theorderoftheelementsinthesequencematterse.g.ageographiccoordinates,"list"
ofpointsinapathorroute,orsetofactionsthatshouldbeexecutedinspecificorder.
Don'tforgetthatyoucanusethemadictionarykeys.Foreverythingelseuselists

Q32.Whatisthefunctionofself?
Ans.
Selfisavariablethatrepresentstheinstanceoftheobjecttoitself.Inmostof
theobjectorientedprogramminglanguages,thisispassedtothemethodsasahidden
parameterthatisdefinedbyanobject.But,inpythonitispassedexplicitly.Itrefersto
separateinstanceofthevariableforindividualobjects.Thevariablesarereferredas
self.xxx.

Q33.HowismemorymanagedinPython?
Ans.
MemorymanagementinPythoninvolvesaprivateheapcontainingall
Pythonobjectsanddatastructures.InterpretertakescareofPythonheapand
theprogrammerhasnoaccesstoit.TheallocationofheapspaceforPython
objectsisdonebyPythonmemorymanager.ThecoreAPIofPythonprovides
sometoolsfortheprogrammertocodereliableandmorerobustprogram.Python
alsohasabuiltingarbagecollectorwhichrecyclesalltheunusedmemory.

Thegcmoduledefinesfunctionstoenable/disablegarbagecollector:
gc
.
enable
() Enablesautomaticgarbagecollection.
gc
.
disable
() Disablesautomaticgarbagecollection
-

PythonInterviewQuestions&AnswersBy
fromdev.com

Q34.Whatis__init__.py?
Ans.
Itisusedtoimportamoduleinadirectory,whichiscalledpackageimport.
Q35.Printcontentsofafileensuringpropererrorhandling?
Ans.
try
:
withopen (
'filename' ,
'r'
) asf:
printf.
read ()
except IOError:
print
"No such file exists"

Q36HowdoweshareglobalvariablesacrossmodulesinPython?
Ans.
Wecancreateaconfigfileandstoretheentireglobalvariabletobe
sharedacrossmodulesinit.Bysimplyimportingconfig,theentireglobalvariable
definedwillbeavailableforuseinothermodules.
ForexampleIwanta,b&ctosharebetweenmodules.
config.py:
a=0
b=0
c=0

module1.py:
importconfig
config .a =1
config .b =2
config .c
=3
print "a ,b &resp .are : ",config .a
,config .
b
,config
.c

output of module1 .py will be


123

Q37.DoesPythonsupportMultithreading?
Ans
.Yes

Medium

PythonInterviewQuestions&AnswersBy
fromdev.com
38.HowdoIgetalistofallfiles(anddirectories)inagivendirectoryinPython?
Ans.Followingisonepossiblesolutiontherecanbeothersimilarones:

importos

fordirname
,dirnames
,filenames
inos
.
walk
(
'.'
):

# print path to all subdirectories first.
forsubdirname
indirnames:
printos
.
path
.
join
(
dirname
,subdirname)

print path to all filenames.


#
forfilename
infilenames:
printos
.
path
.
join
(
dirname
,filename)

Advanced usage:
#

# editing the 'dirnames' list will stop os.walk() from recursing
into there.
if
'.git'
indirnames:

# don't go into any .git directories.
dirnames
.
remove
(
'.git')

39.HowtoappendtoastringinPython?

Ans.Theeasiestwayistousethe+=operator.Ifthestringisalistofcharacter,join()
functioncanalsobeused.

40.HowtoconvertastringtolowercaseinPython?

Ans
.uselower()function.

Example:
s =
'
MYSTRING'
prints.
lower
()

41.HowtoconvertastringtolowercaseinPython?

Ans
.Similartotheabovequestion.useupper()functioninstead.

42.HowtocheckifstringAissubstringofstringB?

PythonInterviewQuestions&AnswersBy
fromdev.com

Ans
.Theeasiestwayistousetheinoperator.

>>>abcinabcdefg
True

43.FindalloccurrencesofasubstringinPython

Ans. Thereisnosimplebuiltinstringfunctionthatdoeswhatyou'relookingfor,but
youcouldusethemorepowerfulregularexpressions:

>>>
[
m
.
start
()
form
inre
.
finditer
(
'test'
,
'test test test test'
)]
[
0
,
5
,
10
,
15] // these are starting indices for the string

44.WhatisGIL?Whatdoesitdo?TalktomeabouttheGIL.Howdoesitimpact
concurrencyinPython?Whatkindsofapplicationsdoesitimpactmorethan
others?

Ans .Python'sGILisintendedtoserializeaccesstointerpreterinternalsfromdifferent
threads.Onmulticoresystems,itmeansthatmultiplethreadscan'teffectivelymake
useofmultiplecores.(IftheGILdidn'tleadtothisproblem,mostpeoplewouldn'tcare
abouttheGILit'sonlybeingraisedasanissuebecauseoftheincreasingprevalence
ofmulticoresystems.)
NotethatPython'sGILisonlyreallyanissueforCPython,thereference
implementation.JythonandIronPythondon'thaveaGIL.AsaPythondeveloper,you
don'tgenerallycomeacrosstheGILunlessyou'rewritingaCextension.Cextension
writersneedtoreleasetheGILwhentheirextensionsdoblockingI/O,sothatother
threadsinthePythonprocessgetachancetorun.

45.Printtheindexofaspecificiteminalist?
Ans.usetheindex()function
>>>["foo","bar",
"baz" ].
index
(
'bar')
1
.

46.Howdoyouiterateoveralistandpullelementindicesatthesametime?

Ans .Youarelookingfortheenumeratefunction.Ittakeseachelementinasequence
(likealist)andsticksit'slocationrightbeforeit.Forexample:
PythonInterviewQuestions&AnswersBy
fromdev.com

>>>my_list
=
[
'a'
,
'b'
,
'c']
>>>list
(
enumerate
(
my_list
))
[(
0
,
'a'
),
(
1
,
'b'
),
(
2
,
'c'
)]

Notethatenumerate()returnsanobjecttobeiteratedover,sowrappingitinlist()just
helpsusseewhatenumerate()produces.

Anexamplethatdirectlyanswersthequestionisgivenbelow

my_list
=
[
'a'
,
'b'
,
'c']

fori
,
char
inenumerate
(
my_list
):
printi
,
char

Theoutputis:

0a
1b
2c


47.HowdoesPython'slist.sortworkatahighlevel?Isitstable?What'sthe
runtime?

Ans.Inearlypythonversions,thesortfunctionimplementedamodifiedversionof
quicksort.However,itwasdeemedunstableandasof2.3theyswitchedtousingan
adaptivemergesortalgorithm.

48.Whatdoesthelistcomprehensiondo:
Ans.
my_list
=[(
x
,
y
,
z
)
forx
inrange
(
1
,
30)
fory
inrange
(
x
,
30
)
forz
in
range
(
y
,
30
)
ifx
**
2
+y
**
2
==z
**
2]

Ans.Itcreatesalistoftuplescalledmy_list,wherethefirst2elementsarethe
perpendicularsidesofrightangletriangleandthethirdvaluezisthehypotenuse.
[(3
,
4
,
5
),
(
5
,
12
,
13
),
(
6
,
8
,
10
),
(
7
,
24
,
25
),
(
8
,
15,
17
),
(
9
,
12
,
15
),
(10
,
24
,
26
),
(
12
,
16
,
20
),
(
15
,
20
,
25
),
(
20
,
21
,
29
)]

PythonInterviewQuestions&AnswersBy
fromdev.com
49.Howcanwepassoptionalorkeywordparametersfromonefunctionto
anotherinPython?
Ans.

Gathertheargumentsusingthe*and**specifiersinthefunction'sparameterlist.This
givesuspositionalargumentsasatupleandthekeywordargumentsasadictionary.
Thenwecanpasstheseargumentswhilecallinganotherfunctionbyusing*and**:

deffun1(
a
,
*
tup
,
**
keywordArg
):

keywordArg
[
'width'
]=
'23.3c'
...
Fun2(
a
,
*
tup
,
**
keywordArg)

50.Explaintheroleofreprfunction.
Ans.

Pythoncanconvertanyvaluetoastringbymakinguseoftwofunctionsrepr()or
str().Thestr()functionreturnsrepresentationsofvalueswhicharehumanreadable,
whilerepr()generatesrepresentationswhichcanbereadbytheinterpreter.
repr()returnsamachinereadablerepresentationofvalues,suitableforanexec
command.

51.PythonHowdoyoumakeahigherorderfunctioninPython?
Ans.
Ahigherorderfunctionacceptsoneormorefunctionsasinputandreturnsanew
function.SometimesitisrequiredtousefunctionasdataTomakehighorderfunction,
weneedtoimportfunctoolsmoduleThefunctools.partial()functionisusedoftenfor
highorderfunction.

52.Whatismap?
Ans.
Thesyntaxofmapis:
map
(
aFunction ,aSequence)
Thefirstargumentisafunctiontobeexecutedforalltheelementsoftheiterablegiven
asthesecondargument.Ifthefunctiongiventakesinmorethan1arguments,then
manyiterablesaregiven.

53.Tellmeaverysimplesolutiontoprinteveryotherelementofthislist?

PythonInterviewQuestions&AnswersBy
fromdev.com
L
=
[
0
,
10
,
20
,
30
,
40
,
50
,
60
,
70
,
80
,
90]

Ans. L
[::
2]

Q54.AreTuplesimmutable?
Ans
.Yes.

Q55.Whyisnotallmemoryfreedwhenpythonexits?

Ans. ObjectsreferencedfromtheglobalnamespacesofPythonmodulesarenot
alwaysdeallocatedwhenPythonexits.Thismayhappeniftherearecircular
references.TherearealsocertainbitsofmemorythatareallocatedbytheClibrarythat
areimpossibletofree(e.g.atoolliketheonePurifywillcomplainaboutthese).Python
is,however,aggressiveaboutcleaningupmemoryonexitanddoestrytodestroyevery
singleobject.IfyouwanttoforcePythontodeletecertainthingsondeallocation,you
canusetheatexitmoduletoregisteroneormoreexitfunctionstohandlethose
deletions.

Q56.WhatisJavaimplementationofPythonpopularlyknow?

Ans. Jython.

Q57.WhatisusedtocreateunicodestringsinPython?

Ans.
Addubeforethestring.
umystring

Q58.Whatisadocstring?
Ans.
docstringisthedocumentationstringforafunction.Itcanbeaccessedby
function_name.__doc__

Q59.Giventhelistbelowremovetherepetitionofanelement.

Ans.
words =
['
one','one','
two ','three',
'
three ',
'two']
Abadsolutionwouldbetoiterateoverthelistandcheckingforcopiessomehowand
thenremovethem!

PythonInterviewQuestions&AnswersBy
fromdev.com
Averygoodsolutionwouldbetousethesettype.InaPythonset,duplicatesarenot
allowed.
So,list(set(words))wouldremovetheduplicates.

Q60.Printthelengthofeachlineinthefilefile.txtnotincludingany
whitespacesattheendofthelines?

Ans.
withopen ("filename.txt" ,
"r")asf1:
printlen
(
f1.readline ().
rstrip ())
rstrip()isaninbuiltfunctionwhichstripsthestringfromtherightendofspacesortabs
(whitespacecharacters).

Q61.Whatiswrongwiththecode?
func
([1
,
2
,
3
])
# explicitly passing in a list
func
()
# using a default empty list

deffunc
(
n=
[]):
#do something with n

printn
Ans.
ThiswouldresultinaNameError.Thevariablenislocaltofunctionfuncand
cantbeaccessesdoutside.So,printingitwontbepossible.

Q62.Whatdoesthebelowmean?

s=a+[+b+:+c+]
Ans.
seemslikeastringisbeingconcatenated.Nothingmuchcanbesaidwithout
knowingtypesofvariablesa,b,c.Also,ifallofthea,b,carenotoftypestring,
TypeErrorwouldberaised.Thisisbecauseofthestringconstants([,])usedinthe
statement.

Q63.WhatarePythondecorators?

Ans.
APythondecoratorisaspecificchangethatwemakeinPythonsyntaxtoalter
functionseasily.

PythonInterviewQuestions&AnswersBy
fromdev.com
Q64.WhatisnamespaceinPython?

Ans.
InPython,everynameintroducedhasaplacewhereitlivesandcanbehooked
for.Thisisknownasnamespace.Itislikeaboxwhereavariablenameismappedto
theobjectplaced.Wheneverthevariableissearchedout,thisboxwillbesearched,to
getcorrespondingobject.

Q65.Explaintheroleofreprfunction.

Ans.
Pythoncanconvertanyvaluetoastringbymakinguseoftwofunctionsrepr()or
str().Thestr()functionreturnsrepresentationsofvalueswhicharehumanreadable,
whilerepr()generatesrepresentationswhichcanbereadbytheinterpreter.repr()
returnsamachinereadablerepresentationofvalues,suitableforanexeccommand.
Followingcodesniipetsshowsworkingofrepr()&str():

deffun():
y
=
2333.3
x
=
str
(y)
z
=
repr(
y)
print" y :",y
print"str(y) :" ,x
print"repr(y):" ,z
fun
()
-------------
output
y:
2333.3
str
(
y
):2333.3
repr
(
y)
:2333.3000000000002

Q66.WhatisLISTcomprehensionsfeaturesofPythonusedfor?

Ans.
LISTcomprehensionsfeatureswereintroducedinPythonversion2.0,itcreates
anewlistbasedonexistinglist.Itmapsalistintoanotherlistbyapplyingafunctionto

PythonInterviewQuestions&AnswersBy
fromdev.com
eachoftheelementsoftheexistinglist.Listcomprehensionscreateslistswithoutusing
map(),filter()orlambdaform.

Q67.ExplainhowtocopyanobjectinPython.?

Ans.
Therearetwowaysinwhichobjectscanbecopiedinpython.Shallowcopy&
Deepcopy.ShallowcopiesduplicateasminuteaspossiblewhereasDeepcopies
duplicateeverything.Ifaisobjecttobecopiedthen
copy.copy(a)returnsashallowcopyofa.
copy.deepcopy(a)returnsadeepcopyofa.

Q68.DescribehowtosendmailfromaPythonscript?

Ans.
ThesmtplibmoduledefinesanSMTPclientsessionobjectthatcanbeusedto
sendmailtoanyInternetmachine.
Asampleemailisdemonstratedbelow.
importsmtplib
SERVER=smtplib.SMTP(smtp.server.domain)
FROM=sender@mail.com
TO=["user@mail.com"]#mustbealist
SUBJECT="Hello!"
TEXT="ThismessagewassentwithPython'ssmtplib."
#Mainmessage
message="""
From:Lincoln<sender@mail.com>
To:CarreerRideuser@mail.com
Subject:SMTPemailmsg
Thisisatestemail.Acknowledgetheemailbyresponding.
"""%(FROM,",".join(TO),SUBJECT,TEXT)
server=smtplib.SMTP(SERVER)
server.sendmail(FROM,TO,message)
server.quit()

Q69.WhichofthelanguagesdoesPythonresembleinitsclasssyntax?

Ans
.c++.

PythonInterviewQuestions&AnswersBy
fromdev.com
Q70.PythonHowtocreateamultidimensionallist?

Ans. TherearetwowaysinwhichMultidimensionallistcanbecreated:
BydirectinitializingthelistasshownbelowtocreatemyListbelow.
>>>
myList = [[
227,122,223
],[
222
,321,192
],[
21,122
,
444
]]
>>>
printmyList [
0]
>>>
printmyList [
1][
2]
____________________
Output
[227,122,223]
192

Thesecondapproachistocreatealistofthedesiredlengthfirstandthenfillineach
elementwithanewlycreatedlistsdemonstratedbelow:

>>>
list
=[0
]*3
>>>
fori inrange(3
):
>>>list[
i
]=[
0]*2
>>>
fori inrange (
3
):
>>>
forj inrange (
2
):
>>>list[
i
][
j
]=i+j
>>>
printlist
__________________________
Output
[[
0
,
1
],[
1
,
2],
[2
,3
]]

Q71.Explainthedisadvantagesofpython

Ans. DisadvantagesofPythonare:Pythonisn'tthebestformemoryintensivetasks.
Pythonisinterpretedlanguage&isslowcomparedtoC/C++orJava.

Q72.ExplainhowtomakeFormsinpython.

Ans. AspythonisscriptinglanguageformsprocessingisdonebyPython.Weneedto
importcgimoduletoaccessformfieldsusingFieldStorageclass.

EveryinstanceofclassFieldStorage(for'form')hasthefollowingattributes:

form.name:Thenameofthefield,ifspecified.
PythonInterviewQuestions&AnswersBy
fromdev.com
form.filename:IfanFTPtransaction,theclientsidefilename.
form.value:Thevalueofthefieldasastring.
form.file:fileobjectfromwhichdatacanberead.
form.type:Thecontenttype,ifapplicable.
form.type_options:Theoptionsofthe'contenttype'lineoftheHTTPrequest,returned
asadictionary.
form.disposition:Thefield'contentdisposition'Noneifunspecified.
form.disposition_options:Theoptionsfor'contentdisposition'.
form.headers:AlloftheHTTPheadersreturnedasadictionary.

Acodesnippetofformhandlinginpython:

importcgi

form
=cgi.
FieldStorage
()
if
not(
form
.
has_key
(
"name"
)
andform.
has_key
(
"age"
)):
print
"<H1>Name & Age not Entered</H1>"
print
"Fill the Name & Age accurately."
return
print
"<p>name:",form
[
"name"
].
value
print
"<p>Age:",form
[
"age"
].
value

Q73. Explainhowpythonisinterpreted.

Ans. Pythonprogramrunsdirectlyfromthesourcecode.EachtypePythonprograms
areexecutedcodeisrequired.Pythonconvertssourcecodewrittenbytheprogrammer
intointermediatelanguagewhichisagaintranslateditintothenativelanguage
machinelanguagethatisexecuted.SoPythonisanInterpretedlanguage.

Q74.Explainhowtooverloadconstructors(ormethods)inPython.?

Ans. _init__()isafirstmethoddefinedinaclass.whenaninstanceofaclassis
created,pythoncalls__init__()toinitializetheattributeoftheobject.
Followingexampledemonstratesfurther:

class
Employee:

def__init__
(
self
,name
,empCode
,
pay
):
self
.
name
=
name
PythonInterviewQuestions&AnswersBy
fromdev.com
self
.
empCode
=empCode
self
.
pay
=
pay

e1
=
Employee
(
"Obama"
,
99
,
30000.00)

e2
=
Employee
(
"Clinton"
,
100,
60000.00)
print
(
"Employee Details:")

print
(
" Name:"
,
e1
.
name
,
"Code:"
,e1
.
empCode
,
"Pay:"
,e1
.
pay)
print
(
" Name:"
,
e2
.
name
,
"Code:"
,e2
.
empCode
,
"Pay:"
,e2
.
pay)
---------------------------------------------------------------
Output

Employee
Details:
(
' Name:'
,
'Obama',
'Code:'
,
99
,
'Pay:'
,
30000.0)
(
' Name:'
,
'Clinton',
'Code:'
,
100
,
'Pay:'
,
60000.0)

Q75.Howdowemakepythonscriptsexecutable?

Ans. Pythonscriptscanbeexecutedintwoways:
Supposewewanttoexecutescript1.py
Wecanopenthescript1.pyinIDEeditor&runthescriptinthefrontmostwindowofthe
pythonIDEbyhittingtherunallbutton.
SecondwayisusingcommandpromptbymakingsurePATHissetappropriately
directlytypescriptnameelsetype

>>>pythonscript1.py

Advanced

76.Wehavethefollowingcodewithunknownfunctionf()

forx
inf
(
5
):
printx,

PythonInterviewQuestions&AnswersBy
fromdev.com
Outputlookslikethis
0
182764
Writethefunctionf()?
Ans
.
Followingisapossibleimplementationoff()

deff
(
n
):
forx inrange
(
n
):
yieldx
**
3

77.WhatisPicklingandunpickling?
Ans.
Pickleisastandardmodulewhichserializes&deserializesapython
objectstructure.picklemoduleacceptsanypythonobjectconvertsitintoastring
representation&dumpsitintoafile(byusingdump()function)whichcanbeused
later,processiscalledpickling.Whereasunpicklingisprocessofretrieving
originalpythonobjectfromthestoredstringrepresentationforuse.

78.WhataresomecommonusesofPicklinginPython?

Ans.
(OpenEndedQuestion,apossibleanswerisgivenbelow)

Thesearesomeoftheusecases,therecanbemanyother:

1)savingaprogram'sstatedatatodisksothatitcancarryonwhereitleftoffwhen
restarted(persistence)

2)sendingpythondataoveraTCPconnectioninamulticoreordistributedsystem
(marshalling)

3)storingpythonobjectsinadatabase

4)convertinganarbitrarypythonobjecttoastringsothatitcanbeusedasadictionary
key(e.g.forcaching&memoization).

PythonInterviewQuestions&AnswersBy
fromdev.com
Therearesomeissueswiththelastonetwoidenticalobjectscanbepickledandresult
indifferentstringsoreventhesameobjectpickledtwicecanhavedifferent
representations.Thisisbecausethepicklecanincludereferencecountinformation.

79.Whydolistcomprehensionswritetotheloopvariable,butgeneratorsdon't?
Ans.
ThiswasabuginPython2.xandisfixedinPython3.x.

78.Whatisthelengthofyourlargestpythoncode?Canyoupleasedescribethe
project?

Ans.

Itsaveryopenendedquestion.Theanswerisdifficulttopredict.Pythonbeginnerswill
havewrittensmallcodes(basicscripts).MoreadvanceduserswouldhaveusedOOPin
pythonandtheircodeswillrangefroma200to800linesofcode.Advanceduserswill
havewrittenlargercodesupto2000or3000linesofcodes.
Beyondthispoint,codesaregenerallywritteningroupstomeetadeadline.

79.Intheaboveproject,wereyoualoneorwereyouingroupofdevelopers?If
so,howmany?

Ans.(OpenEndedQuestion)Dependsonthepersonalexperienceoftheperson.A
goodsuccessfulprojectbeingpartoftheteamindicatesthatthepersonisagoodteam
player.

80.Whatwasyourcontributiontotheaboveproject?
Ans.
(OpenendedQuestion).Intervieweesanswerdependsonthepersonal
experiencewhichcouldinvolvewritingamodulefortheproject,testingor
documentationetc.

81.Howoftendoyoucommentyourcode?Canyouwriteanyonewhoreadsyour
coderecogniseandunderstandyourvariablenames?

Ans.
(OpenEndedQuestion)Agoodprogrammerwoulddomediumamountof
commentingfrequentlymakinguseofpythondocstrings.

Q82.WhydoesPythonhaveamaximumrecursiondepth?
PythonInterviewQuestions&AnswersBy
fromdev.com

Ans.Recursionrequiresspaceonthecallstack,whichislimitedinsize.Codewhich
usedtoomanylevelsofrecursionwillgiveanerrorcalledastackoverflow.Python
stackframesarealsoquitebiginsizewhichfurthermakestheissuemorecrucial.

Q83.CanyoumodifythemaximumdepthforarecursivefunctioninPython?If
yeshow?

Ans
.Yes

sys
.
setrecursionlimit
(
1500) // Generally the length is 1000 stack
frame

Q84.Whatistailrecursion?

Ans .Intraditionalrecursion,thetypicalmodelisthatyouperformyourrecursivecalls
first,andthenyoutakethereturnvalueoftherecursivecallandcalculatetheresult.In
thismanner,youdon'tgettheresultofyourcalculationuntilyouhavereturnedfrom
everyrecursivecall.

Intailrecursion,youperformyourcalculationsfirst,andthenyouexecutetherecursive
call,passingtheresultsofyourcurrentsteptothenextrecursivestep.Thisresultsin
thelaststatementbeingintheformof"(return(recursivefunctionparams))".Basically,
thereturnvalueofanygivenrecursivestepisthesameasthereturnvalueofthenext
recursivecall.

Theconsequenceofthisisthatonceyouarereadytoperformyournextrecursivestep,
youdon'tneedthecurrentstackframeanymore.Thisallowsforsomeoptimization.In
fact,withanappropriatelywrittencompiler,youshouldneverhaveastackoverflow
snickerwithatailrecursivecall.Simplyreusethecurrentstackframeforthenext
recursivestep.

Q85.Doespythonperformtailrecursionoptimization?

Ans
.Noitdoesnt.PythonfounderGuidovanRossumwroteinhisblog:

IrecentlypostedanentryinmyPythonHistoryblogontheoriginsofPython's
functionalfeatures.Asideremarkaboutnotsupportingtailrecursionelimination(TRE)
immediatelysparkedseveralcommentsaboutwhatapityitisthatPythondoesn'tdo
this,includinglinkstorecentblogentriesbyotherstryingto"prove"thatTREcanbe
PythonInterviewQuestions&AnswersBy
fromdev.com
addedtoPythoneasily.Soletmedefendmyposition(whichisthatIdon'twantTREin
thelanguage).Ifyouwantashortanswer,it'ssimplyunpythonic.

Q86.WhatisametaclassinPython?

Ans.Ametaclassistheclassofaclass.Likeaclassdefineshowaninstanceofthe
classbehaves,ametaclassdefineshowaclassbehaves.Aclassisaninstanceofa
metaclass.

Q87.HowtogetclassnameofaninstanceinPython?

Ans.
instance
.
__class__
.
__name__

Q88.DescribehowtouseSessionsforWebpython?
Ans.
Sessionsaretheserversideversionofcookies.Whileacookiepreservesstateatthe
clientside,sessionspreservesstateatserverside.

Thesessionstateiskeptinafileorinadatabaseattheserverside.Eachsessionis
identifiedbyauniquesessionid(SID).Tomakeitpossibletotheclienttoidentify
himselftotheservertheSIDmustbecreatedbytheserverandsenttotheclient
whenevertheclientmakesarequest.

Q89.Multiplyallelementsofalistwithoutwritingaloop.
Ans.
from operatorimportmul
reduce (
mul
,range (
1
,
10
))

Q90.Whatisasingletondesignpattern?
Ans.
Inthesingletondesignpatternthatlimitsthenumberofinstancesofaclass(normallyto
1).

Q91.WriteaprogramtoshowtheusageofsingletonpatterninPython?
Ans.
Somecodealongthefollowinglineswoulddo.

Singleton
&
Singleton
::
Handle
()
{
if
(
!
psingle
){
PythonInterviewQuestions&AnswersBy
fromdev.com
psingle
=
new
Singleton;
}
return
*
psingle;
}

Q92.Canweusesingletonfunctionalitywithoutmakingasingletonclassin
Python?
Ans.
Amodulewithfunctions(andnotaclass)wouldservewellasasingleton.Allits
variableswouldbeboundtothemodule,whichcouldnotbeinstantiatedrepeatedly
anyways.

Q93.Doespythonsupportdatabaseprogramming?
Ans.
Yes.

Q94.WhatisMySQLdb?
Ans.MySQLdbisaninterfaceforconnectingtoaMySQLdatabaseserverfromPython.
ItimplementsthePythonDatabaseAPIv2.0andisbuiltontopoftheMySQLCAPI.

Q95.HowwouldyoucheckifMySQLdbisinstalled?
Ans.TryimportingitwithimportMySQLdb.Anerrorwouldindicatethatitsnot
installed.

Q96.WriteascripttoconnecttoMySqldatabaseusingPython.
Ans.

#!/usr/bin/python

import
MySQLdb

# Open database connection


db
=
MySQLdb
.
connect
(
"localhost"
,
"username"
,
"password"
,
"databasename"
)

# prepare a cursor object using cursor() method


cursor
=db
.
cursor
()

# execute SQL query using execute() method.


cursor
.
execute
(
"SELECT VERSION()")

PythonInterviewQuestions&AnswersBy
fromdev.com
# Fetch a single row using fetchone() method.
data
=cursor
.
fetchone
()

print
"Database version : %s "
%data

# disconnect from server


db
.
close
()

Ifaconnectionisestablishedwiththedatasource,thenaConnectionObjectisreturned
andsavedintodbforfurtheruse,otherwisedbissettoNone.Next,dbobjectisusedto
createacursorobject,whichinturnisusedtoexecuteSQLqueries.Finally,before
comingout,itensuresthatdatabaseconnectionisclosedandresourcesarereleased.

Q97.Howdoyoudisconnectfromthedatabase?
Ans.Usetheclose()method.db.close()closestheconnectionfromthedatabaselikein
thescriptabove.

Q98.DoesPythonsupportenums?
Ans.
Python3.4does.EarlierversionsofPythondont.

Q99.HowdoyouuseenumsinPython?
Ans.
Thefollowingcodewoulddo.

from
enum
import
Enum
Game
=
Enum
(
'Game'
,
'hockey football rugby')

Q100.Booleanshave2possiblevalues.Aretheretypesinpythonthathave3
possiblevalues?
Ans.
Yes.Thisfunctionalitycanbeachievedbyenums.refertotheexampleinprevious
enumquestion.

PythonInterviewQuestions&AnswersBy
fromdev.com
Further Reading and References For Python Developers

80+BestFreePythonTutorials,eBooks&PDFToLearnProgrammingOnline

7BestPythonBooksToLearnProgramming

10+PopularPythonFrameworksForWebDevelopment

PythonInterviewQuestions&AnswersBy
fromdev.com

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy