KEMBAR78
150 Python Interview Q&A | PDF | Class (Computer Programming) | Inheritance (Object Oriented Programming)
0% found this document useful (0 votes)
2 views57 pages

150 Python Interview Q&A

Uploaded by

priyayadav199521
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views57 pages

150 Python Interview Q&A

Uploaded by

priyayadav199521
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

PYTHON

Top 150 Python Interview


Questions & Answers
1. What is the Difference Between a Shallow Copy and
aDeep Copy?

Deepcopycreatesadifferentobjectandpopulatesitwiththechildobjectsoftheoriginalobject.Therefore,

changes inthe original objectare not reflectedin the copy.

copy.deepcopy()createsaDeepCopy.

Ashallowcopycreatesadifferentobjectandpopulatesitwiththereferencesofthechildobjectswithintheo
riginalobject.Therefore,changes intheoriginalobjectare reflectedinthecopy.

copy.copycreatesaShallowCopy.

2. How Is Multithreading Achieved in Python?

Multithreadingusuallyimpliesthatmultiplethreadsareexecutedconcurrently.ThePythonGlobalInterpr
eter Lock doesn't allow more than one thread to hold the Python interpreter at thatparticular point
of time. So, multithreading in Python is achieved through context switching. It isquitedifferent
frommultiprocessing which opensup multiple processesacross multiplethreads.

3. Discuss Django Architecture.

HereyoucanalsofindacomprehensiveguideonPythonDjangoTutorialthatisveryeasyto
understand.

Django is a web service used to build your web pages. Its architecture is as shown:

• Template:thefrontendofthewebpage

• Model:thebackendwherethedataisstored

• View:ItinteractswiththemodelandtemplateandmapsittotheURL

• Django:servesthepagetotheuser
4. What Advantage Does the Numpy Array Have over
aNested List?

Numpy is written in C so that all its complexities are backed into a simple-to-use module. Lists,
onthe other hand, are dynamically typed. Therefore, Python must check the data type of
eachelement every time it uses it. This makes Numpy arrays much faster than lists.

Numpyhasalotofadditionalfunctionalitythatthelistdoesn’toffer;forinstance,alotofthingscanbe
automated in Numpy.

5. What are Pickling and Unpickling?

Pickling Unpickling

• ConvertingabytestreamtoaPythonobjecthier
• ConvertingaPythonobjecthierarchytoabyt archyiscalledunpickling
estreamiscalledpickling • Unpicklingisalsoreferredtoasde
• Picklingisalsoreferredtoasserialization serialization

If you just created a neural network model, you can save that model to your hard drive,
pickleit, and then unpickle it to bring it back into another software program or use it at a later
time.

The following are some of the most frequently asked Python interview questions

6. How is Memory managed in Python?

Python has a private heap space that stores all the objects. The Python memory
managerregulates various aspects of this heap, such as sharing, caching, segmentation,
andallocation. The user has no control over the heap; only the Python interpreter has
access.

7. AreArgumentsinPythonPassedbyValueorbyReference?

Arguments are passed in Python by a reference. This means that any changes made
withina function are reflected in the original object.
Consider two sets of code shown below:

In the first example, we only assigned a value to one element of ‘l’, so the output is [3, 2, 3, 4].

In the second example, we have created a whole new object for ‘l’. But, the values [3, 2, 3,
4]don’t show up in the output as it is outside the definition of the function.

8. HowWouldYouGenerateRandomNumbersinPython?

TogeneraterandomnumbersinPython,youmustfirstimporttherandommodule.The

random() function generates a random float value between 0 & 1.

> random.random()

The randrange() function generates a random number within a given

range.Syntax: randrange(beginning, end, step)

Example - > random.randrange(1,10,2)

9. What Does the // Operator Do?

In Python, the / operator performs division and returns the quotient in the

float.For example: 5 / 2 returns 2.5

The//operator,ontheotherhand,returnsthequotientinaninteger.For

example: 5 // 2 returns 2
10. What Does the ‘is’ Operator Do?

The ‘is’ operator compares the id of the two

objects.list1 = [1,2,3]

list2 =

[1,2,3]list3 =

list1

list1==list2=>Truelis

t1 is list2 =>

Falselist1islist3=>Tr

ue

11. What Is the Purpose of the Pass Statement?

The pass statement is used when there's a syntactic but not an operational requirement.
Forexample - The program below prints a string ignoring the spaces.

var="Si mplilea

rn"for i in var:

if i==" ":

pass

else:

print(i,end="")

Here,thepassstatementrefersto‘noactionrequired.’
12. HowWillYouCheckIfAlltheCharactersinaStringAre
Alphanumeric?

Python has an inbuilt method isalnum() which returns true if all characters in the string
arealphanumeric.

Example -

>>

"abcd123".isaln

um()Output:True

>>”abcd@123#”.isalnum()

Output: False

Another way is to use regex as shown.

>>import re

>>bool(re.match(‘[A-Za-z0-

9]+$','abcd123’))Output:True

>> bool(re.match(‘[A-Za-z0-

9]+$','abcd@123’))Output: False

13. HowWillYouMergeElementsinaSequence?

There are three types of sequences in Python:

• Lists

• Tuples

• Strings

ExampleofLists-
>>l1=[1,2,3]

>>l2=[4,5,6]

>>l1+l2

Output: [1,2,3,4,5,6]

ExampleofTuples-

>>t1=(1,2,3)

>>t2=(4,5,6)

>>t1+t2

Output: (1,2,3,4,5,6)

Example of String -

>>s1=“Simpli”

>>s2=“learn”

>>s1+s2

Output: ‘Simplilearn’

14. HowWouldYouRemoveAllLeadingWhitespaceinaString?

Python provides the inbuilt function lstrip() to remove all leading spaces from a string.

>>“ Python”.lstrip

Output:Python
15. HowWouldYouReplaceAllOccurrencesofaSubstringwith
a New String?

The replace() function can be used with strings for replacing a substring with a given

string.Syntax:

str.replace(old,new,count)

replace() returns a new string without modifying the original

string.Example -

>>"Hey John. How are you,

