Python Interview Questions And Answers For Experienced

1. What is namespace in Python?
Answer: In Python, every name introduced has a place where resides and can be found. This space is known as a namespace. It is an address location where a variable name is mapped to the object placed. Whenever the variable is searched out, this address location will be searched, to get the corresponding object.

2. How do you make 3D plots/visualizations using NumPy/SciPy?
Answer: 
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.

3. Differentiate between .py and .pyc files?
Answer: 
Both .py and .pyc files hold the byte code. “.pyc” is a compiled version of Python file. This file is automatically generated by Python to improve performance. The .pyc file is having byte code which is platform independent and can be executed on any operating system that supports .pyc format.
Note: there is no difference in speed when the program is read from .pyc or .py file; the only difference is the load time.

4. What are Python’s dictionaries?
Answer: 
Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

5. How do I send mail from a Python script?
Answer: 
Use the standard library module smtplib. Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.
import sys, smtplib
fromaddr = raw_input(“From: “)
toaddrs = raw_input(“To: “).split(‘,’)
print “Enter message, end with ^D:”
msg = ”
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# The actual mail sends
server = smtplib.SMTP(‘localhost’)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A UNIX-only alternative uses to send mail. The location of the send mail program varies between systems; sometimes it is /usr/lib/sendmail, sometime /usr/sbin/sendmail. The send mail manual page will help you out. Here’s some sample code:
SENDMAIL = “/usr/sbin/sendmail” # sendmail location
import os
p = os.popen(“%s -t -i” % SENDMAIL, “w”)
p.write(“To: receiver@example.comn“)
p.write(“Subject: testn”)
p.write(“n”) # blank line separating headers from body
p.write(“Some textn”)
p.write(“some more textn”)
sts = p.close()
if sts != 0:
print “Sendmail exit status”, sts

6. Why is that none of my threads are not running? How can I make it work?
Answer: 
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:
import threading, time
def thread_task(name, n):
for I in range(n): print name, i
for I in range(10)

7. Explain about ODBC and Python?
Answer: 
ODBC (“Open Database Connectivity) API standard allows the connections with any database that supports the interface, such as PostgreSQL database or Microsoft Access in a transparent manner. There are 3 ODBC modules for Python: PythonWin ODBC module – limited development
mxODBC – commercial product
pyodbc – it is an open source Python package.

8. Explain Python’s pass by references Vs pass by value. (or) Explain about Python’s parameter passing mechanism?
Answer: 
In Python, by default, all the parameters (arguments) are passed “by reference” to the functions. Thus, if you change the value of the parameter within a function, the change is reflected in the calling function. We can even observe the pass “by value” kind of behavior whenever we pass the arguments to functions that are of type say numbers, strings, tuples. This is because of the immutable nature of them.

9. What is a module and package in Python?
Answer: 
The module is the way to structure a program. Each Python program file is a module, which imports other modules like objects and attributes.

The folder of the Python program is a package of modules. A package can have modules or subfolders.

10. How does exception handling in Python differ from Java?
Answer: 
optional clauses for a block In Python.
Python has its own method of implementing exception handling. is the block which can be used by the programmer to see the error details without having to terminate the program. Also, in some cases, this statement offers a solution to deal with the error.

11. Control flow statements?
Answer: 
By default, python program execution starts from the first line, execute each and every statement only once and transactions the program if the last statement of the program execution is over.
Control flow statements are used to disturb the normal flow of the execution of the program.

12. What is a Tuple?
Answer:

1. Tuple Objects can be created by using parenthesis or by calling tuple function or by assigning multiple values to a single variable
2. Tuple objects are immutable objects
3. Incision order is preserved
4. Duplicate elements are allowed
5. Heterogeneous elements are allowed
6. Tuple supports both positive and negative indexing
7. The elements of the tuple can be mutable or immutable
Example:
x=()
print(x)
print(type(x))
print(len(x))
y-tuple()
print(y)
print(type(y))
print(len(y))
z=10,20
print(z)
print(type(z))
print(len(z))
p=(10,20,30,40,50,10,20,10) Insertion & duplicate
print(p)
q=(100, 123.123, True, “mindmajix”) Heterogeneous
print(q).

