Python Interview Questions for Freshers

1. What is __init__?

__init__ is a constructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables.

# class definition
class Student:
   def __init__(self, fname, lname, age, section):
       self.firstname = fname
       self.lastname = lname
       self.age = age
       self.section = section
# creating a new object
stu1 = Student("Sara", "Ansh", 22, "A2")

2. What is the difference between Python Arrays and lists??

  • Arrays in Python can only contain elements of the same data type, i.e., the data type of the array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists.
  • Lists in Python can contain elements of different data types, i.e., lists can be heterogeneous. However, they consume more memory.
import array
a = array.array('i', [1, 2, 3])
for i in a:
    print(i, end=' ')   #OUTPUT: 1 2 3
a = array.array('i', [1, 2, 'string'])   #OUTPUT: TypeError: an integer is required (got type str)
a = [1, 2, 'string']
for i in a:
   print(i, end=' ')   #OUTPUT: 1 2 string

3. Explain how can you make a Python Script executable on Unix?

  • Script file must begin with #!/usr/bin/env python

4. What is slicing in Python?

  • As the name suggests, ‘slicing’ is taking parts of.
  • Syntax for slicing is [start : stop : step]
  • start is the starting index from where to slice a list or tuple
  • stop is the ending index or where to stop.
  • step is the number of steps to jump.
  • Default value for start is 0, stop is number of items, step is 1.
  • Slicing can be done on strings, arrays, lists, and tuples.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers[1::2])  #output : [2, 4, 6, 8, 10]

5. What is docstring in Python?

  • Documentation string or docstring is a multiline string used to document a specific code segment.
  • The docstring should describe what the function or method does.

6. What are unit tests in Python?

  • Unit test is a unit testing framework of Python.
  • Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at some point in time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations.
  • This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software.

7. What is break, continue and pass in Python?

BreakThe break statement terminates the loop immediately and the control flows to the statement after the body of the loop.
ContinueThe continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop.
PassAs explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc.
pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3]
for p in pat:
   pass
   if (p == 0):
       current = p
       break
   elif (p % 2 == 0):
       continue
   print(p)   # output => 1 3 1 3 1
print(current)   # output => 0

8. What is the use of self in Python?

Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.

9. What are global, protected and private attributes in Python?

  • Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword.
  • Protected attributes are attributes defined with an underscore prefixed to their identifier e.g., _sara. They can still be accessed and modified from outside the class they are defined in, but a responsible developer should refrain from doing so.
  • Private attributes are attributes with a double underscore prefixed to their identifier e.g., __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made.

10. What are modules and packages in Python?

Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages:

  • Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone.
  • Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program.
  • Reusability: Functions defined in a module can be easily reused by other parts of the application.
  • Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program.

Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar.

Packages allow for hierarchical structuring of the module namespace using dot notation. As modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names.
Creating a package is easy since it makes use of the system's inherent file structure. Just place the modules into a folder, and the folder name becomes the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot.

Note: You can technically import the package as well, but it doesn’t import the modules within the package to the local namespace, thus it is practically useless.

11. What is pass in Python?

The pass keyword represents a null operation in Python. It is generally used for filling up empty blocks of code which may execute during runtime but have not yet been written. Without the pass statement in the following code, we may run into errors during execution.

def myEmptyFunc():
    # do nothing
    pass

myEmptyFunc()    # nothing happens

## Without the pass keyword
# File "<stdin>", line 3
# IndentationError: expected an indented block

12. What are the common built-in data types in Python?

There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations, type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of variables. These data types can be grouped into the following categories:

•None Type

None keyword represents the null values in Python.

Class NameDescription
NoneTypeRepresents the NULL values in Python.

•Numeric Types

There are three distinct numeric types integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers.

Class NameDescription
intStores integer literals including hex, octal and binary numbers.
floatStores decimal values and/or exponent signs as floating-point numbers.
complexStores complex numbers in the form (A + Bj) with real and imag attributes.
boolStores boolean value (True or False).

Note: The standard library also includes fractions for rational numbers and decimal for high-precision floating-point numbers.

•Sequence Types

Includes lists, tuples, and range objects. They support in and not in operators for traversal.

Class NameDescription
listMutable sequence to store items.
tupleImmutable sequence to store items.
rangeImmutable sequence of numbers generated at runtime.
strImmutable sequence of Unicode characters for text.

•Mapping Types

Python provides dictionaries that map hashable keys to values.

Class NameDescription
dictStores key: value pairs.

•Set Types

Python supports set (mutable) and frozenset (immutable).

Class NameDescription
setMutable unordered collection of distinct objects.
frozensetImmutable collection of distinct objects.

Note: set is mutable and cannot be used as dictionary keys, while frozenset is hashable and can be used as keys or elements of another set.

•Modules

A module supports attribute access: mymod.myobj. The module’s symbol table resides in __dict__.

•Callable Types

Callable types are those to which function calls can be applied, including functions, methods, generator functions, and some built-in classes. Refer to Python Docs for details.

13. What are lists and tuples? What is the key difference between the two?

Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parentheses ('ansh', 5, 0.97).

The key difference between them is that lists are mutable, meaning they can be modified, appended, or sliced, whereas tuples are immutable and cannot be changed once created.

my_tuple = ('sara', 6, 5, 0.97)
my_list = ['sara', 6, 5, 0.97]

print(my_tuple[0])     # output => 'sara'
print(my_list[0])      # output => 'sara'

my_tuple[0] = 'ansh'   # modifying tuple => throws an error
my_list[0] = 'ansh'    # modifying list => list modified

print(my_tuple[0])     # output => 'sara'
print(my_list[0])      # output => 'ansh'

14. What is Scope in Python?

Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant.Namespaces uniquely identify all the objects inside a program. Each namespace has its own scope where its objects can be accessed without any prefix.

