300+ TOP PYTHON Interview Questions and Answers [Latest]

PYTHON Interview Questions for freshers experienced :-

1) What Is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

2) What are the different ways to create an empty NumPy array in python?
There are two methods we can apply to create empty NumPy arrays.

The first method.

import numpy

numpy.array([])

The second method.

# Make an empty NumPy array

numpy.empty(shape=(0,0))

3) Can’t concat bytes to str?
This is providing to be a rough transition to python on here

f = open( ‘myfile’, ‘a+’ )

f.write(‘test string’ + ‘\n’)

key = “pass:hello”

plaintext = subprocess.check_output([‘openssl’,’aes-128-cbc’,’-d’, ‘-in’,test,’-base64′,’-pass’, key])

print (plaintext)

f.write (plaintext + ‘\n’)

f.close()

The output file looks like:

test string

4) Expline different way to trigger/ raise exception in your python script?
Raise used to manually raise an exception general-form: raise exception-name (“message to be conveyed”).

voting_age = 15

if voting_age < 19: raise ValueError(“voting age should be at least 19 and above”)

output:

ValueError: voting age should be at least 19 and above 2.assert statements are used to tell your program to test that condition attached to assert keyword, and trigger an exception whenever the condition becomes false. Eg: a = -10

assert a > 0 #to raise an exception whenever a is a negative number

Output:

AssertionError

Another way of raising an exception can be done by making a programming mistake, but that is not usually a good way of triggering an exception

5) Why is not__getattr__invoked when attr==’__str__’?
The base class object already implements a default __str__ method, and __getattr__function is called for missing attributes. The example as it we must use the __getattribute__ method instead, but beware of the dangers.

class GetAttr(object):

def __getattribute__(self, attr):

print(‘getattr: ‘ + attr)

if attr == ‘__str__’:

return lambda: ‘[Getattr str]’

else:

return lambda *args: None

A better and more readable solution to simply override the __str__ method explicitly.

class GetAttr(object):

def __getattr__(self, attr):

print(‘getattr: ‘ + attr)

return lambda *args: None

def __str__(self):

return ‘[Getattr str]’

6)What do you mean by list comprehension?
The process of creating a list performing some operation on the data so that can be accessed using an iterator is referred to as list comprehension.

EX:

[ord (j) for j in string.ascii_uppercase]
Output:

65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90

7) What will be the output of the code:def foo (i=[])?
i.append (1)

return i

>>> foo ()

>>> foo ()

Output:

[1] [1,1]
The argument to the function foo is evaluated once when the function is defined

However since it is a list on every all the list is modified by appending a 1 to it.

8) How to Tic tac toe computer move?
Below The code of computer move in the game tic tac toe in python

def computermove(board,computer,human):

movecom=”

rmoves=rd(0,8)

for movecom in legalmoves(board):

board[movecom]=computer

if winner(board)==computer:

return movecom

board[movecom]=”

for movecom in legalmoves(board):

board[movecom]=human

if winner(board)==human:

return movecom

board[movecom]=”

while rmoves not in legalmoves(board):

rtmoves=rd(0,8)

return rmoves

9) Explain about ODBC and python?
ODBC (Open Database Connectivity) API standard allows the connections with any database that supports the interface such as the PostgreSL database or Microsoft access in a transparent manner

Three types of ODBC modules for python:

PythonWin ODBC module – limited development

mxODBC – a commercial product

pyodbc – This is open source python package

10) How to implement the decorator function, using dollar ()?
Code:
def dollar(fn):

def new(*args):

return ‘$’ + str(fn(*args))

return new

@dollar

def price(amount, tax_rate):

return amount + amount*tax_rate

print price(100,0.1)

output:
$110

PYTHON Interview Questions
PYTHON Interview Questions

11) How to count the number of instance?
You have a class A, you want to count the number of A instance.

Hint: use staticmethod

Example

class A:

total = 0

def __init__(self, name):

self.name = name

A.total += 1

def status():

print “Number of instance (A) : “, A.total

status = staticmethod(status)

a1 = A(“A1”)

a2 = A(“A2”)

a3 = A(“A3”)

a4 = A(“A4”)

A.status()

Output:
The number of instance (A) : 4

12) What are the Arithmetic Operators that Python supports?
‘+’ : Addition

‘-’ : Subtraction

‘*’ : Multiplication

‘/’: Division

‘%’: Modulo division

‘**’: Power Of

‘//’: floor div

Python does not support unary operators like ++ or – operators. Python supports “Augmented Assignment Operators”. i.e.,

A += 10 Means A = A+10

B -= 10 Means B = B-10

13) How do you reload a Python module?
All that needs to be a module object to the imp.reload() function or just reload() in Python 2.x, and the module will be reloaded from its source file. Any other code references symbols exported by the reloaded module, they still are bound to the original code.

14) How does Python handle Compile-time and Run-time code checking?
Python supports compile-time code checking up to some extent. Most checks for variable data types will be postponed until run-time code checking. When an undefined custom function is used, it will move forward with compile-time checking. During runtime, Python raises exceptions against errors.

15) What are Supporting Python packages for data science operations?
Pandas: A package providing flexible data structures to work with relational or labeled data.

NumPy: A package that allows working with numerical based data structures like arrays and tensors.

Matplotlib: A 2D rendering engine written for Python.

Tensorflow: A package used for constructing computational graphs.

16) What are the ones that can be used with pandas?
A python dict, ndarray or scalar values can be used with Pandas. The passed index is a list of axis labels.

17) How To Add an Index, Row or Column to a Pandas DataFrame?
The index can be added by calling set_index() on programmer DataFrame.

For accessing rows, loc works on labels of programme index, iloc works on the positions in programme index, it is a more complex case: when the index is integer-based, programmer passes a label to ix[index].

18) How To Create an Empty DataFrame?
The function that programmer will use is the Pandas Dataframe() function: it reuires the programmer to pass the data that programmer wants to put in, the indices and the columns.

19) Does Pandas Recognize Dates When Importing Data?
Yes. but programmer needs to help it a tiny bit: add the argument parse_dates when programmer by reading in data from, let is say, a comma-separated value (CSV) file.

20) How to convert a NumPy array to a Python List?
Use tolist():

import numpy as np

>>> np.array([[1,2,3],[4,5,6]]).tolist()

[[1, 1, 1], [2, 2, 2]]

21) How to set the figure title and axes labels font size in Matplotlib?
Functions dealing with text like label, title, etc. accept parameters same as matplotlib.text.Text. For the font size you can use size/fontsize:

22) Why we are using Def keyword for method?
The Def keyword in python is used to form a new user-defined function. The def keywords mark the beginning of function header. The functions are the objects through which one can easily organize the code.

23) Why are we using self as first argument?
The first argument represents the current instance of the class. The first argument is always called self. With the use of “self” keyword one can easily access the characteristics and methods of the class in python.

24) Why we are using a Python Dictionary?
There is huge collection of data values in the python dictionary. These dictionaries are accessed to retrieve the value of the keys that unknown to the users. There is a key: value pair provided in the dictionary which makes it more optimized.

25) What are the use of tuples in Python?
A tuple in python is a series of immutable Python objects. These tuples are similar to the list that are used for organizing data to make it easier to understand. If Python has created a tuple in memory, it difficult to change them.

26) What are the use of sets in Python?
The Python Set is the collection objects similar to lists and dictionaries. All the elements should be original and uniue and must be immutable. The python sets in comparison with list provides highly optimized method for ensuring whether a specific element is contained in the set.

27) Does Python supports hybrid inheritance?
No, python doesn’t support hybrid inheritance. But we can use straight method and round diamond method we can achieve it.

28) What is the uses of middleware in Django?
Middleware is responsible for user authentication, session management .

29) Explain Deep Copy in Python
There are some values copied already. To store those copied values, Deep copy is used. Unlike Shallow copy, Deep copy will not copy the reference pointers.

30) Define the usage of split
If you want to separate a provided string in Python, use split() function.

31) What is the keyword to import a module in Python?
Use the keyword ‘import’ to import the modules in Python.

32) List out the different types of inheritance available in Python
Hierarchical inheritance, Multi-level inheritance, Multiple inheritance, and Single Inheritance are the four types inheritance available in Python.

