Python interview questions

Python quiz questions

  • 1.

    Name few methods that are used to implement Functionally Oriented Programming in Python?

    Answer:

    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.

    View
  • 2.

    How do you check the file existence and their types in Python?

    Answer:

    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.

    View
  • 3.

    Name few Python Web Frameworks for developing web applications?

    Answer:

    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.

    View
  • 4.

    Differentiate between append() and extend() methods. ?

    Answer:

    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.

    View
  • 5.

    How do you remove duplicates from a list?

    Answer:

    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

    View
  • 6.

    How would you define a protected member in a Python class?

    Answer:

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

    View
  • 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:
    1. PythonWin ODBC module – limited development
    2. mxODBC – commercial product
    3. pyodbc – it is an open source Python package.

    View
  • 8.

    How to retrieve data from a table in MySQL database through Python code? Explain.

    Answer:

    1. import MySQLdb module as : import MySQLdb
    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()

    View
  • 9.

    Differentiate between “*.py” file nad “*.pyc” file?

    Answer:

    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.

    View
  • 10.

    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.

    View
  • 11.

    Does Python supports interfaces like in Java? Discuss.

    Answer:

    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.

    View
  • 12.

    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 “c1.func()”?

    Answer:

    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.

    View
  • 13.

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

    View
  • 14.

    How is Inheritance and Overriding methods are related?

    Answer:

    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.

    View
  • 15.

    Explain different ways to trigger / raise exceptions in your python script ?

    Answer:

    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.

    View
  • 16.

    How instance variables are different from class variables?

    Answer:

    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.

    View
  • 17.

    What is multithreading? Give an example.

    Answer:

    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.

    View
  • 18.

    Explain Inheritance in Python with an example.

    Answer:

    Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. They are different types of inheritance supported by Python. They are: single, multi-level, hierarchical and multiple inheritance. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class.
    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.
    ex:

    class ParentClass:
    v1 = "from ParentClass - v1"
    v2 = "from ParentClass - v2"class ChildClass(ParentClass):
    passc = ChildClass() print(c.v1) print(c.v2)
    View
  • 19.

    What are Exception Handling? How do you achieve it in Python?

    Answer:

    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’
    except:
    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”.

    View
  • 20.

    What is a Class? How do you create it in Python?

    Answer:

    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.

    View

© 2017 QuizBucket.org