A few examples of scope created during code execution in Python are:

  • Local scope: Objects available only inside the current function.
  • Global scope: Objects available throughout the entire program once created.
  • Module-level scope: Global objects of the current module accessible in the program.
  • Outermost scope: All built-in names callable in the program. Python searches this scope last when resolving a name.

Note: Local scope objects can be synced with global scope objects using the global keyword.

15. What is PEP 8 and why is it important?

PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes.PEP 8 is especially important since it documents the style guidelines for Python code. Contributing to the Python open-source community requires following these style guidelines sincerely and strictly.

16. What is an Interpreted language?

An Interpreted language executes its statements line by line. Languages such as Python, JavaScript, R, PHP, and Ruby are prime examples of interpreted languages. Programs written in an interpreted language run directly from the source code, with no intermediary compilation step.

17. What is a dynamically typed language?

Before understanding a dynamically typed language, we should learn about typing. Typing refers to type-checking in programming languages. In a strongly-typed language such as Python, "1" + 2 will result in a type error since these languages don't allow "type-coercion" (implicit conversion of data types). In a weakly-typed language such as JavaScript, the same expression will output "12".

Type-checking can be done at two stages:

  • Static: Data types are checked before execution.
  • Dynamic: Data types are checked during execution.

Python is an interpreted language that executes each statement line by line, so type-checking is done on the fly during execution. Hence, Python is a Dynamically Typed Language.

Dynamically Typed Language

18. What is Python? What are the benefits of using Python

Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools and libraries. Additionally, Python supports objects, modules, threads, exception-handling, and automatic memory management, which help in modeling real-world problems and building applications to solve them.

Benefits of using Python:

  • Python has a simple, easy-to-learn syntax that emphasizes readability and reduces the cost of program maintenance. The language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse.
  • Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment.

Python Interview Questions for Experienced

1. What are Dict and List comprehensions?

Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose.

  • Performing mathematical operations on the entire list
my_list = [2, 3, 5, 7, 11]
squared_list = [x**2 for x in my_list]    # list comprehension
# output => [4 , 9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list}    # dict comprehension
# output => {11:121, 2:4, 3:9, 5:25, 7:49}
  • Performing conditional filtering operations on the entire list
squared_list = [x**2 for x in my_list if x%2 != 0]    # list comprehension
# output => [9 , 25 , 49 , 121]
squared_dict = {x:x**2 for x in my_list if x%2 != 0}    # dict comprehension
# output => {11:121, 3:9, 5:25, 7:49}
  • Combining multiple lists into one
a = [1, 2, 3]
b = [7, 8, 9]
[(x + y) for (x,y) in zip(a,b)]  # parallel iterators
# output => [8, 10, 12]
[(x,y) for x in a for y in b]    # nested iterators
# output => [(1,7),(1,8),(1,9),(2,7),(2,8),(2,9),(3,7),(3,8),(3,9)]
  • Flattening a multi-dimensional list
my_list = [[10,20,30],[40,50,60],[70,80,90]]
flattened = [x for temp in my_list for x in temp]
# output => [10,20,30,40,50,60,70,80,90]

Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set-builder notation rather than map and filter functions in Python.

2. What are decorators in Python?

Decorators in Python are functions that add functionality to an existing function without changing its structure. They are represented using @decorator_name and are called in a bottom-up fashion.

# decorator function to convert to lowercase
def lowercase_decorator(function):
    def wrapper():
        func = function()
        string_lowercase = func.lower()
        return string_lowercase
    return wrapper

# decorator function to split words
def splitter_decorator(function):
    def wrapper():
        func = function()
        string_split = func.split()
        return string_split
    return wrapper

@splitter_decorator   # executed next
@lowercase_decorator  # executed first
def hello():
    return 'Hello World'

hello()  # output => ['hello', 'world']

Decorators can also accept arguments and modify them before passing to the function. The inner nested function (wrapper) enforces encapsulation and remains hidden from the global scope.

# decorator function to capitalize names
def names_decorator(function):
    def wrapper(arg1, arg2):
        arg1 = arg1.capitalize()
        arg2 = arg2.capitalize()
        string_hello = function(arg1, arg2)
        return string_hello
    return wrapper

@names_decorator
def say_hello(name1, name2):
    return 'Hello ' + name1 + '! Hello ' + name2 + '!'

say_hello('sara', 'ansh')  # output => 'Hello Sara! Hello Ansh!'

3. What is Scope Resolution in Python?

Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play automatically in Python. A few examples:

  • Python modules like math and cmath share many functions such as log10(), acos(), exp(). To avoid ambiguity, prefix them with the module: math.exp() and cmath.exp().
  • Consider a global variable temp set to 10 and a local variable temp set to 20 inside a function. Python keeps their namespaces separate, so modifying the local variable does not affect the global one.
temp = 10   # global-scope variable
def func():
     temp = 20   # local-scope variable
     print(temp)

print(temp)   # output => 10
func()       # output => 20
print(temp)  # output => 10

This behavior can be overridden using the global keyword inside the function:

temp = 10   # global-scope variable
def func():
     global temp
     temp = 20   # modifies global variable
     print(temp)

print(temp)   # output => 10
func()       # output => 20
print(temp)  # output => 20

4. What are Python namespaces? Why are they used?

A namespace in Python ensures that object names in a program are unique and can be used without conflict. Python implements these namespaces as dictionaries with the 'name' as key mapped to a corresponding 'object' as value. This allows multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are:

  • Local Namespace: Includes local names inside a function. The namespace is temporarily created for a function call and gets cleared when the function returns.
  • Global Namespace: Includes names from various imported packages/modules used in the current project. Created when the package is imported and lasts until the execution of the script.
  • Built-in Namespace: Includes built-in functions of core Python and built-in names for various exceptions.

The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace ends as well. Hence, it isn't possible to access inner namespace objects from an outer namespace.

Python Namespaces

5. How is memory managed in Python?

  • Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in the form of a private heap space dedicated to Python. All Python objects are stored in this heap, and being private, it is inaccessible to the programmer. However, Python provides some core API functions to work upon the private heap space.
  • Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