John?".replace(“john",“John",1)Output: “Hey John. How are

you, John?

16. WhatIstheDifferenceBetweenDelandRemove()onLists?

del remove()

• delremovesallelementsofalistwithinagive • remove()removesthefirstoccurrenceofapar
nrange ticularcharacter

• Syntax:dellist[start:end] • Syntax:list.remove(element)

Here is an example to understand the two statements -

>>lis=[‘a’, ‘b’, ‘c’, ‘d’]

>>del lis[1:3]

>>lis

Output: [“a”,”d”]

>>lis=[‘a’,‘b’,‘b’,‘d’]
>>lis.remove(‘b’)

>>lis

Output: [‘a’, ‘b’, ‘d’]

Note that in the range 1:3, the elements are counted up to 2 and not 3.

17. HowDoYouDisplaytheContentsofaTextFileinReve
rse Order?

Youcandisplaythecontentsofatextfileinreverseorderusingthefollowingsteps:

• Openthefileusingtheopen()function

• Storethecontentsofthefileinalist

• Reversethecontentsofthelist

• Runaforlooptoiteratethroughthelist

18. Differentiate Between append() and extend().

append() extend()

• append()addsanelementtotheendoftheli • extend()addselementsfromaniterabletot
st heendofthelist
• Example- • Example-
>>lst=[1,2,3] >>lst=[1,2,3]

>>lst.extend([4,5,6])
>>lst.append(4)

>>lst
>>lst

Output:[1,2,3,4]
Output:[1,2,3,4,5,6]
19. WhatIstheOutputofthebelowCode?JustifyYourAnswer.

>>defaddToList(val,list=[]):

>>list.append(val)

>>returnlist

>>list1=addToList(1)

>>list2=addToList(123,[])