33) Define monkey patching
You can make dynamic modifications to a module or class during the run-time. This process is called monkey patching in Python.

34) Explain encapsulation
Binding the data and code together is known as encapsulation. Example of encapsulation is a Python class.

35) Define Flask in Python
Flask, a microframework principally constructed for a minor application with easier reuirements. External libraries must be used in Flask and flask is always ready to use state.

36) Define Pyramid in Python
For larger application, you can make use of Pyramid and this is hefty configurable concept. Pyramid affords suppleness and permits the developer to employ the appropriate tools for their assignment.

37) Define Django in Python
Similar to Pyramid, Django is built for larger applications and ORM is included.

38) Provide the Django MVT Pattern
Django Pattern

39) What is dictionary in Python?
The built-in datatypes in Python are called a dictionary. It defines one-to-one Relationship between keys and values. It contains a pair of keys and their corresponding values. Dictionaries are indexed by keys. It is a collection which is unordered, changeable and indexed.

Let’s take an example: The following example contains some keys. State, Capital,Language. Their corresponding values are Karnataka, Bangalore, and Kannada respectively.

Dict={ ‘Country’:’Karnataka’,’Capital’:’Bangalore’,’Launguage’:’Kannada’}

print dict[Country]

Karnataka

Print dict[Capital]

Bangalore

Print dict[Launguage]

Kannada

40) How memory is managed in Python?
Python private heap space manages python memory. Python heap has all Python objects and data structures. Access to this private heap is restricted to programmer also Python private heap is taken care by the interpreter.

The core API gives access to some tools for the programmer to code. Python memory manager allocates python heap space.

41)What is the output of this following statement?
f=none

for i in range(5);

with open(“data.txt”, ”w”) as f:

if I>1:

break

print f.closed

A) True B) False C) None D) Error
Ans: A

42) Write a coding in Find a Largest Among three numbers?
num1 = 10

num2 = 14

num3 = 12

if (num1 >= num2) and (num1 >= num3):

largest = num1

elif (num2 >= num1) and (num2 >= num3):

largest = num2

else:

largest = num3

print(“The largest number between”,num1,”,”,num2,”and”,num3,”is”,largest)

Output:

The largest Number is 14.0

43) What is Lambda in Python?
lambda is an one line anonymous function,

Example:

Sum=lambda i,c:i+c

44) What is the difference between list and tuples?
Lists are the mutable elements where we can able to perform the task in the existed variable. Lists can able to reduce the utilization of memory
Tuples are immutable so it can execute faster when compared with list. But it will wastes the memory.

45) What are the key features of Python?
The python doesn’t have any header files

  • It doesn’t have any structure or syntax except the indentation.
  • It can execute the instructions fastly because of the RISC architecture.
  • It consumes only less memory because of no internal executions.
  • It doesn’t have any compilers compilation can be done at the time of the program.

46) How to delete a file in Python?
In Python, Delete a file using this command,

os.unlink(filename)

or

os.remove (filename)

47) What is the usage of help() and dir() function in Python?
Help() and dir() both functions are accessible from the Python interpreter used for viewing a consolidated dump of built-in functions. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc.

48) Which of the following statements create a dictionary? (Multiple Correct Answers Possible)
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) d = (40:”john”, 45:”50”)

Ans: All of the above

49) Which of the following is an invalid statement?
a) abc = 1,000,000
b) a b c = 1000 2000 3000
c) a,b,c = 1000, 2000, 3000
d) a_b_c = 1,000,000

Ans: c

50) What is the output of the following?
try:

if ‘1’ != 1:

raise “someError”

else:

print(“someError has not occured”)

except “someError”:

print (“someError has occured”)

a) someError has occured
b) someError has not occured
c) invalid code
d) none of the above
Ans: b

51) What is the maximum possible length of an identifier?
a) 31 characters
b) 63 characters
c) 79 characters
d) None of the above

Ans: d

52) Differentiate list and tuple with an example?
difference is that a list is mutable, but a tuple is immutable.

Example:

>>> mylist=[1,3,3]

>>> mylist[1]=2

>>> mytuple=(1,3,3)

>>> mytuple[1]=2

TypeError: ‘tuple’ object does not support item assignment

53) Which operator will be helpful for decision making statements?
comparison operator

54) Out of two options which is the template by default flask is following?
a) Werkzeug

b) Jinja2

Ans : b

55) Point out the use of help() function
Help on function copy in module copy:

copy(x)

Shallow copy operation on arbitrary Python objects.

56) From below select which data structure is having key-value pair ?
a.List

b.Tuples

c.Dictionary

Ans : c

57) Differentiate *args and **kwargs?
*args :

We can pass multiple arguments we want like list or tuples of data

**kwargs :

we can pass multiple arguments using keywords

58) Use of Negative indices?
It helps to slice from the back

mylist=[0,1,2,3,4,5,6,7,8]

>>>mylist[-3]

6

59) Give an example for join() and split() funcitons
>>> ‘,’.join(‘12345’)

‘1,2,3,4,5’

>>> ‘1,2,3,4,5’.split(‘,’)

[‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

60) Python is case sensitive ?
a.True

b.False

Ans : a

61) List out loop breaking functions
break
continue
pass

62) what is the syntax for exponentiation and give example?
a**b

2**3 = 8

63) Which operator helps to do addition operations ?
arithmetic operator

64) How to get all keys from dictionary ?
dictionary_var.keys()

65) Give one example for multiple statements in single statement?
a=b=c=3

66) What is the output for the following code?
>> def expandlist(val, list=[]):

list.append(val)

return list

>>> list1 = expandlist (10)

>>> list2 = expandlist (123,[])

>>> list3 = expandlist (‘a’)

>>> list1,list2,list3

Ans : ([10, ‘a’], [123], [10, ‘a’])

67) Number of argument’s that range() function can take ?
3

68) Give an example to capital first letter of a string?
a=’test’

print a[0].upper()

Test

69) How to find whether string is alphanumeric or not?
str = “hjsh#”;

print str.isalnum()

Ans :False

70) Which method will be used to delete a file ?
os.remove(filename)

71) What is difference between match & search in regex module in python?
Match Checks for a match only at the beginning of the string, while search checks for a match anywhere in the string.

72) Can we change tuple values? If yes, give an example.
Since tuple are immutable, so we cannot change tuple value in its original form but we can convert it into list for changing its values and then convert again to tuple.

Below is the example:

my_tuple=(1,2,3,4)

my_list=list(my_tuple)

my_list[2]=9

my_tuple=tuple(my_list)

73) What is purpose of __init__ in Class ? Is it necessary to use __init__ while creating a class ?
__init__ is a class contructor in python. __init__ is called when we create an object for a class and it is used to initialize the attribute of that class.

eg : def __init__ (self, name ,branch , year)

self.name= name

self.branch = branch

self.year =year

print(“a new student”)

No, It is not necessary to include __init__ as your first function every time in class.

74) Can Dictionary have a duplicate keys ?
Python Doesn’t allow duplicate key however if a key is duplicated the second key-value pair will overwrite the first as a dictionary can only have one value per key.

For eg :

>>> my_dict={‘a’:1 ,’b’ :2 ,’b’:3}

>>> print(my_dict)

{‘a’: 1, ‘b’: 3}

75) What happened if we call a key that is not present in dictionary and how to tackle that kind of error ?
It will return a Key Error . We can use get method to avoid such condition. This method returns the value for the given key, if it is present in the dictionary and if it is not present it will return None (if get() is used with only one argument).

Dict.get(key, default=None)

76) What is difference b/w range and arange function in python?
numpy.arange : Return evenly spaced values within a given interval. Values are generated within the half-open interval [start, stop) .the interval including start but excluding stop. It return an Array .

numpy.arange([start, ]stop, [step, ]dtype=None)

Range : The range function returns a list of numbers between the two arguments (or one) you pass it.

77) What is difference b/w panda series and dictionary in python?
Dictionaries are python’s default data structures which allow you to store key: value pairs and it offers some built-in methods to manipulate your data.

