Python Basics – Interview Questions – 2


In Python Interview questions series this is the second post. This post also include interview questions for entry level programmer:

Expand All Questions   Collapse All Questions
Question 1: What are global, protected and private attributes in Python?

Answer:

Global attributes: Global Attributes are defined outside of a class and can be accessed from anywhere in the code, including inside classes. 

Protected attributes: Protected attributes are denoted with a single underscore (_) before the attribute name and are intended to be accessed only within the class and its subclasses. However, this is just a convention, Python don’t enforce the logic. When a developer see a _ before any attribute name he should use it in accordance with protected attribute.

Private attributes: Private attributes are denoted with double underscores (__) before the attribute name and are intended to be accessed only within the class in which they are defined. It is important to note that Python’s private attributes are not truly private, as they can still be accessed from outside the class by name mangling. However, this is discouraged as it goes against the principle of encapsulation, which is a fundamental concept in object-oriented programming.


Question 2: What are List and Tuples, what is the common difference between the two?

Answer:

  • List and Tuples are both sequence data type in Python which can contain any data type and objects of multiple data type at the same list or tuple. Both sequences are ordered and allow duplicates.
  • List in mutable and Tuple is immutable. Once created the values stored in Tuple can’t be changes while values stored in List can be modified.
  • List elements are represented by enclosed in square brackets [ ] while tuple elements are represented by enclosing in parenthesis ( ).
  • Tuples are generally fast in processing than List because they are immutable.
  • List have many functions to work with while tuple don’t have many functions as it is immutable.
  • List with single element can be defined like : L=[‘first_elem’] but if you want to define tuple with single element it should end with a comma (,) e.g. t = [‘first_elem’,] . If single element tuple doesn’t end with comm then the variable will take the type of it’s element.

Question 3: What are dunder or magic methods in python?

Answer: Magic methods or Dunder methods are the methods with names starting and ending with double underscore (double underscore). These are special methods in python objects to implement specific functionality like class operations, operator overloading related to mathematics, object comparison, string manipulation etc. Dunder methods should not be called directly, only in case if superclass methods need to be invoked then only they may be used.


Question 4: What are mutable and immutable data types in Python?

Answer: In Python, data types can be classified as mutable or immutable based on whether their values can be changed after they are created.

Mutable Data Types: Mutable data types are those whose values can be modified after they are created. You can change, add, or remove elements without creating a new object.

List, Set and Dictionary are mutable data types.

>>> l = [1]
>>> l
[1]
>>> id(l)
2777545691712
>>> l *= 20
>>> id(l)
2777545691712
>>> # as list id didn't change after multiplication - mutable

Immutable Data Types: Immutable data types are those whose values cannot be changed after they are created. Any modification to an immutable object results in the creation of a new object.

integer, float, tuple, frozenset and string are some examples of immutable data type.

>>> x = 10
>>> id(x)
140713723689688
>>> x += 1
>>> id(x)
140713723689720
>>> # as integer id changes on addition - immutable

Question 5: What are docstring in Python?

Answer: A docstring in Python is a special kind of string used to document modules, classes, functions, and methods. It provides a convenient way of associating documentation with Python code. Docstrings are placed right after the definition of the module, class, function, or method. Docstrings can be assessed using __doc__ attribute of modules, classes or functions etc. It is a convention to use “”” or ”’ (triple quotes/multiline strings) for docstrings. single quotes and double quote strings can also be used as docstrings, but they are usually avoided because of docstrings are mostly multiline.


Related Questions:

Question 5.1: Provide an example of docstring in Python.

Answer: Please find the following example:

"""
Module level docstring
"""
def MyFunction():
    'Function Level docstring'
    pass

class MyClass:
    """
    Class level docstring
    """
    def __init__(self):
        "Method level docstring"
        pass

let’s assume we save the file as docstring_example.py then the docstrings can be accessed in python console as following:

>>> import docstring_example
>>> print(docstring_example.__doc__)

Module level docstring

>>> print(docstring_example.MyClass.__doc__)

    Class level docstring

>>> print(docstring_example.MyClass.__init__.__doc__)
Method level docstring
>>> print(docstring_example.MyFunction.__doc__)
Function Level docstring
>>>

Question 6: What are unit tests in Python?

Answer: Unit tests in Python are a way to test individual units of code, such as functions or methods, to ensure they work as expected. They help in verifying that each part of the program behaves correctly under various conditions. Unit tests are an essential part of the software development process, promoting code reliability and maintainability.

Unit tests help in identifying bugs early, providing clean, modular and maintainable code. It is easier to refactor the code which has unit test cases written for it. Python has a library named “unittest” for writing unit tests


Realted Questions:

Question 6.1: Provide an example of unit test in Python.

Answer: Writing unit test cases involves identifying units and coding test cases, test suits and test runner. The example of unittest module is as follows:

# math_operations.py
# functions to be tested or units
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

Unit testing code:

# test_math_operations.py
import unittest
from math_operations import add, subtract

class TestMathOperations(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)
        self.assertEqual(add(0, 0), 0)

    def test_subtract(self):
        self.assertEqual(subtract(5, 3), 2)
        self.assertEqual(subtract(0, 1), -1)
        self.assertEqual(subtract(-1, -1), 0)

if __name__ == '__main__':
    unittest.main()

Running unit tests:

[command-prompt]$ python test_math_operations.py
..
---------------------------------------------------
Ran 2 tests in 0.000s

OK

Question 7: What is break, continue and pass in Python?

Answer: In Python break, continue and pass are control flow statements that alter the execution flow of loops and other code blocks. Specific meanings are as following:

break: The break statement is used to exit a loop prematurely. When break is encountered, the loop terminates immediately, and control is transferred to the first statement after the loop.

continue: The continue statement is used to skip the rest of the code inside the current iteration of the loop and move to the next iteration. It does not terminate the loop but skips to the next cycle.

pass: The pass statement is a null operation; it does nothing when executed. It is used as a placeholder in situations where a statement is syntactically required but you do not want to execute any code. It is commonly used in empty functions, loops and conditions for placeholder for future code.


Question 8: What is the use of self in Python?

Answer: In Python self is a conventional name used to represent the instance of a class within its methods (it is not a keyword in python). It allows you to access the attributes and methods of the class in object-oriented programming. Self as the first argument to class methods, can be used to access instance and class variables and other methods of the class.


Question 9: What are common built-in types in Python?

Answer: The hierarchy of python built-in data types is as following:


Question 10: What is variable scope in Python?

Answer: In Python, scope refers to the region of the code where a particular variable or name is accessible. In python the scope is determined by LEGB order, which stands for Local, Enclosed, Global and Built-in.

Local Scope: The scope within a function. Variables defined inside a function are local to that function and cannot be accessed outside of it. Code Example:

Enclosed Scope: The scope of any enclosing functions, also known as non-local scope. This is relevant in nested functions.

Global Scope: The scope of the top-level of the script or module. Variables defined at this level are accessible throughout the module.

Built-in Scope: The scope of built-in names provided by Python. These are always available and include functions like print(), len() etc.

When you reference a variable, Python searches for it in this order: First in the Local scope, then in the Enclosing scopes, followed by the Global scope, and finally in the Built-in scope. Following code shows an example of all scopes variable.

global_var = "global"

def outer_function():
    enclosing_var = "enclosing"

    def inner_function():
        local_var = "local"
        print(local_var)  # Local scope
        print(enclosing_var)  # Enclosing scope
        print(global_var)  # Global scope
        print(len("Hello")) # Built-in scope

    inner_function()

outer_function()

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post