>>list3=addToList('a’)

>>print ("list1 = %s" % list1)

>>print ("list2 = %s" % list2)

>>print ("list3 = %s" %

list3)Output:

list1 =

[1,’a’]list2 =

[123]lilst3=[

1,’a’]

Notethatlist1andlist3areequal.WhenwepassedtheinformationtotheaddToList,wediditwithout a
second value. If we don't have an empty list as the second value, it will start with anempty
list, which we then append. For list2, we appended the value to an empty list, so itsvalue
becomes [123].

For list3, we're adding ‘a’ to the list. Because we didn't designate the list, it is a shared
value.It means the list doesn’t reset and we get its value as [1, ‘a’].

Remember that a default list is created only once during the function and not during its
callnumber.
20. WhatIstheDifferenceBetweenaListandaTuple?

Lists are mutable while tuples are

immutable.Example:

List

>>lst = [1,2,3]

>>lst[2] = 4

>>lstOutput:[

1,2,4]Tuple

>>tpl = (1,2,3)

>>tpl[2] = 4

>>tpl

Output:TypeError:'tuple'

the object does not support item assignment

Thereisanerrorbecauseyoucan'tchangethetuple123into124.Youhavetocompletely
reassign the tuple to a new value.

21. What Is Docstring in Python?

This is one of the most frequently asked Python interview questions

Docstrings are used in providing documentation to various Python modules, classes,


functions,and methods.

Example-
def add(a,b):

" " "This function adds two numbers." "

"sum=a+b

return

sumsum=add(1

0,20)

print("Accessing docstring method 1:",add. doc

)print("

Accessing docstring method 2:",end="")help(add)

Output -

Accessing docstring method 1: This function adds two

numbers.Accessing docstring method 2: Help on function add-in module

main

:add(a,

b)

This function adds two numbers.

22. HowDoYouUsePrint()WithouttheNewline?

The solution to this depends on the Python version you are

using.Python v2

>>print(“Hi. ”),

>>print(“How are
you?”)Output: Hi. How

are you?Pythonv3
>>print(“Hi”,end=“ ”)

>>print(“How are

you?”)Output:Hi.Howare

you?

23. HowDoYouUsetheSplit()FunctioninPython?

Thesplit()functionsplitsastringintoseveralstringsbasedonaspecificdelimiter.Syntax

string.split(delimiter,

max)Where:

the delimiter is the character based on which the string is split. By default it is

space.max is the maximum number of splits

Example -

>>var=“Red,Blue,Green,Orange”

>>lst=var.split(“,”,2)

>>print(lst)

Output:

[‘Red’,’Blue’,’Green, Orange’]

Here, we have a variable var whose values are to be split with commas. Note that ‘2’
indicatesthat only the first two values will be split.

24. Is Python Object-oriented or Functional Programming?

Pythonisconsideredamulti-paradigmlanguage.
Python follows the object-oriented paradigm

• Pythonallowsthecreationofobjectsandtheirmanipulationthroughspecificmethods

• ItsupportsmostofthefeaturesofOOPSsuchasinheritanceandpolymorphism

Python follows the functional programming paradigm

• Functionsmaybeusedasthefirst-classobject

• PythonsupportsLambdafunctionswhicharecharacteristicofthefunctionalparadigm

25. WriteaFunctionPrototypeThatTakesaVariableNu
mber of Arguments.

The function prototype is as follows:

def function_name(*list)

>>def fun(*var):

>> for i

invar:print(i)

>>fun(1)

>>fun(1,25,6)

In the above code, * indicates that there are multiple arguments of a variable.

26. What Are *args and *kwargs?

*args

• Itisusedinafunctionprototypetoacceptavaryingnumberofarguments.

• It'saniterableobject.

• Usage-deffun(*args)

*kwargs
• Itisusedinafunctionprototypetoacceptthevaryingnumberofkeywordedarguments.

• It'saniterableobject

• Usage-deffun(**kwargs):

fun(colour=”red”.units=2)

27. “In Python, Functions Are First-class Objects.”


WhatDoYou Inferfrom This?

Itmeansthatafunctioncanbetreatedjustlikeanobject.Youcanassignthemtovariables,orpassthema
sargumentstootherfunctions.Youcanevenreturnthemfromotherfunctions.

28. What Is the Output Of: Print( name )?JustifyYourAnswer.

name is a special variable that holds the name of the current module. Program execution
startsfromthemainorcodewith0indentations.Thus,name hasavaluemain in the above
case.Ifthefileisimportedfromanothermodule,name holdsthenameofthismodule.

29. What Is a Numpy Array?

Anumpyarrayisagridofvalues,allofthesametype,andisindexedby a tuple ofnon-negative integers.


The number of dimensions determines the rank of the array. The shapeof an array is a tuple of
integers giving the size of the array along each dimension.

30. What Is the Difference Between Matrices and Arrays?

Matrices Arrays

• Amatrixcomesfromlinearalgebraandisatwo- • Anarrayisasequenceofobjectsofsimil
dimensionalrepresentationofdata ardatatype
• It comes with a powerful set of • Anarraywithinanotherarrayforms
mathematicaloperationsthatallowyoutoman amatrix
ipulatethe
dataininterestingways
31. HowDoYouGetIndicesofNMaximumValuesinaNum
py Array?

>>import numpy as np

>>arr=np.array([1, 3, 2, 4, 5])

>>print(arr.argsort()[-N:][::-1])

32. HowWouldYouObtaintheRes_setfromtheTrai
n_setandtheTest_setfromBelow?

>>train_set=np.array([1, 2, 3])

>>test_set=np.array([[0, 1, 2], [1, 2, 3])

Res_set[[1,2,3],[0,1,2],[1,2,3]]

Choose the correct option:

1. res_set=train_set.append(test_set)

2. res_set=np.concatenate([train_set,test_set]))

3. resulting_set=np.vstack([train_set,test_set])

4. Noneofthese

Here, options a and b would both do horizontal stacking, but we want vertical stacking. So,
optionc is the right statement.

resulting_set = np.vstack([train_set, test_set])

33. HowWouldYouImportaDecisionTreeClassifierinSkle
arn? Choose the Correct Option.

1. fromsklearn.decision_treeimportDecisionTreeClassifier

2. fromsklearn.ensembleimportDecisionTreeClassifier

3. fromsklearn.treeimportDecisionTreeClassifier
4. Noneofthese

Answer-3.fromsklearn.treeimportDecisionTreeClassifier

34. You Have Uploaded the Dataset in csv Format


onGoogleSpreadsheetandSharedItPublicly.HowCanYouA
ccess This in Python?

Wecanusethefollowingcode:

>>link = https://docs.google.com/spreadsheets/d/...

>>source = StringIO.StringIO(requests.get(link).content))

>>data = pd.read_csv(source)

35. WhatIstheDifferenceBetweentheTwoDataSeriesGiv
en Below?

df[‘Name’] and df.loc[:, ‘Name’], where:

df = pd.DataFrame(['aa', 'bb', 'xx', 'uu'], [21, 16, 50, 33], columns = ['Name',

'Age'])Choose the correct option:

1. 1istheviewoftheoriginaldataframeand2isacopyoforiginaldataframe

2. 2istheviewoftheoriginaldataframeand1isacopyoforiginaldataframe

3. Botharecopiesoforiginaldataframe

4. Bothareviewsoforiginaldataframe

Answer - 3. Both are copies of the original dataframe.

36. YouGettheError“temp.Csv”WhileTryingtoReadaFileUsin
g Pandas. Which of the Following Could Correct It?
Error:
Traceback(mostrecentcalllast):File"<input>",line1,in<module>UnicodeEncodeError:

'ascii'codeccan'tencodeacharacter.Ch

oose the correct option:

1. pd.read_csv(“temp.csv”,compression=’gzip’)

2. pd.read_csv(“temp.csv”,dialect=’str’)

3. pd.read_csv(“temp.csv”,encoding=’utf-8′)

4. Noneofthese

Theerrorrelatestothedifferencebetweenutf-

8codingandUnicode.Sooption3.pd.read_csv(“temp.csv”,encoding=’utf-

8′)cancorrectit.

37. HowDoYouSetaLineWidthinthePlotGivenBelow?

>>import matplotlib.pyplot as plt

>>plt.plot([1,2,3,4])

>>plt.show()

Choose the correct option:

1. Inlinetwo,writeplt.plot([1,2,3,4],width=3)

2. Inlinetwo,writeplt.plot([1,2,3,4],line_width=3

3. Inlinetwo,writeplt.plot([1,2,3,4],lw=3)

4. Noneofthese
Answer - 3. In line two, write plt.plot([1,2,3,4], lw=3)

38. HowWouldYouResettheIndexofaDataframetoaGive
n List? Choose the Correct Option.

1. df.reset_index(new_index,)

2. df.reindex(new_index,)

3. df.reindex_like(new_index,)

4. Noneofthese

Answer - 3. df.reindex_like(new_index,)

39. HowCanYouCopyObjectsinPython?

The function used to copy objects in Python are:

copy.copyforshallowcopyandco

py.deepcopy()fordeepcopy

40. What Is the Difference Between range()


andxrange() Functions in Python?

xrange()
range()

• xrange returns an xrange object


• rangereturnsaPythonlistobject

41. HowCanYouCheckWhetheraPandasDataframeIsEm
pty or Not?

The attribute df.empty is used to check whether a pandas data frame is empty or not.
>>importpandasaspd
>>df=pd.DataFrame({A:[]})

>>df.empty

Output:True

42. WriteaCodetoSortanArrayinNumpybythe(N-
1)th Column.

This can be achieved by using argsort() function. Let us take an array X; the code to sort
the(n-1)th column will be x[x [: n-2].argsoft()]

The code is as shown below:

>>import numpy as np

>>X=np.array([[1,2,3],[0,5,2],[2,3,4]])

>>X[X[:,1].argsort()]Output:array([[

1,2,3],[0,5,2],[2,3,4]])

43. HowDoYouCreateaSeriesfromaList,NumpyArra
y,andDictionary?

The code is as shown:

>> #Input

>>import numpy as np

>>import pandas as pd

>>mylist = list('abcedfghijklmnopqrstuvwxyz’)

>>myarr = np.arange(26)

>>mydict = dict(zip(mylist, myarr))


>> #Solution

>>ser1 = pd.Series(mylist)

>>ser2 = pd.Series(myarr)

>>ser3 = pd.Series(mydict)

>>print(ser3.head())

44. HowDoYouGettheItemsNotCommontoBothSeriesA
and Series B?

>> #Input

>>import pandas as pd

>>ser1 = pd.Series([1, 2, 3, 4, 5])

>>ser2 = pd.Series([4, 5, 6, 7, 8])

>> #Solution

>>ser_u = pd.Series(np.union1d(ser1, ser2)) # union

>>ser_i = pd.Series(np.intersect1d(ser1, ser2)) # intersect

>>ser_u[~ser_u.isin(ser_i)]

45. HowDoYouKeepOnlytheTopTwoMostFrequentValuesasItI
sandReplaceEverythingElseas‘other’inaSeries?

>> #Input

>>import pandas as pd

>>np.random.RandomState(100)
>>ser = pd.Series(np.random.randint(1, 5, [12]))

>> #Solution

>>print("Top2Freq:",ser.value_counts())

>>ser[~ser.isin(ser.value_counts().index[:2])]='Other’

>>ser

46. HowDoYouFindthePositionsofNumbersThatAre
Multiples of Three from a Series?

>> #Input

>>import pandas as pd

>>ser = pd.Series(np.random.randint(1, 10, 7))

>>ser

>>#Solution

>>print(ser)

>>np.argwhere(ser%3==0)

47. HowDoYouComputetheEuclideanDistanceBetweenTw
oSeries?

The code is as shown:

>> #Input

>>p = pd.Series([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

>>q = pd.Series([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])


>> #Solution

>>sum((p - q)**2)**.5

>> #Solution

usingfunc

>>np.linalg.norm(p-q)

YoucanseethattheEuclideandistancecanbecalculatedusingtwoways.

48. HowDoYouReversetheRowsofaDataFrame?

>> #Input

>>df = pd.DataFrame(np.arange(25).reshape(5, -1))

>> #Solutio

n>>df.iloc[::-1,

:]

49. IfYouSplitYourDataintoTrain/TestSplits,IsItPos
sibletooverFit YourModel?

Yes.Onecommonbeginnermistakeisre-
tuningamodelortrainingnewmodelswithdifferentparameters after seeing its performance on the
test set.

50. WhichPythonLibraryIsBuiltonTopofMatplotliband
Pandas to Ease Data Plotting?

Seaborn is a Python library built on top of matplotlib and pandas to ease data plotting. It is a
datavisualization library in Python that provides a high-level interface for drawing
statisticalinformative graphs.

51. What are the important features of Python?


• Python is a scripting language. Python, unlike other programming languages like
Cand its derivatives, does not require compilation before execution.
• Python is dynamically typed, which means you don't have to specify the
kindsof variables when declaring them or anything.

• Python is well suited to object-oriented programming since it supports class


definition,composition, and inheritance.

52. What type of language is Python?

Although Python can be used to write scripts, it is primarily used as


ageneral-purpose programming language.

53. Explain how Python is an interpreted language.

Any programming language that is not in machine-level code before runtime is called
aninterpreted language. Python is thus an interpreted language.

54. What is PEP 8?

PEP denotes Python Enhancement Proposal. It's a collection of guidelines for formatting
Pythoncodefor maximum readability.

55. Explain the Python namespace.

In Python, a namespace refers to the name that is assigned to each object.

56. What are decorators in Python?

Decorators are used for changing the appearance of a function without changing its

structure.Decorators are typically defined before the function they are enhancing.

57. How to use decorators in Python?

Decorators are typically defined before the function they are enhancing. To use a decorator,
wemust first specify its function. Then we write the function to which it is applied, simply placing
thedecorator function above the function to which it must be applied.
58. Differentiatebetween.pycand.py.

The.pyfilesarethesourcecodefilesforPython.ThebytecodeofthePythonfilesisstoredin
.pycfiles,whicharecreatedwhencodeisimportedfromanothersource.Theinterpretersavestime by
converting the source .py files to .pyc files.

59. What is slicing in Python?

Slicing is a technique for gaining access to specific bits of sequences such as strings, tuples,
andlists.

60. How to use the slicing operator in Python?

Slicing is a technique for gaining access to specific bits of sequences such as lists, tuples,
andstrings. The slicing syntax is [start:end:step]. This step can also be skipped. [start:end]
returns allsequence items from the start (inclusive) to the end-1 element. It means the ith
element from theend of the start or end element is negative i. The step represents the jump or
the number ofcomponents that must be skipped.

61. What are keywords in Python?

In Python, keywords are reserved words with a specific meaning. They are commonly used
tospecifythetypeofvariables.Variableandfunctionnamescannotcontainkeywords.Followingarethe
33 keywords of Python:

• Yield

• For

• Else

• Elif

• If

• Not

• Or

• And

• Raise
• Nonlocal

• None

• Is

• In

• Import

• Global

• From

• Finally

• Except

• Del

• Continue

• Class

• Assert

• With

• Try

• False

• True

• Return

• Pass

• Lambda

• Def

• As

• Break

• While

62. How to combine dataframes in Pandas?

This is one of the most commonly asked Python interview questions


The following are the ways through which the data frames in Pandas can be combined:

• Concatenatingthembyverticallystackingthetwodataframes.

• Concatenatingthembyhorizontallystackingthetwodataframes.

• Puttingthemtogetherinasinglecolumn.

63. What are the key features of the Python 3.9.0.0 version?

• Zoneinfo and graphlib are two new modules.

• Improved modules such as asyncio and ast.

• Optimizationsincludeimprovedidiomforassignment,signalhandling,andPythonbuilt-
ins.

• Removal of erroneous methods and functions.

• Instead of LL1, a new parser is based on PEG.

• RemovePrefixesand SuffixeswithNew StringMethods.

• Generics with type hinting in standard collections.

64. In Python, how is memory managed?

• Python's private heap space is in charge of memory management. A private


heapholds all Python objects and data structures. This secret heap is not accessible
to theprogrammer.Instead, the Pythoninterpreter takes careof it.

• Pythonalsoincludesabuilt-ingarbagecollector,whichrecyclesallunusedmemoryand
makes it available to the heap space.

• Python's memory management is in charge of allocating heap space for Python


objects.The core API allows programmers access to some programming tools.

65. ExplainPYTHONPATH.

It's an environment variable that is used when you import a module. When a module is
imported,PYTHONPATHischeckedtoseeiftheimported modules are present in various folders. It
isused by the interpreter to determine which module to load.
66. Explain global variables and local variables in Python.

LocalVariables:Alocalvariableisanyvariabledeclaredwithinafunction.Thisvariableexistsonly in
local space, not in global space.

GlobalVariables:Globalvariablesarevariablesdeclaredoutsideofafunctionorinaglobalspace.

Any function in the program can access these variables.

67. Is Python case-sensitive?

Yes,Pythoniscase-sensitive.

68. HowtoinstallPythononWindowsandsetpathvariables?

• DownloadPythonfromhttps://www.python.org/downloads/

• Installitonyourcomputer.Usingyourcommandprompt,lookforthelocationwherePYTHONisinstalled
onyourcomputerbytypingcmdpython.

• Then,inadvancedsystemsettings,createanewvariablecalledPYTHON_NAMEandpastethecopi
edpathintoit.

• Searchthepathvariable,chooseitsvalue,andselect‘edit’.

• Ifthevaluedoesn'thaveasemicolonattheend,addone,andthentype%PYTHONHOME%.

69. Is it necessary to indent in Python?

Indentation is required in Python. It designates a coding block. An indented block contains all
ofthecodeforloops,classes,functions,andsoon.Typically,fourspacecharactersareused.Yourcodew
illnot executecorrectlyifit isnotindented, anditwillalso generateerrors.

70. On Unix, how do you make a Python script executable?

The script file should start with #!/usr/bin/env python.


71. What is the use of self in Python?

Self is used to represent the class instance. In Python, you can access the class's attributes
andmethods with this keyword. It connects the attributes to the arguments. Self appears in a
varietyof contexts and is frequently mistaken for a term. Self is not a keyword in Python, unlike
in C++.

72. What are the literals in Python?

For primitive data types, a literal in Python source code indicates a fixed value.

73. What are the types of literals in Python?

For primitive data types, a literal in Python source code indicates a fixed value. Following are
the5 types of literal in Python:

• String Literal: A string literal is formed by assigning some text to a variable that is contained
insingle or double quotes. Assign the multiline text encased in triple quotes to produce
multilineliterals.

• NumericLiteral:Theymaycontainnumericvaluesthatarefloating-
pointvalues,integers,orcomplexnumbers.

• CharacterLiteral:Itismadebyputtingasinglecharacterindoublequotes.

• BooleanLiteral:TrueorFalse

• LiteralCollections:Therearefourtypesofliteralssuchaslistcollections,tupleliterals,setliterals,d
ictionaryliterals,andsetliterals.

74. What are Python modules? Name a few


Pythonbuilt-in modules that are often used.

Python modules are files that contain Python code. Functions, classes, or variables can be used
inthis code. A Python module is a .py file that contains code that may be executed. The following
arethe commonly used built-in modules:

• JSON

• datatime

• random
• math

• sys

• OS

75. What is _init_?

_init_ is a constructor or method in Python. This method is used to allocate memory when
anew object is created.

76. What is the Lambda function?

A lambda function is a type of anonymous function. This function can take as many
parametersas you want, but just one statement.

77. Why Lambda is used in Python?

Lambda is typically utilized in instances where an anonymous function is required for a


shortperiod.Lambda functions can be applied in two different ways:

• AssigningLambdafunctionstoavariable

• WrappingtheLambdafunctionintoanotherfunction

78. How does continue, break, and pass work?

When a specified condition is met,


thecontrol is moved to the beginning
Continue ofthe loop, allowing some parts of the
loop to be transferred.

When a condition is met, the loop


Break isterminatedandcontrolispassedtothe
next statement.
Whenyouneedapieceofcodesyntac
Pass ticallybutdon'twantto

execute it, use this. This is a


nulloperation.

79. WhatarePythoniterators?

Iterators are things that can be iterated through or traversed.

80. Differentiate between range and xrange.

Intermsoffunctionality,xrange,andrangeareessentiallythesame.Theybothprovideyoutheoption of
generating a list of integers to use whatever you want. The sole difference betweenrange and
xrange is that range produces a Python list object whereas x range returns anxrange object.
This is especially true if you are working with a machine that requires a lot ofmemory, such as
a phone because range will utilize as much memory as it can to generateyour array of
numbers, which can cause a memory error and crash your program. It is a beastwith a memory
problem.

81. What are unpickling and pickling?

The Pickle module takes any Python object and converts it to a string representation, which it
thendumps into a file using the dump method. This is known as pickling. Unpickling is the process
ofrecovering original Python objects from a stored text representation.

82. What are generators in Python?

Functions that return an iterable set of items are known as generators.

83. How do you copy an object in Python?

The assignment statement (= operator) in Python does not copy objects. Instead, it establishes
aconnection between the existing object and the name of the target variable. The copy module
isused to make copies of an object in Python. Furthermore, the copy module provides two
optionsfor producing copies of a given object –
Deep Copy: Deep Copy recursively replicates all values from the source to the
destinationobject, including the objects referenced by the source object.

fromcopyimportcopy,deepcopylis

t_1 = [1, 2, [3, 5], 4]

## shallow

copylist_2 =

copy(list_1)list_2[3]

7list_2[2].append(6)

list_2#output => [1, 2, [3, 5, 6], 7]

list_1 # output => [1, 2, [3, 5, 6],

4]##deep copy

list_3 = deepcopy(list_1)

list_3[3] =

8list_3[2].append(

7)

list_3 #output=>[1,2,[3,5,6,7],8]

list_1 #output=>[1,2,[3,5,6],4]

Shallow Copy: A bit-wise copy of an object is called a shallow copy. The values in the
copiedobject are identical to those in the original object. If one of the values is a reference to
anotherobject, only its reference addresses are copied.

84. InPython,areargumentsprovidedbyvalueorreference?
Pass by value: The actual item's copy is passed. Changing the value of the object's copy
doesnotaffect the original object's value.
Pass by reference: The actual object is passed as a reference. The value of the old
objectwill change if the value of the new object is changed.

Arguments are passed by reference in

Python.def appendNumber(arr):

arr.append(4)

arr = [1, 2, 3]

print(arr) #Output: => [1, 2,

3]appendNumber(arr)

print(arr) #Output: => [1, 2, 3, 4]

85. How to delete a file in Python?

Use the command os.remove(file_name) to delete a file in Python.

86. Explain join() and split() functions in Python.

The join() function can be used to combine a list of strings based on a delimiter into a
singlestring.

Thesplit()functioncanbeusedtosplitastringintoalistofstringsbasedonadelimiter.string =

"This is a string."

string_list = string.split(' ') #delimiter is a ‘space’ character or ‘

‘print(string_list) #output: ['This', 'is', 'a', 'string.']

print(' '.join(string_list)) #output: This is a string.


87. Explain **kwargs and *args.

*args

• Thefunctiondefinitionusesthe*argssyntaxtopassvariable-lengthparameters.

• "*"denotesvariablelength,while"args"isthestandardname.Anyotherwillsuffice.

**kwargs

• **kwargsisaspecialsyntaxforpassingvariable-lengthkeywordedargumentstofunctions.

• Whenavariableispassedtoafunction,itiscalledakeywordedargument.

• "kwargs"isalsousedbyconventionhere.Youarefreetouseanyothername.

88. What are negative indexes and why are they used?

• Theindexesfromtheendofthelist,tuple,orstringarecallednegativeindexes.

• Arr[-1]denotesthearray'slastelement.Arr[]

89. How will you capitalize the first letter of a string?

Thecapitalize()functioninPythoncapitalizesastring'sinitialletter.Itreturnstheoriginaltextifthe string
already contains a capital letter at the beginning.

90. What method will you use to convert a


stringto all lowercase?

The lower() function can be used to convert a string to a lowercase.

91. In Python, how do you remark numerous lines?

Comments that involve multiple lines are known as multi-line comments. A # must prefix all
linesthat will be commented. You can also use a convenient shortcut to remark several lines. All
youhave to do is hold down the ctrl key and left-click anywhere you want a # character to
appear,theninput a# once. Thiswill adda commentto every linewhere youput your cursor.
92. What are docstrings?

Docstrings are documentation strings. Within triple quotations are these docstrings. They are
notallocated to any variable and, as a result, they can also be used as comments.

93. What is the purpose of ‘not’, ‘is’, and ‘in’ operators?

Special functions are known as operators. They take one or more input values and output a

result.not - returns the boolean value's inverse

is - returns true when both operands are true

in - determines whether a certain element is present in a series

94. Whatarethefunctionshelp()anddir()usedforinPython?

Both help() and dir() are available from the Python interpreter and are used to provide
acondensed list of built-in functions.

dir() function: The defined symbols are displayed using the dir() function.

help() function: The help() function displays the documentation string and also allows you
toaccess help for modules, keywords, attributes, and other items.

95. Whyisn'tallthememoryde-allocatedwhenPythonexits?

• When Python quits, some Python modules, especially those with circular references
toother objects or objects referenced from global namespaces, are not necessarily freed
ordeallocated.

• Python would try to de-allocate/destroy all other objects on exit because it has its
ownefficientcleanup mechanism.

• Itisdifficulttode-allocatememorythathasbeenreservedbytheClibrary.
96. What is a dictionary in Python?

A dictionary is one of Python's built-in datatypes. It establishes a one-to-


onecorrespondence between keys and values. Dictionary keys and values are stored in
pairs indictionaries. Keys are used to index dictionaries.

97. In Python, how do you utilize ternary operators?

TheTernaryoperatoristheoperatorfordisplayingconditionalstatements.Thisismadeoftrueorfalse
values and a statement that must be evaluated.

98. Explain the split(), sub(), and subn() methods of


thePython "re" module.

Python's "re" module provides three ways for modifying strings. They

are:split (): a regex pattern is used to "separate" a string into a list

subn(): It works similarly to sub(), returning the new string as well as the number of

replacements.sub(): identifies all substrings that match the regex pattern and replaces them with

a new string

99. What are negative indexes and why do we utilize them?

Pythonsequencesareindexed,andtheyincludebothpositiveandnegativevalues.Positivenumbersar
eindexedwith'0'asthefirstindexand'1'asthesecondindex,andsoon.

The index for a negative number begins with '-1,' which is the last index in the sequence
andends with '-2,' which is the penultimate index, and the sequence continues like a
positivenumber. The negative index is used to eliminate all new-line spaces from the string and
allow itto accept the last character S[:-1]. The negative index can also be used to represent the
correctorder of the string.

100. Explain Python packages.

PackagesinPythonarenamespacesthatcontainnumerousmodules.
101. What are built-in types of Python?

Given below are the built-in types of Python:

• Built-infunctions

• Boolean

• String

• Complexnumbers

• Floatingpoint

• Integers

102. What are the benefits of NumPy arrays


over(nested) Python lists?

• Lists in Python are useful general-purpose containers. They allow for


(relatively)quick insertion, deletion, appending, and concatenation, and
Python's listcomprehensions make them simple to create and operate.

• They have some limitations: they don't enable "vectorized" operations


likeelementwise addition and multiplication, and because they can include objects
ofdifferenttypes,Pythonmustmaintaintypeinformationforeachelementandexecutetype
dispatching code while working on it.

• NumPyarraysarefaster,andNumPycomeswithseveralfeatures,includinghistograms,algebr
a,linear,basicstatistics,fastsearching,convolutions,FFTs,andmore.

103. What is the best way to add values to a Python array?

Theappend(),extend(),andinsert(i,x)procedurescanbeusedtoaddelementstoanarray.

104. What is the best way to remove values from a Python array?

Thepop()andremove()methodscanbeusedtoremoveelementsfromanarray.Thedifferencebetweenthese
twofunctionsisthatonereturnstheremovedvaluewhiletheotherdoesnot.
105. Is there an object-oriented programming
(OOPs)concept in Python?

Python is a computer language that focuses on objects. This indicates that by simply
constructingan object model, every program can be solved in Python. Python, on the other hand,
may be usedas both a procedural and structured language.

106. Differentiatebetweendeepandshallowcopy.

When a new instance type is formed, a shallow copy is used to maintain the values that
werecopied in the previous instance. Shallow copy is used to copy reference pointers in the
sameway as values are copied. These references refer to the original objects, and any
modificationsmadetoanymemberoftheclasswillhaveanimpactontheoriginalcopy.Shallowcopyenab
lesfaster program execution and is dependent on the size of the data being utilized.

Deep copy is a technique for storing previously copied values. The reference pointers to
theobjects are not copied during deep copy. It creates a reference to an object and stores the
newobjectthatisreferencedtoanotherobject.Thechangesmadetotheoriginalcopywillnotaffectany
subsequent copies that utilize the item. Deep copy slows down program performance
bycreating many copies of each object that is called.

107. What are Python libraries?

APythonlibraryisagroupofPythonpackages.Numpy,Pandas,Matplotlib,Scikit-learn,andmany
other Python libraries are widely used.

108. Why split is used?

In Python, the split() function is used to split a string.

109. How multithreading is achieved in Python?

• Although Python includes a multi-threading module, it is usually not a good idea to


utilizeit if you want to multi-thread to speed up your code.

• Asthishappenssoquickly,itmayappeartothehumaneyethatyourthreadsarerunning
in parallel, but they are actually sharing the same CPU core.
• The Global Interpreter Lock is a Python concept (GIL). Only one of your 'threads'
canexecute at a moment, thanks to the GIL. A thread obtains the GIL, performs
somework, and then passes the GIL to the following thread.

110. How are classes created in Python?

The class keyword in Python is used to construct a class.

111. What is pandas dataframe?

A dataframe is a 2D changeable and tabular structure for representing data with rows
andcolumns labeled.

112. Explain monkey patching in Python.

Monkey patches are solely used in Python to run-time dynamic updates to a class or module.

113. How Python module is imported?

The import keyword can be used to import modules.

114. What is inheritance in Python?

Inheritance allows one class to gain all of another class's members (for example, attributes
andmethods). Inheritance allows for code reuse, making it easier to develop and
maintainapplications.

115. What are the different types of inheritance in Python?

The following are the various types of inheritance in Python:

• Singleinheritance:Themembersofasinglesuperclassareacquiredbyaderivedclass.

• Multiple inheritance: More than one base class is inherited by a derived class.

• Muti-level inheritance: D1 is a derived class inherited from base1 while D2


isinherited from base2.
• HierarchicalInheritance:Youcaninheritanynumberofchildclassesfromasinglebase
class.

116. Is multiple inheritance possible in Python?

A class can be inherited from multiple parent classes, which is known as multiple inheritance.
Incontrast to Java, Python allows multiple inheritance.

117. Explain polymorphism in Python.

The ability to take various forms is known as polymorphism. For example, if the parent class has
amethod named ABC, the child class can likewise have a method named ABC with its
ownparameters and variables. Python makes polymorphism possible.

118. What is encapsulation in Python?

Encapsulation refers to the joining of code and data. Encapsulation is demonstrated through
aPython class.

119. In Python, how do you abstract data?

Onlythenecessarydetailsareprovided,whiletheimplementationishiddenfromview.Interfacesand
abstract classes can be used to do this in Python.

120. Are access specifiers used in Python?

Access to an instance variable or function is not limited in Python. To imitate the behavior
ofprotected and private access specifiers, Python introduces the idea of prefixing the name of
thevariable, function, or method with a single or double underscore.

121. How to create an empty class in Python?

A class that has no code defined within its block is called an empty class. The pass keyword
canbe used to generate it. You can, however, create objects of this class outside of the class.
Whenusedin Python, thePASS command has noeffect.
122. What does an object() do?

It produces a featureless object that serves as the foundation for all classes. It also does
notaccept any parameters.

123. WriteaPythonprogramto generateaStartriangle.

def pyfunc(r):
1

forxinrange(r):
2

print(' '*(r-x-1)+'*'*(2*x+1))
3

pyfunc(9)
4

Output:

***

*****

*******

*********

***********

*************

***************

*****************
124. Writeaprogram toproduce theFibonacciseries inPython.

# Enterthenumberof
1 terms
needednbsp;#0,1,1,2,3,5....
2
a=int(input("Enter the terms"))
3
f=0;#first element of series
4
s=1#second element of series
5
if a=0:
6
print("Therequestedseriesis",f)

7
else:
8
print(f,s,end=" ")
9
for x in range(2,a):
10
print(next,end=" ")
11
f=s
12
s=next

Output: Enter the terms 5 0 1 1 2 3

125. Make a Python program that checks if a


sequenceis a Palindrome.

a=input("enter sequence")

b=a[::-1]
if a==b:

print("palindrome")

else:

print("Not a Palindrome")

Output: enter sequence 323 palindrome

126. Make a one-liner that counts how many capital


lettersare in a file. Even if the file is too large to fit in
memory,your code should work.
1 with open(SOME_LARGE_FILE) as fh:

2 count = 0

3 text = fh.read()

4 for character in text:

5 ifcharacter.isupper():

6 count += 1

Let us transform this into a single line

count sum(1 for line in fh


forcharacter in line if

character.isupper())
1
127. Canyouwriteasortingalgorithmwithanumericaldataset?

list=["1","4","0","6","9"]
1

list = [int(i) for i in list]


2

list.sort()
3

print (list)
4

128. Checkthecodegivenbelow,andlistthefinalvalueofA0,
A1 …An.
1 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))