78) Why it need to be create a virtual environment before staring an project in Django ?
A Virtual Environment is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects.

Benefit of creating virtualenv :

We can create multiple virtualenv , so that every project have a different set of packages .

For eg. if one project we run on two different version of Django , virtualenv can keep thos projects fully separate to satisfy both reuirements at once.It makes easy for us to release our project with its own dependent modules.

79) How to write a text from from another text file in python ?
Below is the code for the same.

import os

os.getcwd()

os.chdir(‘/Users/username/Documents’)

file = open(‘input.txt’ ,’w’)

with open(“output.txt”, “w”) as fw, open(“input.txt”,”r”) as fr:

80) what is difference between input and raw_input?
There is no raw_input() in python 3.x only input() exists. Actually, the old raw_input() has been renamed to input(), and the old input() is gone, but can easily be simulated by using eval(input()). In python 3.x We can manually compile and then eval for getting old functionality.

python2.x python3.x
raw_input() input()
input() eval(input())

81) What are all important modules in python reuired for a Data Science ?
Below are important module for a Data Science :

  • NumPy
  • SciPy
  • Pandas
  • Matplotlib
  • Seaborn
  • Bokeh
  • Plotly
  • SciKit-Learn
  • Theano
  • TensorFlow
  • Keras

82) What is use of list comprehension ?
List comprehensions is used to transform one list into another list. During this process, list items are conditionally included in the new list and each items are transformed as reuired. Eg.

my_list=[]

my_list1=[2,3,4,5]

Using “for “ loop :

for i in my_list1:

my_list.append(i*2)

Using List comprehension :

my_list2=[i*2 for i in my_list1]

print(my_list2)

83) What is lambda function ?
lambda function is used for creating small, one-time and anonymous function objects in Python.

84) what is use of set in python?
A set is a type of python data Structure which is unordered and unindexed. It is declared in curly braces . sets are used when you reuired only uniue elements .my_set={ a ,b ,c,d}

85) Does python has private keyword in python ? how to make any variable private in python ?
It does not have private keyword in python and for any instance variable to make it private you can __ prefix in the variable so that it will not be visible to the code outside of the class .

Eg . Class A:

def __init__(self):

self.__num=345

def printNum(self):

print self.__num

86) What is pip and when it is used ?
it is a package management system and it is used to install many python package. Eg. Django , mysl.connector

Syntax : pip install packagename

pip install Django : to install Django module

87) What is head and tail method for Data frames in pandas ?
Head : it will give the first N rows of Dataframe.

Tail : it will give last N rows of Dataframe.

By default it is 5.

88) How to change a string in list ?
we can use split method to change an existing string into list.

s= ‘Hello sam good morning ’

s.split()

print(s)

[‘hello’ , ‘sam’ , ‘good’ , ‘morning’]

89) How to take hello as output from below nested list using indexing concepting in python.
my_list=[1,2,3,[5,6,7, [2,7,[‘hello’], 4,5]],3,4]

Ans : my_list[3][3][2][0]

print(my_list)

90) What is list when we have to use ?
Lists always store homogeneous elements. we have to use the lists when the data is same type and when accessing is more insteading of inserting in memory.

91) What is dict when we have to use ?
Dict is used to store key value pairs and key is calculated using hash key. This is used when we want to access data in O(1) time as big O notation in average case. Dict I used in u can say super market to know the price of corresponding while doing billing

92) What is tuple when we have to use ?
Tuple is hetrogenous and we have to use when data is different types.

93) Is String Immutable ?
Yes because it creates object in memory so if you want to change through indexing it will throw an exception since it can’t be changes I,e immutable.

94) How to handle Exception ?
We can handle exceptions by using try catch block . we can also else block in python to make it executed based on condition.

95) Will python work multiple inheritance?
Yes it works .by seuentially referring parent class one by one.

96) Will class members accessible by instances of class?
Yes by referring corresponding attributes we can access.

97) What are Special methods in python and how to implement?
Special methods in python are __init__,__str__,__iter__,__del__

__init__-it will initialize when class loads.

__str__-It is used to represent object in a string format.

__iter__-it I used to define iteration based on reuirements.

__del__-It is used to destroy object when it is not reuired for memory optimization.

98) How to handle deadlock in python.
By providing synchronization methods so that each thread access one at a time.It will lock another thread until thread fine it execution.

99) How for loop will works in python?
For loop internally calls iter method of an object for each call.

100) What is List comprehension how to define it and when to use?
List Comprehensions are expression based iteration.

So we have to give expression and then provide loop and provide if condition if needed.

We have to use when we want to define in such a way that write the code in a compact way.

101) What is set when we have to use?
Set is used to define uniue elements without duplicates. So if you have lump of data and we are searching through email record. By using set we can get the uniue elements.

102) How django works ?
Django will take an url from frontend and look for url reolvers and url will ap corresponding view and if data to be handled it will use certain model to make any database transactions and give repone via view and then passs to UI.

Or django template

103) Is python pure object oriented programming ?
Yes in python all types are stored a objects.

104) What are packages in python which are commonly used explain one ?
The packages used are os, sys,time,tempfile,pdb,

Os –it is used for file and directories handling.

Pdb-It is used to debug the code to find the root cause of issue.

105) How will you merge 2 dictionaries in python?
a = {1:’1’} , b={2:’2’}

c= {**a,**b}

106) What is the other way of checking truthiness?
These only test for truthiness:

if x or y or z:

print(‘passed’)

if any((x, y, z)):

print(‘passed’)

107) How will you verify different flags at once?
flags at once in Python

v1,v2,v3 = 0, 1, 0

if v1 == 1 or v2 == 1 or v3 == 1:

print(‘passed’)

if 1 in (v1, v2, v3):

print(‘passed’)

108) What happens when you execute python == PYTHON?
You get a Name Error Execution

109) Tool used to check python code standards?
Pylint

110) How strings can be sliced?
They can be generally treated as arrays without commas.

Eg: a = “python”

a[i] -> i can be any number within the length of the string

111) How to pass indefinite number of arguments to any function?
We use **args when we don’t know the number of arguments to be passed

112) In OOPS what is a diamond problem in inheritance?
During multiple inheritance, when class X has two subclasses Y and Z, and a class D has two super classes Y and Z.If a method present in X is overridden by both Y and Z but not by D then from which class D will inherit that method Y or Z.

113) Among LISTS,SETS,TUPLES which is faster?
Sets

114) How Type casting is done in python?
(Str -> int)

s = “1234” # s is string

i = int(s) # string converted to int

115) How python maintains conditional blocks?
Python used indentation to differentiate and maintain blocks of code

116) Write a small code to explain repr() in python ?
Repr gives the format that can be read by the compiler.

Eg:

y=2333.3

x=str(y)

z=repr(y)

print ” y :”,y

print “str(y) :”,x

print “repr(y):”,z

————-

output

y : 2333.3

str(y) : 2333.3

repr(y) : 2333.3000000000002

117) How to encrypt a string?
str_enc = str.encode(‘base64’, ‘strict’)

118) Functions are objects -> Explain ?
# can be treated as objects

def print_new(val):

return val.upper()

print ( print_new(‘Hello’))

yell = print_new

print yell(‘different string’)

119) Explain the synbtax to split a string in python?
Str.split(separator,max_split)

120) How can you identify the data type of any variable in python?
Use type(var)

121) What does MAP function in python do?
map() returns a list of the results after it applys the function to each item in a iterable data type (list, tuple etc.)

122) What does the enum function in python do?
When we need to print the vars index along when you iterate, we use the enum function to serve this purpose.

123) Explain assert in action?
assert “py” == “PY”, “Strings are not eual”

124) How does pop function works in set data types?
Pop deletes a random element from the set

125) Is Python open source? If so, why it is called so?
Python is an open source programming language. Because Python’s source code (the code in which Python software is written) is open for all and anyone can have a look at the source code and edit.

126). Why Python is called portable?
Because we can run Python in wide range of hardware platforms and has similar interfaces across all the platforms

127) How to give comments in Python?
Using Hashes (#) at the starting of a line

128) How to create prompt in the console window?
Using input function

129) How to write multiple statements in a single line in Python?
Using semicolon between the statements

