1 . Explain Inheritance in Python with an example.
2 . Explain about ODBC and Python ?
- 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.
3 . What is Web Scraping? How do you achieve it in Python?
- 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 “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.
4 . Name the File-related modules in Python?
- Python provides libraries / modules with functions that enable you to manipulate text files and binary files on file system. Using them you can create files, update their contents, copy, and delete files. The libraries are : os, os.path, and shutil.
Here, os and os.path – modules include functions for accessing the filesystem
shutil – module enables you to copy and delete the files.
5 . Which command do you use to exit help window or help command prompt?
When you type quit at the help’s command prompt, python shell prompt will appear by closing the help window automatically.
6 . Explain Python's zip() function.?
- 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.
7 . How many kinds of sequences are supported by Python? What are they?
- Python supports 7 sequence types. They are str, list, tuple, unicode, bytearray, xrange, and buffer. where xrange is deprecated in python 3.5.X.
8 . Name few Python Web Frameworks for developing web applications?
- There are various web frameworks provided by Python. They are
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.
9 . What are Exception Handling? How do you achieve it in Python?
- Exception Handling prevents the codes and scripts from breaking on receipt of an error at run -time might be at the time doing I/O, due to syntax errors, data types doesn’t match. Generally it can be used for handling user inputs.
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”.
10 . Compare Java & Python
11 . Does the functions help() and dir() list the names of all the built_in functions and variables? If no, how would you list them?
- No. Built-in functions such as max(), min(), filter(), map(), etc is not apparent immediately as they are
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’, ……… ]
12 . How to display the contents of text file in reverse order?
- convert the given file into a list.
- reverse the list by using reversed()
Eg: for line in reversed(list(open(“file-name”,”r”))):
13 . Whenever Python exists Why does all the memory is not de-allocated / freed when Python exits?
- Whenever Python exits, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de – allocated/freed/uncollectable.
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.
14 . Explain split(), sub(), subn() methods of
- 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
15 . How do you perform pattern matching in Python? Explain
- Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc.The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.
16 . In the case of Multiple inheritance, if a child class C is derived from two base classes say A and B as: class C(A, B): -- which parent class's method will be invoked by the interpreter whenever object of class C calls a method func() that is existing in both the parent classes say A and B and does not exist in class C as
- since class C does not contain the definition of the method func(), they Python searches for the func() in parent classes. Since the search is performed in a left-to-right fashion, Python executes the method func() present in class A and not the func() method in B.
17 . As Everything in Python is an Object, Explain the characteristics of Python's Objects.
- 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
18 . What is multithreading? Give an example.
- It means running several different programs at the same time concurrently by invoking multiple threads. Multiple threads within a process refer the data space with main thread and they can communicate with each other to share information more easily.Threads are light-weight processes and have less memory overhead. Threads can be used just for quick task like calculating results and also running other processes in the background while the main program is running.
19 . How to retrieve data from a table in MySQL database through Python code? Explain.
20 . Which methods of Python are used to determine the type of instance and inheritance?
- 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”.
21 . How instance variables are different from class variables?
- Instance variables: are the variables in an object that have values that are local to that object. Two objects of the same class maintain distinct values for their variables. These variables are accessed with “object-name.instancevariable-name”.
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.
22 . Which statement of Python is used whenever a statement is required syntactically but the program needs no action?
23 . How is Inheritance and Overriding methods are related?
- If class A is a sub class of class B, then everything in B is accessible in /by class A. In addition, class A can define methods that are unavailable in B, and also it is able to override methods in B. For Instance, If class B and class A both contain a method called func(), then func() in class B can override func() in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it.
24 . How do you create a dictionary which can preserve the order of pairs?
25 . Does Python supports interfaces like in Java? Discuss.
- Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s “abc” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’c provides a sort of “understanding” about methods and their expected behaviour. This module was made available from Python 2.7 version onwards.
26 . Explain how to redirect the output of a python script from standout(ie., monitor) on to a file ?
- They are two possible ways of redirecting the output from standout to a file.
- 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”
- 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.
27 . Explain the shortest way to open a text file and display its contents.?
28 . Is Python object oriented? what is object oriented programming?
- Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.
29 . How do you remove duplicates from a list?
- a. sort the list
b. scan the list from the end.
c. while scanning from right-to-left, delete all the duplicate elements from the list
30 . What is TkInter?
- TkInter is 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.
31 . Explain different ways to trigger / raise exceptions in your python script ?
- The following are the two possible ways by which you can trigger an exception in your Python script. They are:
- 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.
32 . How are the functions help() and dir() different?
- 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.
33 . What is a Class? How do you create it in Python?
- 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:
def inputName(self,fname,lname): self.fname=fname self.lastname=lastname
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.
34 . Name and explain the three magic methods of Python that are used in the construction and initialization of custom Objects.
- 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 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.
35 . Name few methods for matching and searching the occurrences of a pattern in a given text String ?
- 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.
36 . What are Accessors, mutators, @property?
- 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.
37 . Explain all the file processing modes supported by Python ?
- Python allows you to open files in one of the three modes. They are:
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”.
38 . How do you check the file existence and their types in Python?
- 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.
39 . What is JSON? How would convert JSON data into Python data?
databases. Generally JSON is built on 2 structures.
- A collection of <name, value> pairs.
- 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.
40 . Explain the use of with statement?
- In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
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()
41 . What is the use of enumerate() in Python?
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++’]):
42 . How would you define a protected member in a Python class?
- All the members of a class in Python are public by default. You don’t need to define an access specifier for members of class. By adding ‘_’ as a prefix to the member of a class, by convetion you are telling others please don’t this object, if you are not a subclass the respective class.
Eg: class Person:
empid = None
_salary = None #salary is a protected member & it can accessible by the subclasses of Person
43 . Name few methods that are used to implement Functionally Oriented Programming in Python?
- Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list.
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.
44 . Explain how Python does Compile-time and Run-time code checking?
- 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 -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 exists.
45 . When does a dictionary is used instead of a list?
- Dictionaries – are best suited when the data is labelled, i.e., the data is a record with field names.
lists – are better option to store collections of un-labelled items say all the files and sub directories in a folder. List comprehension is used to construct lists in a natural way.
Generally Search operation on dictionary object is faster than searching a list object.
46 . Explain how to overload constructors or methods in Python.
- 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.
47 . Differentiate between .py and .pyc files?
- Both .py and .pyc files holds 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 program is read from .pyc or .py file; the only difference is the load time.
48 . Explain Python's pass by references Vs pass by value . (or) Explain about Python's parameter passing mechanism?
- 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.
49 . Differentiate between append() and extend() methods. ?
- Both append() and extend() methods are the methods of list. These methods a re used to add the elements at the end of 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.
50 . What is a Python module?
- A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules.Inside the module, you can refer to the module name as a string that is stored in the global variable name .
A module can be imported by other modules in one of the two ways. They are
- from module-name import