Python

Python is a widely-used general-purpose, high-level programming language. If you are looking for a job as a python developer, then do check out the list of most frequently asked Interview questions in Python, these questions can help you to get a job in python.



Q.1 What are the advantages of Python over other languages?

Here are the advantages of Python over other languages.

  • Presence of Third Party Modules
  • Extensive Support Libraries
  • Open Source and Community Development
  • Learning Ease and Support Available
  • User-friendly Data Structures
  • Productivity and Speed
Q.2 Why pass statement is used in Python?
It is used to Jump out of the loop.
Q.3 How import modules are stored in Python?
Import modules are stored as Python code file.
Q.4 Which character is used to indicate end of a block?
End of a block is represented by colon (:)
Q.5

What is the value in 'x' from the following expression

x = 17 / 2 * 3 + 2
The value of x is 27.5
Q.6 Whati is Tuple in Python
A tuple is a sequence of immutable Python objects.
Q.7 Where docstring is placed in a module?
Docstring is placed in the Last line.
Q.8 What is Python and give some benefits of using Python?
Python is defined as a programming language with objects, modules, threads, exceptions and automatic memory management. It is very simple and easy, portable, extensible, has a build-in data structure and it is an open source.
Q.9 Define PEP 8.
PEP 8 is defined as a coding convention, that gives a set of recommendation, about how to write your Python code more readable.
Q.10 Define pickling and unpickling?
The process of picking involves pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function. Where on the other hand the process of retrieving original Python objects from the stored string representation is called unpickling.
Q.11 Given reason why Python is interpreted?
Python language is an interpreted language, such that the program runs directly from the source code. Python language converts the source code that is written by the programmer into an intermediate language, that is again translated into machine language which has to be executed.
Q.12 In Python, how is memory managed?

Steps in managing memory in Python are -

  • The Python memory is primarily managed by Python private heap space. 
  • All Python objects and data structures are located in a private heap. 
  • The programmer does not have access to this private heap and interpreter takes care of this Python private heap. 
  • The allocation of Python heap space for Python objects is done by Python memory manager. 
  • The core API gives access to some tools for the programmer to code. 
  • Python has an inbuilt garbage collector, that recycles all the unused memory and frees the memory and makes it available to the heap space.
Q.13 Specify the tools that helps in finding bugs or perform static analysis?
PyChecker is a static analysis tool that is used to detect the bugs in Python source code. PyChecker warns about the style and complexity of the bug. Also Pylint is another tool which verifies whether the module meets the coding standard.
Q.14 What do you understand by Python decorators?
Python decorator can be defined as a specific change that we make in Python syntax to alter functions easily.
Q.15 List the differences between list and tuple.
The point of difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for instance as a key for dictionaries.
Q.16 How will you pass arguments by value or by reference?
Since everything in Python is an object and all variables hold references to the objects. Therefore the references values are according to the functions; due to which you cannot change the value of the references. But we can change the objects if it is mutable.
Q.17 Define namespace in Python.
Since every name introduced has a place where it lives and can be hooked for, in Python. This is referred as namespace. Namespace is like a box where a variable name is mapped to the object placed. Therefore whenever the variable is searched out, this box will be searched, to get corresponding object.
Q.18 Give reason why lambda forms in python does not have statements?
Lambda form in python does not have statements because it is used to make new function object and then return them at runtime.
Q.19 What do you understand by unittest in Python?
unittest is a unit testing framework in Python. Unittest supports sharing of setups, automation testing, shutdown code for tests, aggregation of tests into collections and more.
Q.20 How do you define generators in Python?
Generators are the way of implementing iterators. It is just a normal function except that it yields expression in the function.
Q.21 How will you copy an object in Python?
In order to copy an object in Python, we should try copy.copy () or copy.deepcopy() for the general case. Since we cannot copy all objects but yes most of them.
Q.22 What do you understand negative index in Python
Python sequences are index in positive and negative numbers as well. Therefore for a positive index, 0 is the first index, 1 is the second index and so forth. On the other hand for negative index, (-1) is the last index and (-2) is the second last index and so forth.
Q.23 How will you convert a number to a string?
We must use the inbuilt function str() in order to convert a number into a string. In case you want a octal or hexadecimal representation, use the inbuilt function oct() or hex().
Q.24 Differentiate between Xrange and range?
The primary difference is that Xrange returns the xrange object while range returns the list, and uses the same memory and no matter what the range size is.
Q.25 What do you understand by module and package in Python?
Module is the way to structure program such that each Python program file is a module, which imports other modules like objects and attributes. On the other hand the folder of Python program is a package of modules. Such that a package can have modules or subfolders.
Q.26 State the process to share global variables across modules?
In order to share global variables across modules within a single program, you must first create a special module. Then Import the config module in all modules of your application. Thereafter the module will be available as a global variable across modules.
Q.27 What is Flask and list down its benefits?
Flask is defined as a web micro framework for Python that is based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jingja are two of its dependencies. Since flask is part of the micro-framework. therefore it will have little to no dependencies on external libraries. Also it makes the framework light while there is little dependency to update and less security bugs.
Q.28 Is python interpreted or compiled?
Python as a programming language has no saying about if it's a compiled or interpreted programming language, only the implementation of it. The terms interpreted or compiled is not a property of the language but a property of the implementation. Python program runs directly from the source code. so, Python will fall under byte code interpreted. The .py source code is first compiled to byte code as .pyc. This byte code can be interpreted (official CPython), or JIT compiled (PyPy). Python source code (.py) can be compiled to different byte code also like IronPython (.Net) or Jython (JVM).
Q.29 What is PEP?
PEP stands for Python Enhancement Proposal. A PEP is a design document providing information to the Python community, or describing a new feature for Python or its processes or environment.
Q.30 How is memory allocated for variables in python?