Memory Management in Python

6. What is lambda in Python? Why is it used?

Lambda is an anonymous function in Python that can accept any number of arguments but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways:

  • Assigning lambda functions to a variable:
mul = lambda a, b : a * b
print(mul(2, 5))    # output => 10
  • Wrapping lambda functions inside another function:
def myWrapper(n):
    return lambda a : a * n

mulFive = myWrapper(5)
print(mulFive(2))    # output => 10

7. Explain how to delete a file in Python?

Use command os.remove(file_name)

import os
os.remove("ChangedFile.csv")
print("File Removed!")

8. What are negative indexes and why are they used?

  • Negative indexes are the indexes from the end of the list, tuple, or string.
  • Arr[-1] means the last element of array Arr[].
arr = [1, 2, 3, 4, 5, 6]
# get the last element
print(arr[-1])  # output 6
# get the second last element
print(arr[-2])  # output 5

9. What does *args and **kwargs mean?

*args

  • *args is a special syntax used in the function definition to pass variable-length arguments.
  • “*” means variable length and “args” is the name used by convention. You can use any other.
def multiply(a, b, *argv):
    mul = a * b
    for num in argv:
        mul *= num
    return mul

print(multiply(1, 2, 3, 4, 5))  # output: 120

**kwargs

  • **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments.
  • Here, also, “kwargs” is used just by convention. You can use any other name.
  • Keyworded argument means a variable that has a name when passed to a function.
  • It is actually a dictionary of the variable names and its value.
def tellArguments(**kwargs):
    for key, value in kwargs.items():
        print(key + ": " + value)

tellArguments(arg1="argument 1", arg2="argument 2", arg3="argument 3")
# output:
# arg1: argument 1
# arg2: argument 2
# arg3: argument 3

10. Explain split() and join() functions in Python?

  • You can use split() function to split a string based on a delimiter into a list of strings.
  • You can use join() function to join a list of strings based on a delimiter to form a single string.
string = "This is a string."
string_list = string.split(' ')  # delimiter is 'space' character
print(string_list)  # output: ['This', 'is', 'a', 'string.']
print(' '.join(string_list))  # output: This is a string.

11. What are iterators in Python?

  • An iterator is an object.
  • It remembers its state i.e., where it is during iteration.
  • __iter__() method initializes an iterator.
  • It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of the iterable object,__next__() must raise StopIteration exception.
  • It is also self-iterable.
  • Iterators are objects with which we can iterate over iterable objects like lists, strings, etc.
class ArrayList:
    def __init__(self, number_list):
        self.numbers = number_list

    def __iter__(self):
        self.pos = 0
        return self

    def __next__(self):
        if self.pos < len(self.numbers):
            self.pos += 1
            return self.numbers[self.pos - 1]
        else:
            raise StopIteration

array_obj = ArrayList([1, 2, 3])
it = iter(array_obj)
print(next(it))  # output: 1
print(next(it))  # output: 2
print(next(it))  # output: 3
# Throws StopIteration Exception

12. How are arguments passed by value or by reference in python?

  • Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object.
  • Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object.

In Python, arguments are passed by reference, i.e., a reference to the actual object is passed.

def appendNumber(arr):
    arr.append(4)

arr = [1, 2, 3]
print(arr)          # Output: => [1, 2, 3]
appendNumber(arr)
print(arr)          # Output: => [1, 2, 3, 4]

13. How Python is interpreted?

  • Python as a language is not strictly interpreted or compiled. Interpreted or compiled is a property of the implementation. Python is generally bytecode-interpreted (a set of interpreter-readable instructions).
  • Source code is a file with .py extension.
  • Python compiles the source code into a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called bytecode.
  • .py source code is first compiled to give .pyc, which is bytecode. This bytecode can then be interpreted by CPython or JIT-compiled by PyPy.

14. What is the difference between .py and .pyc files?

  • .py files contain the source code of a program, whereas .pyc files contain the bytecode of your program. Bytecode is generated after compiling the .py file. Note that .pyc files are only created for imported files, not all files you run.
  • Before executing a Python program, the interpreter checks for compiled files. If found, the virtual machine executes the .pyc. If not, it looks for the .py file, compiles it to .pyc, and then executes it.
  • Having .pyc files saves compilation time on subsequent runs.

15. What is the use of help() and dir() functions?

help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, an interactive help utility is launched on the console.
dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data rather than the complete information.

  • For Modules/Library objects, it returns a list of all attributes contained in that module.
  • For Class objects, it returns a list of all valid attributes and base attributes.
  • With no arguments passed, it returns a list of attributes in the current scope.

16. What is PYTHONPATH in Python?

PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.

17. What are generators in Python?

Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object.
Let's try and build a generator for Fibonacci numbers:

# generate fibonacci numbers upto n
def fib(n):
    p, q = 0, 1
    while p < n:
        yield p
        p, q = q, p + q

x = fib(10)  # create generator object

# iterating using __next__()
x.__next__()  # output => 0
x.__next__()  # output => 1
x.__next__()  # output => 1
x.__next__()  # output => 2
x.__next__()  # output => 3
x.__next__()  # output => 5
x.__next__()  # output => 8
# error

# iterating using loop
for i in fib(10):
    print(i)  # output => 0 1 1 2 3 5 8

18. What is pickling and unpickling?

Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it later to obtain the original object. Here, the pickle module comes into play.

Pickling:

  • Pickling is the name of the serialization process in Python. Any object can be serialized into a byte stream and dumped as a file in memory. Pickle objects can be compressed further, and the serialization is portable across Python versions.
  • The function used for this process is pickle.dump().

Unpickling:

  • Unpickling is the inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads them into memory.
  • The function used for this process is pickle.load().

Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files and differs significantly from pickle.

Pickle Module in Python

19. What is the difference between xrange and range in Python?