2 A1 = range(10)A2 = sorted([i for i in A1 if i in A0])

3 A3 = sorted([A0[s] for s in A0])

4 A4 = [i for i in A1 if i in A3]

5 A5 = {i:i*i for i in A1}

6 A6 = [[i,i*i] for i in A1]

7 print(A0,A1,A2,A3,A4,A5,A6)

Here’stheanswer:

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # The order may vary

A1=range(0,10)
A2=[]

A3 = [1, 2, 3, 4, 5]

A4 = [1, 2, 3, 4, 5]

A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

129. What is Flask and explain its benefits.

FlaskisaPythonwebmicroframeworkbasedontheBSDlicense.TwoofitsdependenciesareWerkzeu
g and Jinja2. This means it will have few if any, external library dependencies. Itlightens the
framework while reducing update dependencies and security vulnerabilities.

A session is just a way of remembering information from one request to the next. A session in
aflask employs a signed cookie to allow the user to inspect and edit the contents of the session.
Iftheuseronlyhasthesecretkey,heorshecanchangethesession.Flask.secretkey.

130. Is Django better as compared to Flask?

Django and Flask map URLs or addresses entered into web browsers into Python functions.

Flask is easier to use than Django, but it doesn't do much for you, so you will have to specify
thespecifics, whereas Django does a lot for you and you won't have to do anything. Django
hasprewritten code that the user must examine, whereas Flask allows users to write their
code,making it easier to grasp. Both are technically excellent and have their own set of
advantagesand disadvantages.