13. How can you Get the Google cache age of any URL or web page?
Answer:

Use the following URL format:

Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for.

14. What is map function in Python?
Answer: 
map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given.

15. What is Anonymous Function or Lambda Function?

Answer:
A function which doesn’t contain any name is known as an anonymous function lambda function
Syntax:
lambda arguments: expression
Lambda function we can assign to the variable & we can call the lambda function through the variable
Example:

myfunction=lambda x:x*x
a=myfunction(10)
print(a)
Output: 100

16. Modules Search Path??
Answer: 
By default python interpreter search for the imported modules in the following locations:
Current directory (main module location)
Environment variable path
Installation dependent directory
If the imported module is not found in any one of the above locations. Then python interpreter gives an error.
Built-in attributes of a module:
By default for each and every python module some properties are added internally and we call those properties as a built-in-attribute of a module.

17. What is the function of a negative index?
Answer: 
The sequences in python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is used as the first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in the correct order.
Write a program to check whether the object is of a class or its subclass.
There is a method which is built-in to show the instances of an object that consists of many classes by providing a tuple in a table instead of individual classes. The method is given as isinstance(obj,cls) and in more details given as:

isinstance(obj, (class1, class2, …)) that is used to check about the object’s presence in one of the classes. The built in types can also have many formats of the same function like isinstance(obj, str) or isinstance(obj, (int, long, float, complex)).

It is not preferred to use the class instead of user-defined classes are made that allow easy object-oriented style to define the behavior of the object’s class. These perform a different thing that is based on the class. The function differs from one class to another class.
To find out the object of the particular class the following program is used:
def search(obj):
if isinstance(obj, box):
# This is the code that is given for the box and writes the program in the object
elif isinstance(obj, Document):
# This is the code that searches the document and writes the values in it
elif
obj.search()
#This is the function used to search the object’s class.

18. What is the function of “self”?
Answer: 
“Self” is a variable that represents the instance of the object to itself. In most of the object-oriented programming language, this is passed as to the methods as a hidden parameter that is defined by an object. But, in python, it is declared it and pass it explicitly. It is the first argument that gets created in the instance of class A and the parameters to the methods are passed automatically. It refers to a separate instance of the variable for individual objects. This is the first argument that is used in the class instance and the “self” method is defined explicitly to all the methods that are used and present. The variables are referred to as “self.xxx”.

19. What are the steps required to make a script executable on Unix?
Answer: 
The steps that are required to make a script executable are to:
– First, create a script file and write the code that has to be executed in it.
– Make the file mode as executable by making the first line starts with #! this is the line that python interpreter reads.
– Set the permission for the file by using chmod +x file. The file uses the line that is the most important line to be used:
#!/usr/local/bin/python
– This explains the pathname that is given to the python interpreter and it is independent of the environment programs.
– The absolute pathname should be included so that the interpreter can interpret and execute the code accordingly. The sample code that is written:
#! /bin/sh
# Write your code here
exec python $0 ${1+”$@”}
# Write the function that needs to be included.

20. What are the Packages??
Answer: 
The package is nothing but a folder or dictionary which represents a collection of modules
A package can also contain sub packages
We can import the modules of the package by using the package name. module name
We can import the modules of the package by using the package name. subpackage name.module name

21. What is File Handling?
Answer: 
The file is a named location on the disk, which stores the data in a permanent manner.
Python language provides various functions and methods to provide communication between python programs and files.
Python programs can open the file, perform the read or write operations on the file and close the file
We can open the files by calling the open function of built-in-modules
At the time of opening the file, we have to specify the mode of the file
Mode of the file indicates for what purpose the file is going to be opened(r,w, a,b)

22. When would you use a break statement in a for loop?
Answer: 
The break statement states that the function of the loop is over and to move on to the next block of code. For example, when the item being searched is found, there is no need to keep looping. The break statement comes into play here and the loop terminates and the execution moves on to the next section of the code.

