Python interview questions

Python quiz questions

  • 1.

    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.

  • 2.

    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.

  • 3.

    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.

  • 4.

    Name few Python modules for Statistical, Numerical and scientific computations ?


    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.

  • 5.

    What is JSON? How would convert JSON data into Python data?


    JSON – stands for JavaScript Object Notation. It is a popular data format for storing data in NoSQL
    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.

  • 6.

    How to display the contents of text file in reverse order?


    1. convert the given file into a list.
    2. reverse the list by using reversed()
    Eg: for line in reversed(list(open(“file-name”,”r”))):

  • 7.

    Explain split(), sub(), subn() methods of “re” module in Python.


    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

  • 8.

    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.

  • 9.

    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.

  • 10.

    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.

  • 11.

    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++’]):
    0 Python
    1 Java
    2 C++

  • 12.

    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.
    Generally Search operation on dictionary object is faster than searching a list object.

  • 13.

    How do you create a dictionary which can preserve the order of pairs?


    We know that regular Python dictionaries iterate over <key, value> pairs in an arbitrary order, hence they do not preserve the insertion order of <key, value> pairs.
    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')]
  • 14.

    Explain the shortest way to open a text file and display its contents.?


    The shortest way to open a text file is by using “with” command as follows:

    with open("file-name", "r") as fp:
    fileData =
    #to print the contents of the file print(fileData)
  • 15.

    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.
    1. Open an output file in “write” mode and the print the contents in to that file, using sys.stdout attribute.
    import sys
    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: has the following code:
    print “Testing”
    execution: python > outputfile.

  • 16.

    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”.

  • 17.

    Explain the use “with” in python?


    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:
    processing statements
    note: no need to close the file by calling close() upon file-var.close()

  • 18.

    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.

  • 19.

    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
    1. import
    2. from module-name import or

  • 20.

    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.


© 2017