131. Differentiate between Pyramid, Django, and Flask.

• Pyramid is designed for larger apps. It gives developers flexibility and allows them
toutilizetheappropriatetoolsfortheirprojects.Thedatabase,URLstructure,templatingstyle
,andotheroptionsareallavailabletothedeveloper.Pyramidscanbeeasily customized.

• Flask is a "microframework" designed for small applications with straightforward


needs.External libraries are required in a flask. The flask is now ready for use.
• Django, like Pyramid, may be used for larger applications. It has an ORM in it .

132. InNumPy,howwillyoureadCSVdataintoanarray?

Thismaybeaccomplishedbyutilizingthegenfromtxt()methodwithacommaas thedelimiter.

133. What is GIL?

The term GIL stands for Global Interpreter Lock. This is a mutex that helps
threadsynchronization by preventing deadlocks by limiting access to Python objects. GIL
assists withmultitasking (and not parallel computing).

134. What is PIP?

PIP denotes Python Installer Package. It is used to install various Python modules. It's
acommand-line utility that creates a unified interface for installing various Python modules.
Itsearches the internet for the package and installs it into the working directory without
requiringany user intervention.

135. What is the use of sessions in the Django framework?

Djangohasasessionfeaturethat allowsyoutostoreand retrievedataforeachsitevisitor. Djangoisolates