xrange() and range() are similar in functionality. Both generate a sequence of integers, but range() returns a Python list, whereas xrange() returns an xrange object.

So how does that make a difference?

Unlike range(), xrange() doesn’t generate a static list. It creates values on the go, using a technique commonly associated with generators, called "yielding". Yielding is crucial when memory is limited. Creating a static list as in range() can lead to MemoryError, while xrange() handles it optimally with minimal memory usage.


for i in xrange(10):    # numbers from 0 to 9
    print i               # output => 0 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10):  # numbers from 1 to 9
    print i               # output => 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10, 2):  # skip by two for next
    print i               # output => 1 3 5 7 9

Note: xrange has been deprecated as of Python 3.x. Now range behaves exactly like xrange did in Python 2.x, which made xrange() preferable over the original range() in Python 2.x.

20. How do you copy an object in Python?

In Python, the assignment statement (= operator) does not copy objects. It creates a binding between the existing object and the target variable name. To create copies of an object, we use the copy module. There are two ways of creating copies using this module:

Shallow Copy

A shallow copy is a bit-wise copy of an object. The copied object has an exact copy of the values in the original object. If any value is a reference to another object, only the reference addresses are copied.

Deep Copy

A deep copy copies all values recursively from source to target object. It duplicates even the objects referenced by the source object.


from copy import copy, deepcopy

list_1 = [1, 2, [3, 5], 4]

## shallow copy
list_2 = copy(list_1)
list_2[3] = 7
list_2[2].append(6)
list_2    # output => [1, 2, [3, 5, 6], 7]
list_1    # output => [1, 2, [3, 5, 6], 4]

## deep copy
list_3 = deepcopy(list_1)
list_3[3] = 8
list_3[2].append(7)
list_3    # output => [1, 2, [3, 5, 6, 7], 8]
list_1    # output => [1, 2, [3, 5, 6], 4]

Python OOPS Interview Questions

1. How will you check if a class is a child of another class?

This is done by using a method called issubclass() provided by Python. The method tells us if any class is a child of another class by returning true or false accordingly.

Example:

class Parent(object):
    pass   

class Child(Parent):
    pass   

# Driver Code
print(issubclass(Child, Parent))    # True
print(issubclass(Parent, Child))    # False
  • We can check if an object is an instance of a class by making use of the isinstance() method:
obj1 = Child()
obj2 = Parent()

print(isinstance(obj2, Child))    # False 
print(isinstance(obj2, Parent))   # True

2. What is init method in python?

The __init__ method works similarly to constructors in Java. This method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation.

Example:

class InterviewbuzzEmployee:

    # __init__ method / constructor
    def __init__(self, emp_name):
        self.emp_name = emp_name

    # introduce method
    def introduce(self):
        print('Hello, I am', self.emp_name)

emp = InterviewbuzzEmployee('Mr Employee')  # __init__ method is called here
emp.introduce()

3. Why is finalize used?

The finalize() method is used for freeing up unmanaged resources and performing cleanup tasks before the garbage collection mechanism is invoked. This ensures better memory management and helps release system resources properly.

4. Differentiate between new and override modifiers.

The new modifier is used to explicitly instruct the compiler to hide a base class method and use the new implementation defined in the derived class.

The override modifier, on the other hand, is used to extend or modify the abstract or virtual method defined in a base class. It allows a child class to provide a specific implementation of a method that was declared in the parent class.

5. How is an empty class created in python?

An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in Python). We can still create objects for this class outside the class.


class EmptyClassDemo:
    pass

obj = EmptyClassDemo()
obj.name = "Interviewbuzz"
print("Name created= ", obj.name)

Output:
Name created = Interviewbuzz

6. Is it possible to call parent class without its instance creation?

Yes, it is possible if the base class is instantiated by other child classes or if the base class defines a static method.

7. Are access specifiers used in python?

Python does not make use of access specifiers like private, public, or protected explicitly. Instead, it imitates their behavior by using underscores:

  • No underscore: Public variable (default).
  • Single underscore (_): Indicates protected members.
  • Double underscore (__): Indicates private members.
# to demonstrate access specifiers
class InterviewbuzzEmployee:
    # protected members
    _emp_name = None
    _age = None

    # private members
    __branch = None

    # constructor
    def __init__(self, emp_name, age, branch): 
        self._emp_name = emp_name
        self._age = age
        self.__branch = branch

    # public member
    def display(self):
        print(self._emp_name + " " + str(self._age) + " " + self.__branch)

8. How do you access parent members in the child class?

Following are the ways to access parent class members within a child class:

1. By using Parent class name

You can directly use the parent class name to access attributes:

class Parent(object):
    # Constructor
    def __init__(self, name):
        self.name = name    

class Child(Parent): 
    # Constructor
    def __init__(self, name, age):
        Parent.__init__(self, name)
        self.age = age

    def display(self):
        print(self.name, self.age)

# Driver Code
obj = Child("Interviewbuzz", 6)
obj.display()   # Output: Interviewbuzz 6

2. By using super()

The super() keyword can be used to call parent class methods inside a child class.

class Parent(object):
    # Constructor
    def __init__(self, name):
        self.name = name    

class Child(Parent):
    # Constructor
    def __init__(self, name, age):         
        # In Python 3.x, we can also use super().__init__(name)
        super(Child, self).__init__(name)
        self.age = age

    def display(self):
        print(self.name, self.age)

# Driver Code
obj = Child("Interviewbuzz", 6)
obj.display()   # Output: Interviewbuzz 6

9. How does inheritance work in python? Explain it with an example.

Inheritance gives a class the power to access all attributes and methods of another class. It promotes code reusability and avoids redundancy. - The class inheriting from another is called a child class (derived class). - The class from which members are inherited is the parent class (superclass).

Types of Inheritance in Python

1. Single Inheritance

Child class derives members of one parent class.

Single Inheritance
# Parent class
class ParentClass:
    def par_func(self):
        print("I am parent class function")