130) List out standard datatypes in Python
Numbers, string, list, tuple, dictionary

131) Which standard datatype in Python is immutable?
tuple

132) What is indexing? Explain with an example
Indexing is the numbering of characters in string or items in list, tuple to give reference for them. It starts from 0. Str = “Python”. The index for P is 0, y is 1, t is 2 and goes on.

133).Which statement is used to take a decision based on the comparison?
IF statement

134) List out atleast two loop control statements
break, continue, pass

135) What is the result of pow(x,y)
X raised to the power Y

136) What is the difference between while and for loop?
While loops till the condition fails, for loops for all the values in the list of items provided.

137) Which method removes leading and trailing blanks in a string?
strip – leading and trialing blanks, lstrip – leading blanks, rstrip – trailing blanks

138) Which method removes and returns last object of a list?
list.pop(obj=lst[-1])

139) What is argument in a function?
Argument is the variable which is used inside the function. While calling the function we need to provide values to those arguments.

140) What is variable length argument in function?
Function having undefined no. of arguments are called variable length argument function. While calling this function, we can provide any no. of arguments

141) What is namespace?
Namespace is the dictionary of key-value pairs while key is the variable name and value is the value assigned to that variable.

142) What is module?
Module is a file containing python code which can be re-used in a different program if it is a function.

143) Which is the default function in a class?
Explain about it – _init_. It is called class contructor or initialization method. Python calls _init_ whenever you create a instance for the class

144) What is docstring? How to define it?
docstring is nothing but a comment inside the block of codes. It should be enclosed inside “”” mark. ex: “”” This is a docstring ”””

145) What is the default argument in all the functions inside a class?
Self

146) How to send a object and its value to the garbage collection?
del objname

147) How to install a package and import?
In DOS prompt, run pip install package_name and run import package_name in editor window in Python’s IDE.

148) Name the function which helps to change the files permission
os.chmod

149) Which is the most commonly used package for data importing and manipulation?
Pandas

150) Will python support object oriented?
Yes, it will support by wrapping the code with objects.

151) IS python can be compatible with command prompt?
Yes, it can be accessed through command prompt.

152) How Lists is differentiated from Tuples?
List are slow, can be edited but Tuples are fast and cannot be edited.

153). Use of NUMPY package?
It is fastest, and the package take care of the number calculations.

154). Uses of python?
Pie charts, web application, data modeling, automation and Cluster data.

155) Does python interact with Database?
Yes, it interfaces to most of the Databases.

156) Is python is intended oriented?
Yes, it will throw error if it is not in seuence.

157) How is Garbage handled in python?
It will be automatically handle the garbage after the variable is used.

158) How will you check python version?
Using python –version.

159) How will you uit the python?
Using exit()

160) Does Python has any command to create variable?
No, just (x =244)

161) What is complex type in python?
It is mixture of variable and number.

162) Casting in python?
To make String use command str(2) = ‘2’

163) What is strip in python?
Used to remove white spaces in String

164) Other String literals?
Lower, upper, len, split, replace.

165) Python operators?
Arithmetic, Assignment, Comparison, Logical, Identity, Membership and Bitwise.

166) Membership operator in python?
In and not in.

167) Lambda in python?
Can take only one expression but any number of Argument.

168) Dict in python?
It is something like key and value pair as Map in java.

169) Does python has classes?
In python all are denoted as some classes.

170) Multi threading on python?
It is a package in python and it use GIL to run the thread one after the other. But isn’t it being not good to use here.

171) What is python private heap space?
It is a inbuild garbage collection like java and this space can be used by the developer.

172) Does python support inheritance?
Yes, it supports all forms of inheritance single, multiple, hierarchical and multi-level

173) Benefits of Flask?
It is light weight and independent package. Mainly a web micro framework.

174) How dir() function is used in python?
The defined symbols are defined here.

175) Will exit method in python de allocate the global namespace?
No, it has a specific mechanism which it follows as an individual portion.

176) Has python has monkey patching concept within?
Yes of course, it does dynamic transactions during the run time of the program.

177) args vs kwargs?

  • Args – don’t know how many arguments are used.
  • Kwargs- don’t know how many keywords are used.

178) use of isupper keyword in python?
This will prompt the upper keyword of any character in a string literal.

179) pickling vs unpickling?
If the objects translated from string then it seems to be pickling

If the String is dumped to objects then it seems to un picking

180) What is py checker in python?
It is tool to uantitatively detects the bugs in source code.

181) What are the packages?
NUMPY, SCIPY, MATLAB, etc

182) Pass in Python?
IT is a namespace with no character and it can be moved to next object.

183) How is unit test done in python?
It is done in form of Unittest. This does major of testing activity.

184) Python documentation is called?
DoctString such as AI, Python jobs ,Machine learning and Charts.

185) Convert Sting to number and viceversa in python?
Str() for String to number and oct() for number to string.

186) Local vs Global in python?
Anything inside the function body is local and outside is global as simple as that.

187) How to run script in python?
Use py command or python command to run the specific file in Unix.

188) What is unlink in python?
This is used to remove the file from the specified path.

189) Program structure in python?
Always import the package and write the code without indention

190) Pyramid vs Django?
Both used for larger application and Django comes with a ORM framework.

191) Cookies in python?
Sessions are known as cookies here it is used to reuest from one object to other.

192) Different types of reuest in python?
Before reuest – it is used to passes without the arguments.

After reuest – it is used to pass the reuest and response will be generated.

Tear down reuest – it is used as same as past but it does not provide response always and the reuest cant be changed.

193) How is fail over mechanism works in python?
Once the server shoots the fail over term then it automatically tends to remove the packet each on the solid base and then re shoot again on its own. Socket wont get removed or revoked from the orgin.

194) Dogpile mechanism explain?
Whenever the server host the service and when it gets multiple hits from the various clients then the piles get generated enormously. This effect will be seems as Dogpile effect. This can be captured by processing the one hit per time and not allowed to capture multiple times.

195) What is CHMOD 755 in python?
This will enhance the file to get all the privileges to read write and edit.

196) CGI in Python?
This server mode will enable the Content-type – text/html\r\n\r\n

This has an extension of .cgi files. This can be run through the cgi command from the cmd prompt.

197) Sockets explain?
These are the terminals from the one end to the other using the TCP, UDP protocols this reuires domain, type, protocol and host address.

Server sockets such as bind, listen and accept

Client socket such as connect.

198) Assertions in python?
This is stated as the expression is hits when we get the statement is contradict with the existing flow. These will throw the error based on the scenario.

199) Exceptions in python?
This is as same as JAVA exceptions and it is denoted as the try, catch and finally this also provides the user defined expression.

200) What made you to choose python as a programming language?
The python programming language is easy to learn and easy to implement.

The huge 3rd party library support will make python powerful and we can easily adopt the python

201) what are the features of python?

  • The dynamic typing
  • Large third party library support
  • Platform independent
  • OOPs support
  • Can use python in many areas like machine learning,AI,Data science etc..

202) How the memory is managed in python?
The private heap space is going to take care about python memory. whenever the object is created or destroyed the heap space will take care. As a programmer we don’t need to involve in memory operations of python

203) What is the process of pickling and unpicling?
In python we can convert any object to a string object and we can dump using inbuilt dump().this is called pickling. The reverse process is called unpicling

204). What is list in python?
A list is a mutable seuential data items enclosed with in[] and elements are separated by comma.

Ex: my_list=[1,1.2,’chandra’,’Besant’,[4,5,6]]

In a list we can store any kind of data and we can access them by using index

205) What is tuple in python?
A tuple is immutable seuential data element enclosed with in () and are separated by comma.

Ex: my_tuple=(1,4,5,’mouli’,’python’)

We use tuple to provide some security to the data like employee salaries, some confidential information

206) Which data type you prefer to implement when deal with seuential data?
I prefer tuple over list. Because the tuple accessing is faster than a list because its immutability

207) What are advantages of a tuple over a list?
We can use tuple as a dictionary key because it is hash able and tuple accessing very fast compare to a list.

208) What is list comprehension and dictionary comprehension and why we use it?
A list comprehension is a simple and elegant way to create a list from another list. we can pass any number of expressions in a list comprehension and it will return one value, we can also do the same process for dictionary data types