Due to Python's dynamic nature. The answer is one of:

  • the byte size of the name of a variable as a string, plus two bytes/pointers
  • one byte/pointer plus one byte/pointer for every unique attribute
  • the memory of your entire application >more than the current memory of your application
  • something else, depending on your definition of a variable
Q.31 What is the difference between python arrays and lists.
Arrays can hold only a single data type element whereas lists can hold any data type elements.
Q.32 What are negative indices used for?

The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number.

The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in the correct order.

Q.33 Why do we use numpy mainly?

We use python numpy array instead of a list because of the below three reasons:

  • Less Memory
  • Fast
  • Convenient
Q.34 What is dictionary in python?
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
Q.35 What are *args and **kwargs?
We use *args when we aren’t sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don’t know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.
Q.36 Does python support multi-threading? How do we achieve that?
Python does not support multithreading natively. However, there are libraries to add support of multithreading into python but it is generally not a good idea in Python.
Q.37 What is monkey patching and mention its most common use?

Monkey patching is changing the behavior of a function or object after it has already been defined.

Most of the time it's a pretty terrible idea - it is usually best if things act in a well-defined way. One reason to monkey patch would be in testing. The mock package is very useful to this end.

Q.38 What are the naming conventions of variables in python?
  • Only use lower case while naming a Package in Python.
  • Python loves the small case alphabets and hence suggests Module names should also follow the suite.
  • Classes in Python subject to a different naming scheme called as CapWords convention.
  • Global variables must all be in lowercase.
  • Every instance method should have ‘self’ as its first argument.
  • All class methods should have ‘cls’ as their first argument.
  • All constants must be CAPITALISED completely.
Q.39 How do we specify private and protected access specifiers?
We use double underscore as the beginning for a private variable name and single underscore for protected.
Q.40 How will you manage different versions of your code?
Everyone should be knowing and using version management service like git or github as it will help a lot when working in large projects with big teams.
Q.41 Explain python’s garbage collection mechanism.
  • Python maintains a count of the number of references to each object in memory. If a reference count goes to zero then the associated object is no longer live and the memory allocated to that object can be freed up for something else.
  • Occasionally things called "reference cycles" happen. The garbage collector periodically looks for these and cleans them up. An example would be if you have two objects o1 and o2 such that o1.x == o2 and o2.x == o1. If o1 and o2 are not referenced by anything else then they shouldn't be live. But each of them has a reference count of 1.
  • Certain heuristics are used to speed up garbage collection. For example, recently created objects are more likely to be dead. As objects are created, the garbage collector assigns them to generations. Each object gets one generation, and younger generations are dealt with first.
Q.42 Write a program to swap two numbers?
a, b = b, a
Q.43 What is slicing in python?
It is a single expression anonymous function often used as an inline function.
Q.44 How do you use slicing operation to reverse a string?
original_string[::-1]
Q.45 How do append() and extend() differ in a list?
Append is used to add elements. Extend is use to concatenate lists.
Q.46 How do we write a multiline string?

By using the escape character backslash.

Eg. String=”Hello I am a string\

         And I continue that string.”

Q.47 Find the number with maximum frequency in a list using single line of code.
max(lst,key=lst.count)
Q.48 How do you give arguments to a program via a terminal?
By importing system module and then using argv variable.
Q.49 What is the use of lambda function?
It is a single expression anonymous function often used as inline function.
Q.50 Mention a few main differences in python 2.0 and 3.0?
  • Division: 2.x returns integer, 3.x always gives float
  • Print: 3.x always requires parenthesis
  • Unicode: In Python 2, implicit str type is ASCII. But in Python 3.x implicit str type is Unicode