# Child class
class ChildClass(ParentClass):
    def child_func(self):
        print("I am child class function")

# Driver code
obj1 = ChildClass()
obj1.par_func()
obj1.child_func()

2. Multi-level Inheritance

A child class inherits from a parent, which is further inherited by another class (grandchild).

Multi-level Inheritance
# Parent class
class A:
   def __init__(self, a_name):
       self.a_name = a_name

# Intermediate class
class B(A):
   def __init__(self, b_name, a_name):
       self.b_name = b_name
       A.__init__(self, a_name)

# Child class
class C(B):
   def __init__(self, c_name, b_name, a_name):
       self.c_name = c_name
       B.__init__(self, b_name, a_name)
       
   def display_names(self):
       print("A name :", self.a_name)
       print("B name :", self.b_name)
       print("C name :", self.c_name)

# Driver code
obj1 = C('child', 'intermediate', 'parent')
print(obj1.a_name)
obj1.display_names()

3. Multiple Inheritance

A child class inherits from more than one parent class.

Multiple Inheritance
# Parent class1
class Parent1:
   def parent1_func(self):
       print("Hi I am first Parent")

# Parent class2
class Parent2:
   def parent2_func(self):
       print("Hi I am second Parent")

# Child class
class Child(Parent1, Parent2):
   def child_func(self):
       self.parent1_func()
       self.parent2_func()

# Driver code
obj1 = Child()
obj1.child_func()

4. Hierarchical Inheritance

A parent class is inherited by more than one child class.

Hierarchical Inheritance
# Base class
class A:
     def a_func(self):
         print("I am from the parent class.")

# 1st Derived class
class B(A):
     def b_func(self):
         print("I am from the first child.")

# 2nd Derived class
class C(A):
     def c_func(self):
         print("I am from the second child.")

# Driver code
obj1 = B()
obj2 = C()
obj1.a_func()
obj1.b_func()    # child 1 method
obj2.a_func()
obj2.c_func()    # child 2 method

10. How do you create a class in Python?

To create a class in Python, we use the class keyword as shown below:

class InterviewbuzzEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name

To instantiate or create an object from the class:

emp_1 = InterviewbuzzEmployee("Mr. Employee")

To access the attribute emp_name, we use the dot operator:

print(emp_1.emp_name)
# Prints Mr. Employee

To create methods inside the class, we include them under the class scope:

class InterviewbuzzEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name
       
   def introduce(self):
       print("Hello I am " + self.emp_name)

The self parameter refers to the current instance of the class and is required for accessing attributes and methods. It must be the first parameter in any method defined inside the class.

The method introduce() can be accessed as:

emp_1.introduce()

Complete Example

class InterviewbuzzEmployee:
   def __init__(self, emp_name):
       self.emp_name = emp_name
       
   def introduce(self):
       print("Hello I am " + self.emp_name)
       
# create an object of InterviewbuzzEmployee class
emp_1 = InterviewbuzzEmployee("Mr Employee")
print(emp_1.emp_name)    # print employee name
emp_1.introduce()        # introduce the employee

Python Pandas Interview Questions

1. Can you get items of series A that are not available in another series B?

This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below.

import pandas as pd
df1 = pd.Series([2, 4, 8, 10, 12])
df2 = pd.Series([8, 12, 10, 15, 16])
df1 = df1[~df1.isin(df2)]
print(df1)

"""
Output:
0    2
1    4
dtype: int64
"""

2. While importing data from different sources, can the pandas library recognize dates?

Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data from the sources. Consider an example where we read data from a CSV file, we may encounter different date-time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below:

import pandas as pd
from datetime import datetime

dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S')

df = pd.read_csv(
    "some_file.csv",
    parse_dates=['datetime_column'],
    date_parser=dateparser
)

3. How will you get the items that are not common to both the given series A and B?

We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection.

Union and Intersection of Series

The following code demonstrates this:

import pandas as pd
import numpy as np

df1 = pd.Series([2, 4, 5, 8, 10])
df2 = pd.Series([8, 10, 13, 15, 17])

p_union = pd.Series(np.union1d(df1, df2))   # union of series
p_intersect = pd.Series(np.intersect1d(df1, df2))   # intersection of series

unique_elements = p_union[~p_union.isin(p_intersect)]
print(unique_elements)

"""
Output:
0     2
1     4
2     5
5    13
6    15
7    17
dtype: int64
"""

4. How will you delete indices, rows and columns from a dataframe?

  • Execute del df.index.name for removing the index by name.
  • Alternatively, the df.index.name can be assigned to None.
  • For example, if you have the below dataframe:
                Column 1
   Names             
   John               1
   Jack               2
   Judy               3
   Jim                4
  • To drop the index name “Names”:
df.index.name = None
# Or run the below:
# del df.index.name
print(df)

        Column 1
John          1
Jack          2
Judy          3
Jim           4

To Delete Row/Column from DataFrame

  • drop() method is used to delete row/column from dataframe.
  • The axis argument is passed to the drop method where if the value is 0, it indicates to drop a row and if 1 it has to drop the column.
  • Additionally, we can try to delete the rows/columns in place by setting the value of inplace=True. This makes sure that the job is done without the need for reassignment.
  • The duplicate values from the row/column can be deleted by using the drop_duplicates() method.
Delete row/column from DataFrame

5. How to add new column to pandas dataframe?

A new column can be added to a pandas dataframe as follows:

import pandas as pd      

data_info = {
    'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),    
    'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
}    
  
df = pd.DataFrame(data_info)    

# To add new column 'third'
df['third'] = pd.Series([10, 20, 30], index=['a', 'b', 'c'])    
print(df)    

# To add new column 'fourth'
df['fourth'] = df['first'] + df['third']    
print(df)

6. What do you understand by reindexing in pandas?

Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN /NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe.

7. How will you identify and deal with missing values in a dataframe?

We can identify if a dataframe has missing values by using the isnull() and isna() methods.

