Top Python Interview Questions And Answers
Top Answers to Python Interview Questions
|Ease of use||Good||Very Good|
|Speed of coding||Average||Excellent|
|Data types||Static typed||Dynamically typed|
|Data Science & machine learning applications||Average||Very Good|
These are the two functions that are accessible from the Python Interpreter. These two functions are used for viewing a consolidated dump of built-in functions.
help() - it will display the documentation string. It is used to see the help related to modules, keywords, attributes, etc.
To view the help related to string datatype, just execute a statement help(str) – it will display the documentation for 'str, module. ◦ Eg: >>>help(str) or >>>help() - it will open the prompt for help as help>
to view the help for a module, help> module module name Inorder to view the documentation of 'str' at the help>, type help>modules str
to view the help for a keyword, topics, you just need to type, help> “keywords python- keyword” and “topics list”
dir() - will display the defined symbols. ▪ Eg: >>>dir(str) – will only display the defined symbols.
When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically.
available as part of standard module.To view them, we can pass the module ” builtins ” as an argument to “dir()”. It will display the
built-in functions, exceptions, and other objects as a list.>>>dir(__builtins )
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ……… ]
It is impossible to deallocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient clean up mechanism, Python would try to deallocate/
destroy every object.
zip() function- it will take multiple lists say list1, list2, etc and transform them into a single list of tuples by taking the corresponding elements of the lists that are passed as parameters. Eg:
list1 = ['A', 'B','C'] and list2 = [10,20,30]. zip(list1, list2) # results in a list of tuples say [('A',10),('B',20),('C',30)]
whenever the given lists are of different lengths, zip stops generating tuples when the first list ends.
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 a behaviour whenever we pass the arguments to functions that are of type say numbers, strings, tuples. This is because of the immutable nature of them.
• As Python’s Objects are instances of classes, they are created at the time of instantiation. Eg: object-name = class-name(arguments)
• one or more variables can reference the same object in Python
• Every object holds unique id and it can be obtained by using id() method. Eg: id(obj-name) will return unique id of the given object.
every object can be either mutable or immutable based on the type of data they hold.
• Whenever an object is not being used in the code, it gets destroyed automatically garbage collected or destroyed
• contents of objects can be converted into string representation using a method
Python’s constructor – _init__ () is a first method of a class. Whenever we try to instantiate a object __init__() is automatically invoked by python to initialize members of an object.
If we want to load a module or open a file, and even if the requested module/file does not exist, we want to continue with other tasks. In such a scenario, use try-except block with pass statement in the except block.
try:import mymodulemyfile = open(“C:\myfile.csv”)except:pass
In order to scrap the web:load the web page which is interesting to you. To load the web page, use “requests” module.
parse HTML from the web page to find the interesting information.Python has few modules for scraping the web. They are urllib2, scrapy, pyquery, BeautifulSoap, etc.
A module can be imported by other modules in one of the two ways. They are
2. from module-name import or
Here, os and os.path – modules include functions for accessing the filesystem
shutil – module enables you to copy and delete the files.
General form of with:
with open(“file name”, “mode”) as file-var:
note: no need to close the file by calling close() upon file-var.close()
read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”, “w”, “rw”, “a” respectively.
A text file can be opened in any one of the above said modes by specifying the option “t” along with
“r”, “w”, “rw”, and “a”, so that the preceding modes become “rt”, “wt”, “rwt”, and “at”.A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “rw”, and “a” so that the preceding modes become “rb”, “wb”, “rwb”, “ab”.
1. Open an output file in “write” mode and the print the contents in to that file, using sys.stdout attribute.
filename = “outputfile” sys.stdout = open() print “testing”
2. you can create a python script say .py file with the contents, say print “testing” and then redirect it to the output file while executing it at the command prompt.
Eg: redirect_output.py has the following code:
execution: python redirect_output.py > outputfile.
with open("file-name", "r") as fp: fileData = fp.read() #to print the contents of the file print(fileData)
Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the same interface like the general dictionaries but it traverse through keys and values in an ordered manner depending on when a key was first inserted.
from collections import OrderedDict d = OrderDict([('Company-id':1),('Company-Name':'Intellipaat')]) d.items() # displays the output as: [('Company-id':1),('Company-Name':'Intellipaat')]
lists – are better option to store collections of un-labelled items say all the files and sub directories in a folder.
Generally Search operation on dictionary object is faster than searching a list object.
>>> for i,v in enumerate([‘Python’,’Java’,’C++’]):
There are 4 different methods in “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 match and return them as a list
finditer() – finds all the occurrences of match and return them as an iterator.
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
2. reverse the list by using reversed()
Eg: for line in reversed(list(open(“file-name”,”r”))):
databases. Generally JSON is built on 2 structures.
1. A collection of <name, value> pairs.
2. An ordered list of values.
As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert json data into python using load() of json module.
numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays. scipy – this module provides methods for doing numeric integrals, solving differential equations, etc pylab – is a module for generating and saving plots
matplotlib – used for managing data and generating plots.
new – this method can be considered as a “constructor”. It is invoked to create an instance of a class with the statement say, 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,
invocation of del__ takes place and it defines behaviour during the garbage collection. Note: new , del are rarely used explicitly.
Encapsulation, Data Abstraction, Inheritance, Polymorphism.
A class is a blue print/ template of code /collection of objects that has same set of attributes and behaviour. To create a class use the keyword class followed by class name beginning with an uppercase letter. For example, a person belongs to class called Person class and can have the attributes (say first-name and last-name) and behaviours / methods (say showFullName()). A Person class can be defined as:
class Person(): #method def inputName(self,fname,lname): self.fname=fname self.lastname=lastname #method def showFullName() (self): print(self.fname+" "+self.lname)person1 = Person() #object instantiation person1.inputName("Ratan","Tata") #calling a method inputName person1. showFullName() #calling a method showFullName()
Note: whenever you define a method inside a class, the first argument to the method must be self (where self – is a pointer to the class instance). self must be passed as an argument to the method, though the method does not take any arguments.
The keywords that are used to handle exceptions in Python are:
try – it will try to execute the code that belongs to it. May be it used anywhere that keyboard input is required.
except – catches all errors or can catch a specific error. It is used after the try block.x = 10 + ‘Python’ #TypeError: unsupported operand type(s) …. try:
x = 10 + ‘Python’
print(“incompatible operand types to perform sum”)
raise – force an error to occur
o raise TypeError(“dissimilar data types”)
finally – it is an optional clause and in this block cleanup code is written here following “try” and “except”.
Single Inheritance – where a derived class acquires the members of a single super class.
multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 is inherited from base2.
hierarchical inheritance – from one base class you can inherit any number of child classes
multiple inheritance – a derived class is inherited from more than one base class.
class ParentClass: v1 = "from ParentClass - v1" v2 = "from ParentClass - v2"class ChildClass(ParentClass): passc = ChildClass() print(c.v1) print(c.v2)
class variables: these are the variables of class. All the objects of the same class will share value of “Class variables. They are accessed with their class name alone as “class- name.classvariable-name”. If you change the value of a class variable in one object, its new value is visible among all other objects of the same class. In the Java world, a variable that is declared as static is a class variable.
The following are the two possible ways by which you can trigger an exception in your Python script. They are:
1. raise — it is used to manually raise an exception general-form:
raise exception-name (“message to be conveyed”)
Eg: >>> voting_age = 15
>>> if voting_age < 18: raise ValueError(“voting age should be atleast 18 and above”) output: ValueError: voting age should be atleast 18 and above 2. assert statement 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 and exception can be done by making a programming mistake, but that’s not
usually a good way of triggering an exception.
isinstance() – this method checks the type of instance.
o for eg, isinstance(myObj, int) – returns True only when “myObj. class ” is “int”.
issubclass() – this method checks class inheritance
o for eg: issubclass(bool, int) – returns True because “bool” is a subclass of “int”.
o issubclass(unicode, str) – returns False because “unicode” is not a subclass of “str”.
Note: there is no difference in speed when program is read from .pyc or .py file; the only difference is the load time.
2. establish a connection to the database.
db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
3. initialize the cursor variable upon the established connection: c1 = db.cursor()
4. retrieve the information by defining a required query string. s = “Select * from dept”
5. fetch the data using fetch() methods and print it. data = c1.fetch(s)
6. close the database connection. db.close()
1. PythonWin ODBC module – limited development
2. mxODBC – commercial product
3. pyodbc – it is an open source Python package.
Eg: class Person:
empid = None
_salary = None #salary is a protected member & it can accessible by the subclasses of Person
b. scan the list from the end.
c. while scanning from right-to-left, delete all the duplicate elements from the list
append(element) – adds the given element at the end of the list which has called this method.
extend(another-list) – adds the elements of another-list at the end of the list which is called the extend method.
web2py – it is the simplest of all the web frameworks used for developing web applications.
cherryPy – it is a Python-based Object oriented Web framework.
Flask – it is a Python-based micro-framework for designing and developing web applications.
os.path.exists() – use this method to check for the existence of a file. It returns True if the file exists, false otherwise. Eg: import os; os.path.exists(‘/etc/hosts’)
os.path.isfile() – this method is used to check whether the give path references a file or not. It returns True if the path references to a file, else it returns false. Eg: import os; os.path.isfile(‘/etc/hosts’)
os.path.isdir() – this method is used to check whether the give path references a directory or not. It returns True if the path references to a directory, else it returns false. Eg: import os; os.path.isfile(‘/etc/hosts’)
os.path.getsize() – returns the size of the given file
os.path.getmtime() – returns the timestamp of the given path.
filter() – enables you to extract a subset of values based on conditional logic.
map() – it is a built-in function that applies the function to each item in an iterable.
reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.