23. How To Save An Image Locally Using Python Whose URL Address I Already Know?
Answer: 
We will use the following code to save an image locally from an URL address

1.import urllib.request
2.urllib.request.urlretrieve(“URL”, “local-filename.jpg”)

24. What is the process to run sub-process with pipes that connect both input and output?
Answer: 
The popen2() module is used to run the sub-process but due to some difficulty in processing like the creation of deadlock that keeps a process blocked that wait for the output from the child and child is waiting for the input. The deadlock occurs due to the fact that parent and child don’t have the synchronization and both are waiting to get the processor to provide the resources to one another. Use of popen3() method allows the reading of stdout and stderr to take place where the internal buffer increases and there is no read() takes place to share the resources. popen2() take care of the deadlock by providing the methods like wait() and waitpid() that finishes a process first and when a request comes it hands over the responsibility to the process that is waiting for the resources.
The program is used to show the process and run it.
import popen2
fromchild, tochild = popen2.popen2(“command”)
tochild.write(“inputn”)
tochild.flush()
output = fromchild.readline()

25. What are the different ways to generate random numbers?
Answer: 
The random module is the standard module that is used to generate a random number.
The method is defined as:
import random
 .random()
The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that create a different instance of individual threads. The other random generators that are used in this are:
– randrange(a, b): it chooses an integer and defines the range in-between [a, b). It returns the elements by selecting them randomly from the range that is specified. It doesn’t build a range object.
– uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
– normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
– The Random class that is used and instantiated creates an independent multiple random number generators.
Write a program to show the singleton pattern used in python.
Singleton patter is used to provide a mechanism that limits the number of instances that can be used by one class. It also allows the same object to be shared between many different parts of the code. This allows the global variables to be used as the actual data that is used is hidden by the singleton class interface. The singleton class interface can have only one public member and one class method Handle. Private constructors are not used to creating an object that is used outside the class. The process waits for the static member function to create new instances and return the singleton object.

26. What Are The Built-In Types Available In Python?
Answer:

Here is the list of most commonly used built-in types that Python supports:

  • Immutable built-in types of Python
  • Numbers
  • Strings
  • Tuples
  • Mutable built-in types of Python
  • List
  • Dictionaries
  • Sets

27. Which methods of Python are used to determine the type of instance and inheritance?
Answer:

Python has 2 built-in functions that work with inheritance:
isinstance() – this method checks the type of instance.

for eg, isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.
issubclass() – this method checks class inheritance

for eg: issubclass(bool, int) – returns True because “bool” is a subclass of “int”.

issubclass(unicode, str) – returns False because “unicode” is not a subclass of “str”.

28. What is the use of enumerate() in Python?
Answer: 
Using enumerate() function you can iterate through the sequence and retrieve the index position and its corresponding value at the same time.
>>> for i,v in enumerate([‘Python’,’Java’,’C++’]):
print(i,v)
0 Python
1 Java
2 C++

29. How many kinds of sequences are supported by Python? What are they?
Answer: 
Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and buffer. where xrange is deprecated in python 3.5.X.

30. Name a few methods for matching and searching the occurrences of a pattern in a given text String?
Answer: 
There are 4 different methods in the “re” module to perform pattern matching. They are:

match() – matches the pattern only to the beginning of the String. search() – scan the string and look for a location the pattern matches findall() – finds all the occurrences of the match and return them as a list
finder() – finds all the occurrences of match and return them as an iterator.

31. Explain how Python does Compile-time and Run-time code checking?
Answer: 
Python performs some amount of compile-time checking, but most of the checks such as type, name, etc are postponed until code execution. Consequently, if the Python code references a user -a defined function that does not exist, the code will compile successfully. In fact, the code will fail with an exception only when the code execution path references the function which does not exist.

32. What is Abnormal Termination?
Answer: 
The concept of terminating the program in the middle of its execution without executing the last statement of the main module is known as an abnormal termination
Abnormal termination is an undesirable situation in programming languages.