missing_data_count = df.isnull().sum()

We can handle missing values by either replacing the values in the column with 0 as follows:

df['column_name'].fillna(0)

Or by replacing it with the mean value of the column:

df['column_name'] = df['column_name'].fillna(df['column_name'].mean())

8. Can you create a series from the dictionary object in pandas?

One dimensional array capable of storing different data types is called a Series. We can create pandas series from a dictionary object as shown below:

import pandas as pd    

dict_info = {'key1': 2.0, 'key2': 3.1, 'key3': 2.2}  
series_obj = pd.Series(dict_info)    
print(series_obj)    

Output:
key1    2.0
key2    3.1
key3    2.2
dtype: float64

If an index is not specified in the input method, then the keys of the dictionary are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary.

9. How will you combine different pandas dataframes?

The dataframes can be combined using the following approaches:

append() method

This is used to stack the dataframes horizontally.

df1.append(df2)

concat() method

This is used to stack dataframes vertically. Best used when the dataframes have the same columns and similar fields.

pd.concat([df1, df2])

join() method

This is used for extracting data from various dataframes having one or more common columns.

df1.join(df2)

10. Define pandas dataframe.

A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns.

Syntax for creating a DataFrame:

import pandas as pd
dataframe = pd.DataFrame(data, index, columns, dtype)

Parameters:

  • data - Represents various forms like series, map, ndarray, lists, dict etc.
  • index - Optional argument that represents an index to row labels.
  • columns - Optional argument for column labels.
  • dtype - The data type of each column (optional).

11. What do you know about pandas?

  • Pandas is an open-source, Python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. It was developed in 2008 by Wes McKinney for data analysis.
  • Pandas are useful in performing 5 major steps of data analysis: load the data, clean/manipulate it, prepare it, model it, and analyze the data.

Numpy Interview Questions

1. How will you reverse the numpy array using one line of code?

  • Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis.
  • Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.

2. How will you find the nearest value in a given numpy array?

We can use the argmin() method of NumPy as shown below:

import numpy as np

def find_nearest_value(arr, value):
    arr = np.asarray(arr)
    idx = (np.abs(arr - value)).argmin()
    return arr[idx]

# Driver code
arr = np.array([0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742])
value = 0.52
print(find_nearest_value(arr, value))  # Prints 0.5645

3. How will you sort the array based on the Nth column?

For example, consider an array arr.

arr = np.array([[8, 3, 2],
          [3, 6, 5],
          [6, 1, 4]])

Let us try to sort the rows by the 2nd column so that we get:

[[6, 1, 4],
 [8, 3, 2],
 [3, 6, 5]]

We can do this by using the sort() method in NumPy as:

import numpy as np
arr = np.array([[8, 3, 2],
          [3, 6, 5],
          [6, 1, 4]])

# sort the array using np.sort
arr = np.sort(arr.view('i8,i8,i8'),
       order=['f1'],
       axis=0).view(np.int)

We can also perform sorting and that too in-place sorting by doing:

arr.view('i8,i8,i8').sort(order=['f1'], axis=0)

4. How will you read CSV data into an array in NumPy?

This can be achieved by using the genfromtxt() method by setting the delimiter as a comma.

from numpy import genfromtxt

csv_data = genfromtxt('sample_file.csv', delimiter=',')

5. How will you efficiently load data from a text file?

We can use the method numpy.loadtxt() which can automatically read the file’s header and footer lines and the comments if any.

This method is highly efficient and even if it feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used.

Supported File Formats:

  • Text files: Generally very slow, huge but portable, and human-readable.
  • Raw binary: No metadata, not portable, but very fast.
  • Pickle: Borderline slow, portable, depends on NumPy versions.
  • HDF5: Known as the High-Powered Kitchen Sink format; supports PyTables and h5py.
  • .npy: NumPy's native binary data format, extremely simple, efficient, and portable.

6. You are given a numpy array and a new column as inputs. How will you delete the second column and replace the column with a new column value?

Example:
Given array:

[[35 53 63]
 [72 12 22]
 [43 84 56]]

New Column values:

[
   20
   30
   40
]

Solution:

import numpy as np

# inputs
inputArray = np.array([[35, 53, 63],
                       [72, 12, 22],
                       [43, 84, 56]])
new_col = np.array([[20, 30, 40]])

# delete 2nd column
arr = np.delete(inputArray, 1, axis=1)

# insert new_col to array
arr = np.insert(arr, 1, new_col, axis=1)

print(arr)

7. What are the steps to create 1D, 2D and 3D arrays?

1D array creation:

import numpy as np
one_dimensional_list = [1, 2, 4]
one_dimensional_arr = np.array(one_dimensional_list)
print("1D array is :", one_dimensional_arr)

2D array creation:

import numpy as np
two_dimensional_list = [[1, 2, 3], [4, 5, 6]]
two_dimensional_arr = np.array(two_dimensional_list)
print("2D array is :", two_dimensional_arr)

3D array creation:

import numpy as np
three_dimensional_list = [[[1, 2, 3],
                           [4, 5, 6],
                           [7, 8, 9]]]
three_dimensional_arr = np.array(three_dimensional_list)
print("3D array is :", three_dimensional_arr)

ND array creation (using ndmin):

This can be achieved by giving the ndmin attribute. The below example demonstrates the creation of a 6D array:

import numpy as np
ndArray = np.array([1, 2, 3, 4], ndmin=6)
print(ndArray)
print('Dimensions of array:', ndArray.ndim)

8. How are NumPy arrays advantageous over python lists?

  • The list data structure of Python is highly efficient and capable of performing various functions. But it has severe limitations when it comes to the computation of vectorized operations (element-wise multiplication and addition).
    Python lists also require type information for every element, which results in overhead since type dispatching code executes every time an operation is performed.
    This is where NumPy arrays come into the picture, removing these limitations.
  • As the size of the NumPy arrays increases, NumPy becomes around 30x faster than Python Lists.
    This is because NumPy arrays are densely packed in memory due to their homogeneous nature, which also ensures faster memory cleanup.

