Python interview questions

Python quiz questions

  • 1.

    How Can You Perform Unit Testing In Python?

    Answer:

    Python packages a unit testing framework called <Unittest>. It supports the following features.

    • Automation testing.
    • Sharing of setup and shutdown code for tests.
    • Aggregation of tests into collections.
    • Independence of the tests from the reporting framework.
    View
  • 2.

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

    Answer:

    Yes. PyChecker is a static analysis tool. It finds bugs in the source code and raises alerts for the issues in code complexity or style.

    Pylint is another tool that checks if a module meets the coding standard. It also supports additional plug-ins to enable custom features.

    View
  • 3.

    How Will You Share Global Variables Across Modules?

    Answer:

    If you add a variable to the <__builtin__> module, it will be accessible as if a global from any other module that includes <__builtin__> — which is all of them, by default.

    a.py contains
    print foo
    b.py contains
    import __builtin__
    __builtin__.foo = 1
    import a
    The result is that "1" is printed.

    Note: Python 3 introduced the builtins keyword as a replacement for the <__builtin__>.

    View
  • 4.

    How Will You Set A Global Variable Inside A Function?

    Answer:

    You can use a global variable in other functions by declaring it as global in each function that assigns to it:

    globvar = 0
    def set_globvar_to_one():
        global globvar    # Needed to modify global copy of globvar
        globvar = 1
    def print_globvar():
        print globvar     # No need for global declaration to read value of globvar
    set_globvar_to_one()
    print_globvar()       # Prints 1

    I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that’s what you’re playing with by explicitly requiring the global keyword.

    View
  • 5.

    How Will You Convert A String To A Number In Python?

    Answer:

    Python provides the <int()> method, a standard built-in function to convert a string into an integer value.

    You can call it with a string containing a number as the argument, and it returns the number converted to an actual integer.

    print int("1") + 1
    The above prints 2.

     

    View
  • 6.

    What Are The Different Methods Python Provides For Copying An Object?

    Answer:

    We can either use a “Shallow Copy” or follow a “Deep Copy” approach.

    Shallow Copy Method.

    The content of an object (say dictionary) doesn’t get copied by value but by creating a new reference.

    >>> a = {1: [1,2,3]}
    >>> b = a.copy()
    >>> a, b
    ({1: [1, 2, 3]}, {1: [1, 2, 3]})
    >>> a[1].append(4)
    >>> a, b
    ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

    Deep Copy Method.

    It copies all the contents by value.

    >>> c = copy.deepcopy(a)
    >>> a, c
    ({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
    >>> a[1].append(5)
    >>> a, c
    ({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

     

    View
  • 7.

    Does Python Allow Arguments Pass By Value Or Pass By Reference?

    Answer:

    Neither the arguments are Pass by Value nor does Python supports Pass by reference. Instead, they are Pass by assignment.

    The parameter which you pass is originally a reference to the object not the reference to a fixed memory location. But the reference is passed by value. Additionally, some data types like strings and tuples are immutable whereas others are mutable.

    View
  • 8.

    What Is The Best Approach To Store A List Of An Employee’s First And Last Names?

    Answer:

    A list of first and last names is best stored as a list of dictionaries. The following format can be used.

    {'first_name':'Example','last_name':'TechBeamers'}

     

    View
  • 9.

    How Will You Print The Sum Of Numbers Starting From 1 To 100 (Inclusive Of Both)?

    Answer:

    print sum(range(1,101))
    #range() returns a list to the sum function containing
    #all the numbers from 1 to 100. Please see that
    #the range function does not include the end given (101 here).
    print(sum(xrange(1, 101)))
    #xrange() returns an iterator rather than a list
    #which is less heavy in the memory.

     

    View
  • 10.

    How Will You Remove The Duplicate Elements From The Given List?

    words = [‘one’, ‘one’, ‘two’, ‘three’, ‘three’, ‘two’]

    Answer:

    A simple solution is to iterate over the list, identify duplicates and remove them.

    But the best solution which we can recommend is as follows.

    a = [1,2,2,3]
    list(set(a))

    The set is another type available in Python. It doesn’t allow copies and provides some good functions to perform set operations like union, difference etc.

    View
  • 11.

    How Will You Run A Subprocess Or An External Program With Arguments In Python?

    Answer:

    There are two methods which can run a subprocess or external programs. First is to use the subprocess module in the stdlib.

    from subprocess import call
    call(["ls", "-l"])

    The advantage of subprocess vs system is that it is more flexible. You can get the stdout, stderr, the “real” status code and better error handling. The second approach to run a program with arguments is as follows.

    subprocess.Popen(arglist,stdout=outputfile)

     

    View
  • 12.

    What Are Generators In Python?

    Answer:

    Generators are a way of implementing iterators. A generator function is a normal function except that it contains yield expression in the function definition making it a generator function.

    This function returns a generator iterator known as a generator.

    To get the next value from a generator, we use the same built-in function as for iterators: <next(). next()> takes care of calling the generator’s <__next__()> method.

    View
  • 13.

    What Are Iterators In Python?

    Answer:

    Iterators in Python enables to traverse containers like a list or a set of elements. For a container to support iterator, it must provide the <__iter__()> method.

    container.__iter__() :
    # This returns an iterator object.

     

    View
  • 14.

    Why Is The “Pass” Keyword Used For In Python?

    Answer:

    The “pass” keyword is a no-operation statement in Python. It signals that no action is required. It works as a placeholder in compound statements which are intentionally left blank.

    >>> if x==0:
            pass
        else:
            print "x!=0"

     

    View
  • 15.

    What Are The Different Ways To Generate Random Numbers In Python?

    Answer:

    #1. random() - This command returns a floating point number, between 0 and 1.
    #2. uniform(X, Y) - It returns a floating point number between the values given as X and Y.
    #3. randint(X, Y) - This command returns a random integer between the values given as X and Y.

     

    View
  • 16.

    What Is Slicing In Python? Explain With Example.

    Answer:

    Slicing in Python is a mechanism to select a range of items from Sequence types like strings, list, tuple, etc.

    >>> l=[1,2,3,4,5]
    >>> l[1:3]
    [2, 3]
    >>> l[1:-2]
    [2, 3]
    >>> l[-3:-1]      # negative indexes in slicing
    [3, 4]
    >>> s="Hello World"
    >>> s[1:3]
    'el'
    >>> s[:-5]
    'Hello '
    >>> s[-5:]
    'World'

     

    View
  • 17.

    What Is Pickling And How Does It Different From Unpickling?

    Answer:

    Pickling is a process by which a Python object get converted into a string via a pickle module. The process then puts it into a file by calling the dump() method.

    Whereas unpickling does the reverse of the above-said process. It retrieves the stored string and turns it back into an object.

    View
  • 18.

    What Is A Negative Index In Python?

    Answer:

    In Python, we can access both arrays & lists using a positive or negative numbers (aka index). A negative index reads the list elements from the end counting in the backward direction. Check out from the example given below.

    >>> import array
    >>> a = [1, 2, 3]
    >>> print a[-3]
    1
    >>> print a[-2]
    2
    >>> print a[-1]
    3

     

    View
  • 19.

    Why Is <__init__.Py> Module Used In Python?

    Answer:

    The <__init__.py> module can help in fulfilling following objectives.

    1. It makes Python interpret directories as containing packages by excluding the ones with a common name such as string.

    2. It grants a programmer with the control to decide which directory is a package and which is not.

    3. However, the <__init__.py> can also be an empty file. It can then help in executing the initialization code for a package or setting the <__all__> variable.

    View
  • 20.

    What Are The Core Default Modules Available In Python? List Down A Few Of Them.

    Answer:

    Following are a few of the default modules available in Python.

    • email – Help to parse, handle, and generate email messages.
    • string – Contains functions to process standard Python strings.
    • sqlite3 – Provides methods to work with the SQLite database.
    • XML – Enables XML support.
    • logging – Adds support for log classes and methods.
    • traceback – Allows to extract and print stack trace details.
    View

© 2017 QuizBucket.org