the process of sending and receiving cookies by keeping all necessary data on the serverside and
inserting a session ID cookie on the client side.

136. Writeaprogramthatchecksifallofthenumbersin a
sequence are unique.

def check_distinct(data_list):

if len(data_list) ==

len(set(data_list)):returnTrue

else:

returnFalse;
print(check_distinct([1,6,5,8])) #Prints

Trueprint(check_distinct([2,2,5,5,7,8]))#PrintsF

alse

137. What is an operator in Python?

An operator is a symbol that is applied to a set of values to produce a result. An


operatormanipulates operands. Numeric literals or variables that hold values are known as
operands.Unary, binary, and ternary operators are all possible. The unary operator, requires
only
oneoperand,thebinaryoperator,requirestwooperands,andtheternaryoperator,requiresthreeop
erands.

138. What are the various types of operators in Python?

• Bitwise operators

• Identity operators

• Membership operators

• Logical operators

• Assignment operators

• Relational operators

• Arithmetic operators

139. How to write a Unicode string in Python?

The old Unicode type has been replaced with the "str" type in Python 3, and the string
isnow considered Unicode by default. Using the art.title.encode("utf-8") function, we
cancreate a Unicode string.

140. Explain the differences between Python 2.x and

Python3.x?

Python2.xisanolderversionofthePythonprogramminglanguage.Python3.xisthemostrecentversion.Pyth
on2.xisnolongersupported.Python3.xisthelanguage'spresentandfuture.
InPython2,astringisinherentlyASCII,whileinPython3,itisUnicode.
141. How to send an email in Python language?