9. What do you understand by NumPy?

NumPy is one of the most popular, easy-to-use, versatile, open-source, Python-based, general-purpose packages used for processing arrays. NumPy stands for NUMerical PYthon.

It is highly famous for its optimized tools that result in high performance and powerful N-Dimensional array processing features, explicitly designed to work on complex arrays.

Due to its popularity, powerful performance, and flexibility to perform various operations like trigonometric, algebraic, and statistical computations, it is widely used in scientific computations and broadcasting functions.

Applications of NumPy

Applications of NumPy

10. How will you find the shape of any given NumPy array?

We can use the shape attribute of the NumPy array to find the shape. It returns the row count and column count of the array.

import numpy as np

arr_two_dim = np.array([("x1","x2", "x3","x4"),
             ("x5","x6", "x7","x8" )])

arr_one_dim = np.array([3,2,4,5,6])

# find and print shape
print("2-D Array Shape: ", arr_two_dim.shape)
print("1-D Array Shape: ", arr_one_dim.shape)

"""
Output:
2-D Array Shape:  (2, 4)
1-D Array Shape:  (5,)
"""

✅ Output

2-D Array Shape: (2, 4)
1-D Array Shape: (5,)

Python Libraries Interview Questions

1. Differentiate between deep and shallow copies.

  • Shallow copy creates new objects storing references of original elements. It does not recursively copy nested objects—only references to them.
  • Deep copy creates an independent and completely new copy of an object, including all nested objects (recursively).

2. What is main function in python? How do you invoke it?

In the world of programming languages, main is considered as an entry point of execution for a program. But in Python, the interpreter serially interprets the file line-by-line. This means Python does not provide a main() function explicitly.

However, we can simulate this behavior by defining a user-defined main() function and using the __name__ property of a Python file. The __name__ variable is a special built-in variable that points to the name of the current module.

def main():
    print("Hi Interviewbuzz!")

if __name__ == "__main__":
    main()

3. Are there any tools for identifying bugs and performing static analysis in python?

Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively.

  • PyChecker helps find bugs in Python source code files and raises alerts for code issues and their complexity.
  • Pylint checks for a module’s coding standards and supports different plugins to enable custom features to meet this requirement.

4. Define PIP.

PIP stands for Python Installer Package. As the name indicates, it is used for installing different python modules. It is a command-line tool providing a seamless interface for installing different python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is:

pip install <package_name>

5. Define PYTHONPATH.

It is an environment variable used for incorporating additional directories during the import of a module or a package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded.

6. Define GIL.

GIL stands for Global Interpreter Lock. This is a mutex used for limiting access to python objects and aids in effective thread synchronization by avoiding deadlocks. GIL helps in achieving multitasking (and not parallel computing). The following diagram represents how GIL works.

Global Interpreter Lock

Based on the above diagram, there are three threads. First Thread acquires the GIL first and starts the I/O execution. When the I/O operations are done, thread 1 releases the acquired GIL which is then taken up by the second thread. The process repeats and the GIL are used by different threads alternatively until the threads have completed their execution. The threads not having the GIL lock goes into the waiting state and resumes execution only when it acquires the lock.

7. What are the differences between pickling and unpickling?

Pickling is the conversion of python objects to binary form. Whereas, unpickling is the conversion of binary form data to python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as python objects upon which processing can be done in python.

Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump python objects into disks. Unpickling uses the pickle.load() method to get back the data as python objects.

Differences between pickling and unpickling

8. Can you easily check if all characters in the given string is alphanumeric?

This can be easily done by making use of the isalnum() method that returns true in case the string has only alphanumeric characters.

For Example -

"abdc1321".isalnum() #Output: True
"xyz@123$".isalnum() #Output: False

Another way is to use match() method from the re (regex) module as shown:

import re
print(bool( re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True
print(bool( re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False

9. How can you generate random numbers?

Python provides a module called random using which we can generate random numbers.

  • We have to import a random module and call the random() method as shown below:
    • The random() method generates float values lying between 0 and 1 randomly.
 import random
 print(random.random())
  • To generate customised random numbers between specified ranges, we can use the randrange() method
    Syntax: randrange(beginning, end, step)
    For example:
import random
print(random.randrange(5,100,2))

10. What are lambda functions?

Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as:

mul_func = lambda x,y : x*y
print(mul_func(6, 4))
# Output: 24

11. What are some of the most commonly used built-in modules in Python?

Python modules are the files having python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are:

  • os
  • math
  • sys
  • random
  • re
  • datetime
  • JSON

12. Differentiate between a package and a module in python.

The module is a single python file. A module can import other modules (other python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside.

A python module is created by saving a file with the extension of .py. This file will have classes and functions that are reusable in the code as well as across modules.

A python package is created by following the below steps:

  • Create a directory and give a valid name that represents its operation.
  • Place modules of one kind in this directory.
  • Create __init__.py file in this directory. This lets python know the directory we created is a package. The contents of this package can be imported across different modules in other packages to reuse the functionality.

Python Programming Examples

1. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive?

We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source.

from io import StringIO
import pandas
csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())

Conclusion:

In this article, we have seen commonly asked interview questions for a python developer. These questions along with regular problem practice sessions will help you crack any python based interviews. Over the years, python has gained a lot of popularity amongst the developer’s community due to its simplicity and ability to support powerful computations. Due to this, the demand for good python developers is ever-growing. Nevertheless, to mention, the perks of being a python developer are really good. Along with theoretical knowledge in python, there is an emphasis on the ability to write good-quality code as well. So, keep learning and keep practising problems and without a doubt, you can crack any interviews.

Looking to get certified in Python? Check out Scaler Topic's Free Python course with certification. 

Important Resources:

2. Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionary

We can use the Counter method from the collections module

from collections import Counter
d1 = 'key1': 50, 'key2': 100, 'key3':200}
d2 = 'key1': 200, 'key2': 100, 'key4':300}
new_dict = Counter(d1) + Counter(d2)
print(new_dict)

3. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format.

We can again use the re module to convert the date string as shown below:

import re
def transform_date_format(date):
   return re.sub(r'(\d + "4" + )-(\d2)-(\d2)', '\\3-\\2-\\1', date)
date_input = "2021-08-01"
print( transform_date_format(date_input))

You can also use the datetime module as shown below:

from datetime import datetime
new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y")
print(new_date)

4. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s.

We can use the re module of python to perform regex pattern comparison here.

import re
def match_text(txt_data):
       pattern = 'ab8'
       if re.search(pattern, txt_data): #search for pattern in txt_data
           return 'Match found'
       else:
           return('Match not found')
print( match_text("abc"))   #prints Match not found
print( match_text("aabbbbbc")) #prints Match found

5. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants:

ax + by = c
mx + ny = o

By solving the equation, we get:

a, b, c, m, n, o = 5, 9, 4, 7, 9, 4
temp = a*n - b*m
if n != 0:
   x = (c*n - b*o) / temp
   y = (a*o - m*c) / temp
   print(str(x), str(y))

6. Write a Program to add two integers >0 without using the plus operator.

We can use bitwise operators to achieve this.

def add_nums(num1, num2):
   while num2 != 0:
       data = num1 & num2
       num1 = num1 ^ num2
       num2 = data << 1
   return num1
print(add_nums(2, 10))

7. Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N.

This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair.

def print_pairs(arr, N):
   # hash set
   hash_set = set()

   for i in range(0, len(arr)):
       val = N-arr[i]
       if (val in hash_set): #check if N-x is there in set, print the pair
           print("Pairs " + str(arr[i]) + ", " + str(val) )
       hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 3
print_pairs(arr, N)

8. Write a program for counting the number of every character of a given text file.

The idea is to use collections and pprint module as shown below:

import collections
import pprint
with open("sample_file.txt", 'r') as data:
   count_data = collections.Counter(data.read().upper())
   count_value = pprint.pformat(count_data)
print(count_value)

9. WAP (Write a program) which takes a sequence of numbers and check if all numbers are unique.

You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True.

def check_distinct(data_list):
   if len(data_list) == len(set(data_list)):
       return True
   else:
       return False
print( check_distinct([1, 6, 5, 8])) #Prints True
print( check_distinct([2, 2, 5, 5, 7, 8])) #Prints False

10. Write python function which takes a variable number of arguments.

A function that takes variable arguments is called a function prototype. Syntax:

def function_name(*arg_list)

For example:

def func(*var):
   for i in var:
       print(i)
func(1)
func(20, 1, 6)

The * in the function argument represents variable arguments in the function.

Node js MCQ

1. What is the output of the below code?

main_dict={}

def insert_item(item):
    if item in main_dict:
        main_dict[item] += 1
    else:
        main_dict[item] = 1

# Driver code
insert_item('Key1')
insert_item('Key2')
insert_item('Key2')
insert_item('Key3')
insert_item('Key1')

print(len(main_dict))

2. Which among the below options picks out negative numbers from the given list.

3. What is the output of the below program?

class Human(object):
   def __init__(self, name):
       self.human_name = name

   def getHumanName(self):
       return self.human_name

   def isEmployee(self):
       return False

class IBEmployee(Human):
   def __init__(self, name, emp_id):
       super(IBEmployee, self).__init__(name)
       self.emp_id = emp_id

   def isEmployee(self):
       return True

   def get_emp_id(self):
       return self.emp_id

# Driver code
employee = IBEmployee("Mr Employee", "IB007")
print( employee.getHumanName(), employee.isEmployee(), employee.get_emp_id())

4. time.time() in Python returns?

5. Which among the below options will correct the below error obtained while reading “sample_file.csv” in pandas?

Traceback (most recent call last): File <input>, line 10, in<module> UnicodeEncodeError:
'ascii' codec can't encode character.

6. Which of the following is untrue for Python namespaces?

7. Let func = lambda a, b : (a ** b), what is the output of func(float(10),20) ?

8. Which among the following options helps us to check whether a pandas dataframe is empty?

9. What is the output of the below code?

class X:
    def __init__(self):
        self.__num1 = 5
        self.num2 = 2

    def display_values(self):
        print(self.__num1, self.num2)
class Y(X):
    def __init__(self):
        super().__init__()
        self.__num1 = 1
        self.num2 = 6
obj = Y()
obj.display_values()

10. What is the difference between lists and tuples?

11. Which statement is false for __init__?

12. Let list1 = ['s', 'r', 'a', 's'] and list2 = ['a', 'a', 'n', 'h'], what is the output of ["".join([i, j]) for i, j in zip(list1, list2)]

13. Which of the following is the function responsible for pickling?

14. How will you find the location of numbers which are multiples of 5 in a series?

import pandas as pd
import numpy as np
series_data = pd.Series(np.random.randint(1, 20, 7))
#insert code here

15. Which of the following is a protected attribute?

16. What is the output of the below code?

class Person:
   def __init__(self, first_name, last_name):
       self.first_name = first_name
       self.last_name = last_name

first_name = "XYZ"
person = Person(first_name, "ABC")
first_name = "LMN"
person.last_name = "PQR"
print(person.first_name, person.last_name)

17. What is the output of the following statement "Hello World"[::-1]?

18. What is the output of the following program?

class A(object):
    def __init__(self, a):
        self.num = a

    def mul_two(self):
        self.num *= 2

class B(A):
    def __init__(self, a):
        A.__init__(self, a)   # parent class call

    def mul_three(self):
        self.num *= 3

obj = B(4)
print(obj.num)

obj.mul_two()
print(obj.num)

obj.mul_three()
print(obj.num)

19. Suppose list1 = [3,4,5,2,1,0], what is list1 after list1.pop(1)?