Data=[99,100,345,45,43,67,43,67]

Ex: new_list = [n**2 for n in data if n%3==0]

209) What is the type of the given datatype a=1?
a)int

b)Tuple

c)Invalid datatype

d)String

Ans:b

210) Which is the invalid variable assignment from the below?
a)a=1,2,3

b)The variable=10

c)the_variable=11

d)none of the above

Ans:b

211) Why do we use sets in python?
Generally we use sets in python to eliminate the redundant data from any data. And sets didn’t accept any mutable data types as a element of a set

Ex: my_set={123,456,’computer’,(67,’mo’)}

212) What are the nameless functions in python?
The anonymous functions are called nameless functions in python. We can also call it as lambda function. The lambda functions can be called as a one liner and can be created instantly

Syntax: lambda arguments: expression

Ex: hello=lambda d:d-(d+1)

To call the lambda function

Hello(5)

213) What is map and filter in python?
Map and filter are called higher order functions which will take another functions as an argument.

214) What is the necessity to use pass statement in python program?
Pass is no operation python statement. we can use it while we are implementing the classes or functions or any logic. If class is going be define later in the development phase we can use pass statement for the class to make it syntactically make it valid.

Ex: def library():

Pass

215) What is *kwargs and **kwargs?
Both are used in functions. both are allowed to pass variable number of arguments to a function only difference is *kwargs is used for non-key word arguments and **kwargs is used for key word arguments

Ex: def kwargs(formal_arg, *kwargv):

print(“first normal arg:”, formal_arg)

for arg in kwargv:

print(“another arg through *argv:”, arg)

kwargs(‘mouli’, ‘ramesh’, ‘rajesh’, ‘kanna’)

216) Explain about negative indexing?
Negative indexing is used in python seuential datatypes like list,string,tuple etc

We can fetch the element from the back with out counting the list index

Ex: list1[-10]

217) What is file context manager?
To open a file in safe mode we use WITH context manager. This will ensure the file crashing from some exceptions. we don’t need to close the file explicitly

Ex: with open(‘sample.txt’,’w’) as f:

Pass

218) Explain between deep and shallow copy?
The deep copy , copy the object with reference so that if we made any changes on the original copy the reference copy will be effected, shallow copy ,copy the object in a separate memory so that if we do any changes on original it won’t effect the shallow copy one

219) How can you make modules in python?
First we need to save the file with somename.py

Second import the somename.py in the newfile.py, so that we can access the somename.py functions in the newfile.py. so that somename.py acts as a module. Even we can share our module to the rest of the

world by registering to PYPY community

220) Explain about default database with python?
SLite3 comes with python3. It is light weight database for small scale of application

221) What are different modes in file operations?
There are 3 modes in python file operations read, write and append sometimes we can do both at a time. read(),readline(),readlines() are the inbuilt functions for reading the file write() is inbuilt function for writing to the file

222) What is enumerate() explain its uses?
Enumerate is a built in function to generate the index as we desired in the seuential datatypes

Ex: for c ,i in enumerate(data,p):

Print(c,i)

Here p is optional if we don’t want it we can eliminate it

223) Can we use else with for loop in python?
Yes we can use. once all the for loop is successfully executed the else part is going to execute, If there are any error occurs or any break happened in the loop then the else is not going to execute

Ex: for I in list1:

print(i)

Else:

print(execution done)

even we can use else with while also

224) What is type() and id() will do?
The type() will give you the information about datatype and id() will provide you the memory location of the object

225) What is decorators?
The decorators are special functions which will very useful when tweaking the function or class.it will modify the functionality of another function.

226) Explain about different blocks in exception handling?
There are three main blocks in python exception handling

Try

Except

Finally

In the try block we will write all the code which can be prone to error, if any error occurred in this block it will go to the except block. If we put finally block also the execution will hit the finally block.

227) Explain inheritance in python?
Inheritance will allow the access to the child call meaning it can access the attributes and methods of the base. There are many types in the inheritance

Single inheritance: in this one, have only one base class and one derived class

Multilevel inheritance: there can be one or more base classes and one more derived classes to inherit

Hierarchical: can derive any number of child classes from single base class

Multiple: a single derived can be inherited from any number of base classes

29.write sorting algorithm in python for given dataset=[‘10’,’22’,’9’,’3’,’1’] using list comprehension

x=[int(i) for I in dataset]

print(x.sort())

228) Explain about multi-threading concept in python?
Multi-threading process can be achieved through the multiprocess inbuilt module. GIL(global interpreter lock ) will take care about the multiprocessing in python. simultaneously there are several threads can be run at same time. The resource management can be handled by GIL.

229) Can we do pattern matching using python?
Yes, we can do it by using re module. like other programming languages python has comes with powerful pattern matching techniue.

230) What is pandas?
Pandas is data science library which deal with large set of data. pandas define data as data frame and processes it. Pandas is a third party library which we need to install.

231) What is pip?
Pip is a python package installer. Whenever we need third party library like paramiko,pandas etc

We have to use pip command to install the packages

Ex: pip install paramiko

232) What is the incorrect declaration of a set?
a)myset={[1,2,3]}

b)myset=set([1,2,3])

c)myset=set((1,2,3))

d)myset={1,2,3}

Ans:a

233) What is OS module will do in python?
OS module is giving access to python program to perform operating system operations like changedirectory, delete or create.

Ex: import os

os.cwd()

234) What is scheduling in threading?
Using scheduling we can decide which thread has to execute first and what is the time to execute the thread. And it is highly dynamic process

235) What is the difference between module and package?
A package is folder which can have multiple modules in it.

We can import module by its package name.module name

236) How we can send email from python?
We can use smtplib inbuilt module to define smtp client, that can be used to send email

237) What is TKIner?
TKIner is a python inbuilt library for developing the GUI

238) How can you prevent abnormal termination of a python program
We can prevent the abnormal termination by using the exception handling mechanism in python. Try , except and finally are the key words for handling the exception. we can raise our own exceptions in the python. They are called user exceptions

239) what module is used to execute linux commands through the python script and give us with one example
We can use OS module to execute any operation system commands. We have to import the OS module first and then give the commands

Ex: import os

Print(os.system(‘nslookup’+’127.10.45.00’))

240) what is the process to set up database in Django
First we need to edit the settings.py module to set up the database. Django comes with SLite database by default, if we want to continue with default database we can leave settings.py as it is. If we decide to work with oracle or other kind of databases like oracle your database engine should be ‘django.db.backends.oracle’. if it is postgresl then the engine should ‘django.db.backends.postgresl_psycopg2’. We can add settings like password, name host etc.

241) what is Django template
A django template is a simple text file which is used to create HTML,CSV or XML. A template contains variables that is replaced with values when we evaluates it

242) what is the uses of middleware in Django?
Middleware is responsible for user authentication, session management .

243) what is Django architecture
Django architecture contains models ,views, templates and controller

The model describes the database schema and data structure. the views retrieves data from model and pass it to the template. Templates are described how the user see it. controller is the logic part and heart of the Django

244) List some of the data science libraries in python
NumPy

Pandas

SciPy

Matplotlib

245) How do substitute a pattern in a string using re module
Import re

>>> re.sub(‘[abc]’, ‘o’, ‘Space’)

‘Spooe’

>>> re.sub(‘[aeu]’, ‘n’, re.sub(‘[abc]’, ‘o’, ‘Space’))

‘Spoon’

246) What is random module will do in python and what are the functions we can apply on random module
Random module will gives the random number from the specific range. Every time we execute we will get the random number

Randrange()

Randint()

Choice()

Shuffle()

Uniform()

Are some of the useful functions in random module

247) What are the noted modules of python in terms of networking
Paramiko, netmiko, pexpect etc

These module will create a ssh connection between server and the program

248) What is beautifulSoup module will do in python?
We are using the module for pulling the data from HTML and XML files

249) What is reuests module will do?
It is a python http library. The aim of the reuests module is to make http reuests simpler and more human friendly

Ex:

Import reuests