Python includes the smtplib and email libraries for sending emails. Import these modules into
thenewly generated mail script and send mail to users who have been authenticated.

142. Create a program to add two integers >0 without


usingtheplus operator.

def add_nums(num1, num2):

while num2 != 0:

data = num1 &

num2num1 = num1 ^

num2num2 = data <<

return

num1print(add_nums(2,

10))

143. Create a program to convert dates from yyyy-mm-dd


todd-mm-by.

Wecanuse thismoduleto convertdates:

import re

def transform_date_format(date):

return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1',

date)date_input = "2021-08-

01"print(transform_date_format(date_input))
The datetime module can also be used, as demonstrated below:
from datetime import datetime

new_date=datetime.strptime("2021-08-01","%Y-%m-

%d").strftime("%d:%m:%Y")print(new_data)

144. Create a program that combines two dictionaries. If


youlocate the same keys during combining, you can sum
thevaluesofthesesimilarkeys.Createanewdictionary.

from collections import Counter

d1 = {'key1': 50, 'key2': 100, 'key3':200}

d2 = {'key1': 200, 'key2': 100, 'key4':300}

new_dict = Counter(d1) +

Counter(d2)print(new_dict)

145. Is there an inherent do-while loop in Python?

No.

146. What kind of joins are offered by Pandas?

TherearefourjoinsinPandas:left,inner,right,andouter.

147. How are dataframes in Pandas merged?

The type and fields of the dataframes being merged determine how they are merged. If
thedata has identical fields, it is combined along axis 0, otherwise, it is merged along axis
1.
148. What is the best way to get the first five entries of
adata frame?

Wemaygetthetopfiveentriesofadataframeusingthehead(5)method.df.head()returnsthetop 5 rows
by default. df.head(n) will be used to fetch the top n rows.

149. Howcanyouaccessthedataframe'slatestfiveentries?

Wemaygetthetopfiveentriesofadataframeusingthetail(5)method.df.tail()returnsthetop5rows by
default. df.tail(n) will be used to fetch the last n rows.

150. Explainclassifier.

Anydatapoint'sclassispredictedusingaclassifier.Classifiersarehypothesesthatareusedtoassign
labels to data items based on their classification.

You might also like