33. What is Try Block?
Answer: 
A block which is preceded by the try keyword is known as a try block
Syntax:

try{//statements that may cause an exception}
The statements which cause to run time errors and other statements which depends on the execution of run time errors statements are recommended to represent in a try block
While executing try block statement if any exception is raised then immediately try block identifies that exception, receive that exception and forward that exception to except block without executing remaining statements to try block.

34. What is scheduling?
Answer: 
Among multiple threads which thread as to start the execution first, how much time the thread as to execute after allocated time is over, which thread, as to continue the execution next this, comes under scheduling
Scheduling is highly dynamic.

35. What is Threads Life Cycle?
Answer: 
Threads Life Cycle
Creating the object of a class which is overwriting run method of thread class is known as a creating thread
Whenever a thread is created then we call thread is in new state or birth state thread.
Whenever we call the start method on the new state threads then those threads will be forwarded for scheduling
The threads which are forwarded for scheduling are known as ready state threads
Whenever scheduling time occurs, ready state thread starts execution
The threads which are executing are known as running state threads
Whenever sleep fun or join methods are called on the running state threads then immediately those threads will wait.
The threads which are waiting are known as waiting for state threads
Whenever waiting time is over or specified thread execution is over then immediately waiting state threads are forwarded for scheduling.
If running state threads execution is over then immediately those threads execution will be terminated
The threads which execution is terminated are known as dead state threads.

36. What is Web Scraping? How do you achieve it in Python?
Answer: 
Web Scrapping is a way of extracting the large amounts of information which is available on the web sites and saving it onto the local machine or onto the database tables.
In order to scrap the web: load the web page which is interesting to you. To load the web page, use the “requests” module.
parse HTML from the web page to find interesting information. Python has few modules for scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoap, etc.

37. What are Accessors, mutators, @property?
Answer: 
Accessors and mutators are often called getters and setters in languages like “Java”. For example, if x is a property of a user-defined class, then the class would have methods called setX() and getX(). Python has an @property “decorator” that allows you to ad getters and setters in order to access the attribute of the class.

38. How To Find Bugs Or Perform Static Analysis In A Python Application?
Answer: 
You can use PyChecker, which is a static analyzer. It identifies the bugs in Python project and also reveals the style and complexity related bugs.
Another tool is Pylint, which checks whether the Python module satisfies the coding standard.

39. How to retrieve data from a table in MySQL database through Python code?
Answer:

Explain.
import MySQLdb module as import MySQLdb
establishes a connection to the database.
db = MySQLdb.connect(“host”=” localhost”, “database-user”=”user-name”, “password”=” password”, “database-name”=” database”)
initialize the cursor variable upon the established connection: c1 = db.cursor()
retrieve the information by defining a required query string. s = “Select * from dept”
fetch the data using fetch() methods and print it. data = c1.fetch(s)
close the database connection. db.close()
40. What Are Different Methods To Copy An Object In Python?
Answer:

There are two ways to copy objects in Python.

copy.copy() function
It makes a copy of the file from source to destination.
It’ll return a shallow copy of the parameter.
copy.deepcopy() function
It also produces the copy of an object from the source to destination.
It’ll return a deep copy of the parameter that you can pass to the function.

41. When Is The Python Decorator Used?
Answer: 
Python decorator is a relative change that you do in Python syntax to adjust the functions quickly.

42. What Is The Key Difference Between A List And The Tuple?
Answer:

List Vs Tuple.
The major difference between a list and the tuple is that the list is mutable while tuple is not. A tuple is allowed to be hashed, for example, using it as a key for dictionaries.

43. What Is The Purpose Of Doc Strings In Python?
Answer: 
In Python, a documentation string is popularly known as docstrings. It sets a process of recording Python functions, modules, and classes.

44. What is Tkinter?
Answer: 
TkInter is a Python library. It is a toolkit for GUI development. It provides support for various GUI tools or widgets (such as buttons, labels, text boxes, radio buttons, etc) that are used in GUI applications. The common attributes of them include Dimensions, Colors, Fonts, Cursors, Etc.

45. Name and explain the three magic methods of Python that are used in the construction and initialization of custom Objects?
Answer: The 3 magic methods of Python that are used in the construction and initialization of custom Objects are: init__, new, and del__.
new – this method can be considered as a “constructor”. It is invoked to create an instance of a class with the statement said, myObj = MyClass()
init__ — It is an “initializer”/ “constructor” method. It is invoked whenever any arguments are passed at the time of creating an object. myObj = MyClass(‘Pizza’,25)
del- this method is a “destructor” of the class. Whenever an object is deleted,
the invocation of del__ takes place and it defines behavior during the garbage collection. 

Note: new, del are rarely used explicitly.

46. Which Python Function Will You Use To Convert A Number To A String?
Answer: 
For converting a number into a string, you can use the built-in function <str()>. If you want an octal or hexadecimal representation, use the inbuilt function <oct()> or <hex()>.

47. How Do You Debug A Program In Python? Is It Possible To Step Through Python Code?
Answer: 
Yes, we can use the Python debugger () to debug any Python program. And if we start a program using, then it let us even step through the code.

48. List Down Some Of The PDB Commands For Debugging Python Programs?
Answer: 
Here are a few PDB commands to start debugging Python code.

  • Add breakpoint 
  • Resume execution 
  • Step by step debugging 
  • Move to next line 
  • List source code 
  • Print an expression 

49. Why And When Do You Use Generators In Python?
Answer: 
A generator in Python is a function which returns an iterable object. We can iterate on the generator object using the keyword. But we can only do that once because their values don’t persist in memory, they get the values on the fly.

Generators give us the ability to hold the execution of a function or a step as long as we want to keep it. However, here are a few examples where it is beneficial to use generators.

We can replace loops with generators for efficiently calculating results involving large data sets.
Generators are useful when we don’t want all the results and wish to hold back for some time.
Instead of using a callback function, we can replace it with a generator. We can write a loop inside the function doing the same thing as the callback and turns it into a generator.

50. Explain split(), sub(), sub() methods of “re” module in Python?
Answer: 
To modify the strings, Python’s “re” module is providing 3 methods. They are:

split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of replacements

51. How can you generate random numbers in Python?
Answer: 
The random module is the standard module that is used to generate a random number. The method is defined as:

1.import random
2.random.random
The statement random.random() method return the floating point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that create a different instance of individual threads. The other random generators that are used in this are:

randrange(a, b): it chooses an integer and defines the range in-between [a, b). It returns the elements by selecting them randomly from the range that is specified. It doesn’t build a range object.
uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number
normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation.
The Random class that is used and instantiated creates an independent multiple random number generators.

52. What advantages do NumPy arrays offer over (nested) Python lists?
Answer: 
Python’s lists are efficient general-purpose containers. They support (fairly) efficient insertion, deletion, appending, and concatenation, and Python’s list comprehensions make them easy to construct and manipulate.
They have certain limitations: they don’t support “vectorized” operations like elementwise addition and multiplication, and the fact that they can contain objects of differing types mean that Python must store type information for every element, and must execute type dispatching code when operating on each element.
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.
NumPy array is faster and you get a lot built-in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc.

53. What does this mean: *args, **kwargs? And why would we use it?
Answer: 
We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargsis used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and *billy but that would not be wise.

54. How Does Python Handle The Memory Management?
Answer: Python uses private heaps to maintain its memory. So the heap holds all the Python objects and the data structures. This area is only accessible to the Python interpreter; programmers can’t use it.
And it’s the Python memory manager that handles the Private heap. It does the required allocation of the heap for Python objects.
Python employs a built-in garbage collector, which salvages all the unused memory and offloads it to the heap space.

Note: Browse latest Python Interview Questions and Python Tutorial Videos. Here you can check Python Training details and Python Training Videos for self learning. Contact +91 988 502 2027 for more information.

Leave a Comment

FLAT 30% OFF

Coupon Code - GET30
SHOP NOW
* Terms & Conditions Apply
close-link