r = reuests.get(‘https://api.github.com/user’, auth=(‘user’, ‘pass’))

r.status_code

200

>>> r.headers[‘content-type’]

‘application/json; charset=utf8’

>>> r.encoding

‘utf-8′

>>> r.text # doctest: +ELLIPSIS

u'{“type”:”User”…’

>>> r.json() # doctest: +ELLIPSIS

{u’private_gists’: 419, u’total_private_repos’: 77, …}

250) What are the basic datatypes in python?
Python datatypes include int, float, strings, lists, tuples, sets, dictionaries.

251) How Manages to Python Handle Memory Management?

  • Python is a separate on heaps to keep its memory. So the heap contains all the Python information and these data structures.
  • And it’s the Python created handler that manages the Individual heap.
  • Python employs a built-in garbage receiver, which salvages all the available memory including offloads it to some heap space.

252) What is means by string Python?
A string in Python is a mixture of the alpha-numeric volume of characters. They are clear of objects Volume. It suggests that both don’t help move once all get assigned a value. Python provides to programs of join(), replace(), or split() to alter strings variable.

253) What does the meaning of Slicing in python?
Python Slicing is defined as Lists of Tuples and Arrays Volume function. The Lists element function has a default bit fo the functionality while slicing. If there is a no conseuence of before that first colon, it expects to begin at the start index of the list.

254) Definition of %S In Python?

  • Python it has to been guide for formatting of any value into a string volume function. It may include uite complex characters.
  • It’s One of the popular usages of the start contents into a string including the %s form specifier.
  • The %S formatting helps Python in a similar variable volume syntax as the C function printf().

255) what does a function of python programming?
A function is an object which describes a block of the system and is a reusable object. It takes modularity to a performance code program and a higher level of code reusability.
Python has to give us several built-in functions Volume such as print() function volume and it gives the ability to perform a user-defined function.

256) How to write a functioning volume for python?
Step-1: To begin the function Volume of start writing the function with the keyword and then specify the Volume function name.
Step-2: We can immediately give the reasons and enclose them doing the parentheses.
Step-3: After pushing an enter, we can do it determine the coveted Python records for execution.

257) What is means by Call function in Python?
A python function value gets treated because of a callable object. It can provide any thoughts value and also pass a value or increased values into the model of a tuple. Apart from this function, Python should additional constructs, such as being groups or the class instances fit in the related category.

258) How to use of return keywords in python?

The purpose of a value function get the inputs and return value of some output.
The return value of is a Python statement if it’s we can relate to using for sending content following to its caller.

259) What is meant by“Call By Value” In Python?
In call-by-value, that argument to be valued expression or value becomes connected to the particular variable in this function.
Python command treats that variable being confined within the function-level field.
Any changes done to this variable will continue local and order reflect outside the function.

260) What does means by “Call By Reference” In Python?
The Call-by-reference we pass as an argument by reference volume, then it is possible because of an absolute source on the use, first then some simple copy. In such any case, any change to the discussion instructions further is obvious to the caller.

261) Difference between Pass and Continue In Python?
The continue report executes the loop value to return from the following emphasis. On the opposite, that passing record instructs to make nothing, including the remainder from the code effects as usual.

262) What is meant by R strip() In Python?
Python gives the r-strip() system to increases this string value function but allows avoid this whitespace symbols of that end. This r-strip() transmits that numbers value function of right end based upon particular argument value a string specifying the group of numbers to get excluded.

263) What does defined by whitespace in python?
Whitespace is representing the characters string value function that we practice for spacing moreover separation. They maintain the“empty” value function symbol. In Python, it could move some tab or space.

264) What is defined Isalpha() In Python?
Python has been provided that built-in isalpha() value function for each string manipulating purpose. It reflects the True value function if all types in this string value function are of alphabet type number, else value function it returns False.

265) What does making the CPython Different From Python?
Jython means an implementation from some Python programming language that can operate code using on this Java platform. Jython is uiet as compared to CPython and reuires agreement with CPython libraries. A Python implementation is written in C# getting a Microsoft’s .NET framework.

266) Which is the package Fastest Form Of Python?
PyPy gives maximum agreement while utilizing CPython implementation as increasing its performance.
The tests verified that PyPy is almost five times faster than uniue CPython.

267) What does the meaning of GIL In Python Language?
Python is helped to GI(thats means by the global interpreter) which operates some mutex done to ensure introduction into Python objects, synchronizing multiple threads of running these Python bytecodes at the same time.

268) How do Python Thread Safe?
Python ensures the reliable path of the threads. It does this GIL mutex to secure synchronization. If a thread fails the GIL lock through any time, when you must to get this system thread-safe.

269) How Does determine the Python Manage The Memory?
Python performs a property manager within which operates any of its articles also data structures.
This heap manager makes that allocation/de-allocation from heap space to objects.

270) What is a means by “Tuple In Python”?
A tuple is a group of specific data structure under Python is immutable. They mean similar to progressions, really prefer the lists. Also, that tuples follow parentheses as including, but these programs have suare sections in their syntax.

271) What does means by split do in Python?
This is the opposite of order which mixes or combines strings within one. To do this, you practice this split function value. What it takes is divided or develop up a string and attach that data into each order collection using a specified separator. If none separator is specified while you charge against specific function, whitespace order signify done by default.

272) How do you convert a string to in python?
Use the “int” String function value to convert the number to an integer value. Add five value to the integer. Then, the “str” function value it’s to converts the integer function value to a string value function that Python concatenates and print the output value of the answer.

273) How do you reverse any string in Python?
This is continued the reverse value function part syntax. It goes outcomes too by doing [beginvalue: and endingvalue: step] – by leaving start value and end off value and defining a step of -1, it reverses value function a string function.

274) What does by Python a scripting language?
Python is identified as a scripting language because it is an interpreted language also because that is simple to record scripts in it. A defined python communication programming is a language whose programs have to be obtained before they can be run.

275) What language is Python based on?
Since largest recent OS continue written in C, compilers/editors before improved high-level languages exist also written in C. Python continues an exception – its various popular/”traditional” implementation means described CPython more is written in C.

276) What is the best free website to learn Python?
Python.org. is one the best Python Software Foundation’s official website is further one of the valuable free source locations.SoloLearn- If it refers to a modular, crash-course-like information environment, SoloLearn gives an excellent, step-by-step knowledge program for beginners, TechBeamers , Hackr.io, Real Python.

277) Difference between Python and Java?
The Two biggest difference languages signify that the Java is one the statically typed program coding language and Python is one of the dynamical typed. Python is very heavily code programming language but dynamically typed. In certain means types in one code remain confined to strongly Copied something at runtime.

278) How Can you declare the variables function in Python?
In Java or C, every variable must be certified before it can be used. Declaring the variable means connecting it to a data type value function. Declaration of variables is expected in Python. You can specify an integer value function to a variable, use it is an integer value function for a while and when specifying a string to the variable function.

279) How to declare the variables function in Python?
Python is defined as a dynamically typed variable, which indicates that you have to declare what type each function variable is. In Python, variables do a storage placeholder during texts and numbers variable. It needs to convert one name so that you remain ualified to get this again. The variable does forever assign with an eual sign, replaced by the value of the variable function.

280) How do you reverse the string in python?
There is no such inbuilt function for this. The Easiest way for reversing the string in python is using slice which steps backwards, -1.

For example:

txt = “Hello World”[::-1]

print(txt).

281) WAP to find the given string in the line?
This is the WAP for finding the given string in line.

Str = ‘Hello world’

If ‘hello’ in str:

Print ‘string found’.

282) What is class variable in python?
The Class variable are also known as static variables. These variables are shared by all objects. In Python the variables that are assigned the value in class declaration are known as class variables.

283) What is class in Python?
The python is “object oriented language”. Almost all the codes of this language are implemented using a special construct called Class. In simple words, “Class” is an object constructer in Python.

284) How can you handle multiple exception in python?
To handle multiple exception in python you can use try statement. You can also use these blocks:

The try/except blocks
The finally blocks
The raise keywords
Assertions
Defining your own exception

285) Can we write else statement try block in python?
Yes, it is possible to write else statement try block.

try:

operation_that_can_throw_ioerror()

except IOError:

handle_the_exception_somehow()

else:

# we don’t want to catch the IOError if it’s raised

another_operation_that_can_throw_ioerror()

finally:

something_we_always_need_to_do().

286) Does Python have do-while loop statements?
No, Python doesn’t have any do-while loop statements.

287) What is the difference between range and xrange in Python?
In python the range and xrange are two functions that are used repeat number of time in for loops. The major difference between rang and xrange is that the xrange returns the xrange object while the range returns a python list objects. The xrange is not capable for generating the static list at run-time. On the other hand range can do that.

288) Is it possible to inherit one class from another class?
Yes, we can inherit one class from another class in python.

289) Name different types of inheritance in python?
The inheritance refers to the capability of on class to derive the properties from other class. In python, there are two major types of inheritance.

  1. Multiple Inheritance
  2. Multilevel Inheritance

290) What is polymorphism?
The polymorphism in python refers to various types of respond to the same function. In Greek language the word poly means “many” and morphism means “forms”. This means that the same function name is being used on objects of different types.

291) How do you convert string as a variable name in python?
The simplest way to convert string as a variable name is by using vars().

292) Why do we want to use break statement in while-loop?
While-loop can convert into the infinite loop if you don’t use break statement.

293) Why to use Python numpy instead o f lists?
Python numpy is convenient, less memory and rapid when compared to lists. Hence, it is better to use python numpy.

294) Mention the floor division available in Python
Double-slash (//) is the floor division in Python.

295) Is there any maximum length expected for an identifier?
No, there is no maximum length expected for an identifier as it can have any length.

296) Why do we say “a b c = 1000 2000 3000” is an invalid statement in Python?
We cannot have spaces in variable names and hence a b c = 1000 2000 3000 becomes invalid statement.

297) Mention the concept used in Python for memory managing
Python private heap space is the one used to manage memory.

298) What are the two (2) parameters available in Python map?
Iterable and function are the two (2) parameters available in Python map

299) Explain “with” statement in Python
As soon as there is a block of code, you can open and close a file using “with” statement in Python.

300) What are the modes to open a file in Python?
read–write mode (rw), write-only mode (w), and read-only mode (r) is the three (3) modes to open a file in Python.

301) Try to provide the command to open a file c:\welcome.doc for writing
Command to open a file for writing

f= open(“welcome.doc”, “wt”)

302) Explain Tkinter in Python
An inbuilt Python module helpful in creating GUI applications is known as Tkinter.

303) What does the <yield> keyword do in python?
The yield keyword can turn ant function into a generator. It works like a standard return keyword. But it will always return a generator object. A function can have multiple calls the <yield> keyword.

Example:

def testgen(index):

weekdays = [‘sun’,’mon’,’tue’,’wed’,’thu’,’fri’,’sat’]

yield weekdays[index]

yield weekdays[index+1]

day = testgen(0)

print next(day), next(day)

Output:

Sun mon

PYTHON Interview Questions with Answers Pdf Download

300+[LATEST] Python Interview Questions and Answers

Q1. What’s A Negative Index?

Python sequences are indexed with positive numbers and negative numbers. For positive numbers 0 is the first index 1 is the second index and so forth. For negative indices -1 is the last index and -2 is the penultimate (next to last) index and so forth. Think of seq[-n] as the same as seq[len(seq)-n].
Using negative indices can be very convenient. For example S[:-1] is all of the string except for its last character, which is useful for removing the trailing newline from a string.

Q2. What Is The Difference Between A Tuple And A List?

A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.
Other significant difference is of the syntax. A list is defined as
list1 = [1,2,5,8,5,3,]
list2 = [“Sachin”, “Ramesh”, “Tendulkar”]
A tuple is defined in the following way
tup1 = (1,4,2,4,6,7,8)
tup2 = (“Sachin”,”Ramesh”, “Tendulkar”)

Q3. Are There Any Interfaces To Database Packages In Python?

Yes.
Python 2.3 includes the bsddb package which provides an interface to the BerkeleyDB library. Interfaces to disk-based hashes such as DBM and GDBM are also included with standard Python.

Q4. Explain About Classes In Strings?

Classes are the main feature of any object oriented programming. When you use a class it creates a new type. Creating class is the same as in other programming languages but the syntax differs. Here we create an object or instance of the class followed by parenthesis.

Q5. How Do I Delete A File?

Use os.remove(filename) or os.unlink(filename);

Q6. Explain About The Programming Language Python?

Python is a very easy language and can be learnt very easily than other programming languages. It is a dynamic object oriented language which can be easily used for software development. It supports many other programming languages and has extensive library support for many other languages.

Q7. Explain About Raising Error Exceptions?

In python programmer can raise exceptions using the raise statement. When you are using exception statement you should also specify about error and exception object. This error should be related to the derived class of the Error. We can use this to specify about the length of the user name, password field, etc.

Q8. If Given The First And Last Names Of Bunch Of Employees How Would You Store It And What Datatype?

Either a dictionary or just a list with first and last names included in an element.

Q9. How Is Python Interpreted?

Python has an internal software mechanism which makes your programming easy. Program can run directly from the source code. Python translates the source code written by the programmer into intermediate language which is again translated it into the native language of computer. This makes it easy for a programmer to use python.

Q10. What Is A Method?

A method is a function on some object x that you normally call as x.name(arguments…). Methods are defined as functions inside the class definition:
class C:
def meth (self, arg):
return arg*2 + self.attribute

Q11. State Some Programming Language Features Of Python?

Python supports many features and is used for cutting edge technology. Some of them are
1) A huge pool of data types such as lists, numbers and dictionaries.
2) Supports notable features such as classes and multiple inheritance.
3) Code can be split into modules and packages which assists in flexibility.
4) It has good support for raising and catching which assists in error handling.
5) Incompatible mixing of functions, strings, and numbers triggers an error which also helps in good programming practices.
6) It has some advanced features such as generators and list comprehensions.
7) This programming language has automatic memory management system which helps in greater memory management.

Q12. How Do I Generate Random Numbers In Python?

The standard module random implements a random number generator. Usage is simple:
import random
random.random()
This returns a random floating point number in the range [0, 1).

Q13. How Do I Debug An Extension?

When using GDB with dynamically loaded extensions, you can’t set a breakpoint in your extension until your extension is loaded.
In your .gdbinit file (or interactively), add the command:
br _PyImport_LoadDynamicModule
Then, when you run GDB:
$ gdb /local/bin/python
gdb) run myscript.py
gdb) continue # repeat until your extension is loaded
gdb) finish # so that your extension is loaded
gdb) br myfunction.c:50
gdb) continue

Q14. Explain About Pickling And Unpickling?

Python has a standard module known as Pickle which enables you to store a specific object at some destination and then you can call the object back at later stage. While you are retrieving the object this process is known as unpickling. By specifying the dump function you can store the data into a specific file and this is known as pickling.

Q15. How Do I Convert A Number To A String?

To convert, e.g., the number 144 to the string ‘144’, use the built-in function str(). If you want a hexadecimal or octal representation, use the built-in functions hex() or oct(). For fancy formatting, use the % operator on strings, e.g. “%04d” % 144 yields ‘0144’ and “%.3f” % (1/3.0) yields ‘0.333’.

Q16. Where Is Freeze For Windows?

“Freeze” is a program that allows you to ship a Python program as a single stand-alone executable file. It is not a compiler; your programs don’t run any faster, but they are more easily distributable, at least to platforms with the same OS and CPU.

Q17. Explain And Statement About List?

As the name specifies list holds a list of data items in an orderly manner. Sequence of data items can be present in a list. In python you have to specify a list of items with a comma and to make it understand that we are specifying a list we have to enclose the statement in square brackets. List can be altered at any time.

Q18. How Do I Make Python Scripts Executable?

On Windows 2000, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:Program FilesPythonpython.exe “%1” %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.

On Windows NT, the steps taken by the installer as described above allow you to run a script with ‘foo.py’, but a longtime bug in the NT command processor prevents you from redirecting the input or output of any script executed in this way. This is often important.

The incantation for making a Python script executable under WinNT is to give the file an extension of .cmd and add the following as the first line:

@setlocal enableextensions & python -x %~f0 %* & goto :EOF

Q19. Can I Create My Own Functions In C?

Yes, you can create built-in modules containing functions, variables, exceptions and even new types in C.

Q20. State And Explain About Strings?

Strings are almost used everywhere in python. When you use single and double quotes for a statement in python it preserves the white spaces as such. You can use double quotes and single quotes in triple quotes. There are many other strings such as raw strings, Unicode strings, once you have created a string in Python you can never change it again.

Q21. Is A *.pyd File The Same As A Dll?

Yes .

Q22. Explain About The Use Of Python For Web Programming?

Python can be very well used for web programming and it also has some special features which make you to write the programming language very easily. Some of the features which it supports are Web frame works, Cgi scripts, Webservers, Content Management systems, Web services, Webclient programming, Webservices, etc. Many high end applications can be created with Python because of the flexibility it offers.

Q23. How Can I Evaluate An Arbitrary Python Expression From C?

Call the function PyRun_String() from the previous question with the start symbol Py_eval_input; it parses an expression, evaluates it and returns its value.

Q24. How Do I Find The Current Module Name?

A module can find out its own module name by looking at the predefined global variable __name__. If this has the value ‘__main__’, the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:
def main():
print ‘Running test…’

if __name__ == ‘__main__’:
main()
__import__(‘x.y.z’) returns
Try:
__import__(‘x.y.z’).y.z
For more realistic situations, you may have to do something like
m = __import__(s)
for i in s.split(“.”)[1:]:
m = getattr(m, i)

Q25. What Is Tuple?

Tuples are similar to lists. They cannot be modified once they are declared. They are similar to strings. When items are defined in parenthesis separated by commas then they are called as Tuples. Tuples are used in situations where the user cannot change the context or application; it puts a restriction on the user.

Q26. Explain About Assert Statement?

Assert statement is used to assert whether something is true or false. This statement is very useful when you want to check the items in the list for true or false function. This statement should be predefined because it interacts with the user and raises an error if something goes wrong.

Q27. How Do I Copy An Object In Python?

In general, try copy.copy() or copy.deepcopy() for the general case. Not all objects can be copied, but most can.
Some objects can be copied more easily. Dictionaries have a copy() method:
newdict = olddict.copy()
Sequences can be copied by slicing:
new_l = l[:]

Q28. What Is A Lambda Form?

This lambda statement is used to create a new function which can be later used during the run time. Make_repeater is used to create a function during the run time and it is later called at run time. Lambda function takes expressions only in order to return them during the run time.

Q29. Does Python Support Object Oriented Scripting?

Python supports object oriented programming as well as procedure oriented programming. It has features which make you to use the program code for many functions other than Python. It has useful objects when it comes to data and functionality. It is very powerful in object and procedure oriented programming when compared to powerful languages like C or Java.

Q30. Describe About The Libraries Of Python?

Python library is very huge and has some extensive libraries. These libraries help you do various things involving CGI, documentation generation, web browsers, XML, HTML, cryptography, Tk, threading, web browsing, etc. Besides the standard libraries of python there are many other libraries such as Twisted, wx python, python imaging library, etc.

Q31. What Will Be The Output Of The Following Code

class C(object):
Def__init__(self):
Self.x =1
C=c()
Print C.x
Print C.x
Print C.x
Print C.x

All the outputs will be 1

1
1
1
1

Q32. What Is Python?

Python is an interpreted, interactive, object-oriented programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on PCs under MS-DOS, Windows, Windows NT, and OS/2.

Q33. How Do I Emulate Os.kill() In Windows?

Use win32api:
def kill(pid):
“””kill function for Win32″””
import win32api
handle = win32api.OpenProcess(1, 0, pid)
return (0 != win32api.TerminateProcess(handle, 0))

Q34. Is There An Equivalent Of C’s “?:” Ternary Operator?

No

Q35. What Are The Rules For Local And Global Variables In Python?

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as ‘global’.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a builtin function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.

Q36. How Do I Call A Method Defined In A Base Class From A Derived Class That Overrides It?

If you’re using new-style classes, use the built-in super() function:
class Derived(Base):
def meth (self):
super(Derived, self).meth()
If you’re using classic classes: For a class definition such as class Derived(Base): … you can call method meth() defined in Base (or one of Base’s base classes) as Base.meth(self, arguments…). Here, Base.meth is an unbound method, so you need to provide the self argument.

Q37. How Do I Share Global Variables Across Modules?

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg). Just import the config module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:
config.py:
x = 0 # Default value of the ‘x’ configuration setting
mod.py:
import config
config.x = 1
main.py:
import config
import mod
print config.x

Q38. Where Is The Math.py (socket.py, Regex.py, Etc.) Source File?

There are (at least) three kinds of modules in Python:
@modules written in Python (.py);
@modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
@modules written in C and linked with the interpreter; to get a list of these, type:
import sys
print sys.builtin_module_names

Q39. How Can I Execute Arbitrary Python Statements From C?

The highest-level function to do this is PyRun_SimpleString() which takes a single string argument to be executed in the context of the module __main__ and returns 0 for success and -1 when an exception occurred (including SyntaxError).

Q40. How Do I Interface To C++ Objects From Python?

Depending on your requirements, there are many approaches. To do this manually, begin by reading the “Extending and Embedding” document. Realize that for the Python run-time system, there isn’t a whole lot of difference between C and C++ — so the strategy of building a new Python type around a C structure (pointer) type will also work for C++ objects.

Q41. What Is A Class?

A class is the particular object type created by executing a class statement. Class objects are used as templates to create instance objects, which embody both the data (attributes) and code (methods) specific to a datatype.
A class can be based on one or more other classes, called its base class(es). It then inherits the attributes and methods of its base classes. This allows an object model to be successively refined by inheritance. You might have a generic Mailbox class that provides basic accessor methods for a mailbox, and subclasses such as MboxMailbox, MaildirMailbox, OutlookMailbox that handle various specific mailbox formats.

Q42. Can I Create My Own Functions In C++?

Yes, using the C compatibility features found in C++. Place extern “C” { … } around the Python include files and put extern “C” before each function that is going to be called by the Python interpreter. Global or static C++ objects with constructors are probably not a good idea.

Q43. How Do I Run A Subprocess With Pipes Connected To Both Input And Output?

Use the popen2 module. For example:
import popen2
fromchild, tochild = popen2.popen2(“command”)
tochild.write(“inputn”)
tochild.flush()
output = fromchild.readline()

Q44. What Is Self?

Self is merely a conventional name for the first argument of a method. A method defined as meth(self, a, b, c) should be called as x.meth(a, b, c) for some instance x of the class in which the definition occurs; the called method will think it is called as meth(x, a, b, c).

Q45. How Do I Copy A File?

The shutil module contains a copyfile() function.

Q46. Explain About Indexing And Slicing Operation In Sequences?

Tuples, lists and strings are some examples about sequence. Python supports two main operations which are indexing and slicing. Indexing operation allows you to fetch a particular item in the sequence and slicing operation allows you to retrieve an item from the list of sequence. Python starts from the beginning and if successive numbers are not specified it starts at the last. In python the start position is included but it stops before the end statement.

Q47. Explain About The Dictionary Function In Python?

A dictionary is a place where you will find and store information on address, contact details, etc. In python you need to associate keys with values. This key should be unique because it is useful for retrieving information. Also note that strings should be passed as keys in python. Notice that keys are to be separated by a colon and the pairs are separated themselves by commas. The whole statement is enclosed in curly brackets.

Q48. Is There A Tool To Help Find Bugs Or Perform Static Analysis?

Yes.
PyChecker is a static analysis tool that finds bugs in Python source code and warns about code complexity and style.
Pylint is another tool that checks if a module satisfies a coding standard, and also makes it possible to write plug-ins to add a custom feature.

Q49. How Do I Apply A Method To A Sequence Of Objects?

Use a list comprehension:
result = [obj.method() for obj in List]

Q50. How Can I Find The Methods Or Attributes Of An Object?

For an instance x of a user-defined class, dir(x) returns an alphabetized list of the names containing the instance attributes and methods and attributes defined by its class.