Q.51 Given two sequences, how do you make a dictionary?

dict (zip(t1,t2)

here t1 and t2 are the two sequences. Note: both sequences should be of same length.

Q.52 What are accessors, mutators, and @property?
What we call getters and setters in languages like Java, we term accessors and mutators in Python. In Java, if we have a user-defined class with a property ‘x’, we have methods like getX() and setX(). In Python, we have @property, which is syntactic sugar for property(). This lets us get and set variables without compromising on the conventions.
Q.53 How can you imitate switch-case behavior in python?
We use dictionary to approach to the solution of this problem. For ex.:
def switch_demo(argument):
    switcher = {
        1: "January",
        2: "February",
        3: "March",
        4: "April",
        5: "May",
        6: "June",
        7: "July",
        8: "August",
        9: "September",
        10: "October",
        11: "November",
        12: "December"
    }
    print switcher.get(argument, "Invalid month")

Q.54 Write a program in Python to produce Star triangle.

def pyfunc(r):

for x in range(r):

print(''*(r-x-1)+'*'*(2*x+1))


Q.55 Write an efficient one-liner that will count the number of capital letters in a file.

count sum(1 for line in fh for character in line if character.isupper())

Q.56 Compare Django and flask.
  • Flask provides simplicity, flexibility and fine-grained control. It is unopinionated (it lets you decide how you want to implement things).
  • Django provides an all-inclusive experience: you get an admin panel, database interfaces, an ORM, and directory structure for your apps and projects out of the box.
Q.57 What is map function in Python?

map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions.

Q.58

What is the difference between NumPy and SciPy?

  • In an ideal world, NumPy would contain nothing but the array data type and the most basic operations: indexing, sorting, reshaping, basic elementwise functions, et cetera.
  • All numerical code would reside in SciPy. However, one of NumPy’s important goals is compatibility, so NumPy tries to retain all features supported by either of its predecessors.
  • Thus, NumPy contains some linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy contains more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms.
  • If you are doing scientific computing with python, you should probably install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy.
Q.59 Write a program for binary search.

def BinarySearch(lys, val):  

    first = 0

    last = len(lys)-1

    index = -1

    while (first <= last) and (index == -1):

        mid = (first+last)//2

        if lys[mid] == val:

            index = mid

        else:

            if val<lys[mid]:

                last = mid -1

            else:

                first = mid +1

    return index

Q.60 Write a program for interpolation search.

def InterpolationSearch(lys, val):  

    low = 0

    high = (len(lys) - 1)

    while low <= high and val >= lys[low] and val <= lys[high]:

        index = low + int(((float(high - low) / ( lys[high] - lys[low])) * ( val - lys[low])))

        if lys[index] == val:

            return index

        if lys[index] < val:

            low = index + 1;

        else:

            high = index - 1;

    return -1


Q.61 What is JSON? Describe in brief how you’d convert JSON data into Python data?

JSON stands for JavaScript Object Notation.

JSON is generally built on the following two structures:

  • A collection of <name,value> pairs
  • An ordered list of values.

We use load() function from JSON module in python.


Q.62 Is python good for image processing?

It is highly dependant on what we mean by image processing here but a good starting point will be PIL library. It can be used to easily import images, do basic operations like rotation and resizing and saving images.

Q.63 Why is python so famous for ML?

This is because of a number of reason, the main points being:

  • It has most of the libraries used for ML
  • All the heavy backend is done in c or fortran hence speed issue does not come up
  • It also has gained a historical consistency in this sector
  • Python codes have  great readability and helps in concentrating more in logic than syntax
  • Python codes are in general much shorter which means lesser development time
Q.64 Compare Juia, R and Python.

Julia is the fastest language, so much so that a code which takes 5 seconds in Julia takes more than half an hour in python or R.

R is mainly for data scientist and not much anticipated for general purpose programming, hence for programmers, learning R is a bit of limiting.

Python has a balance between usability and speed. Its versatility makes it the first choice of programmers.

Q.65 What do you think about the future of python programming language?

According to all the current researches, the future ( at least the near future) is going to be Artificial Intelligence and Machine Learning. Python is a programming language getting popular day by day due to its reduced complexity and the freedom it provides to work in various sectors of programming.

And because of high usage of python in the above field, it is considered one of the best languages to design a project related to AI and Machine Learning (although there are other things too used for that). So, Python serves to be the best ingredient of the dessert.

Get Govt. Certified Take Test
 For Support