Easy way to IT Job

Python Interview Questions and Answers
Share on your Social Media

Python Interview Questions and Answers

Published On: April 16, 2019

Softlogic supports the students by offering Python Interview Questions and Answers which will lead to confidence in the students. Python is one of the Popular Programming language, since several job openings are found for this technology. We have written the answers in a lucid manner and we hope that you understand them.

1. What is Python? What is the Significance of Python?

Python is a programming language with objects, threads, modules, exceptions, and automatic memory management. The advantages of Python are: simplicity, portability, extensibility, built-in data structure and open source nature.

2. What is PEP8?

PEP8 is the latest Python coding standard. It is a set of coding recommendations. It helps in producing more readable Python code.

3. What Are The Built-In Types Available In Python?

We list below the list of most frequently used built-in types that Python supports:

Immutable built-in datatypes of Python

  • Numbers
  • Tuples
  • Strings

Mutable built-in datatypes of Python

  • List
  • Sets
  • Dictionaries

4. What are the Major Differences Between Lambda and Def?

  • Def has the ability to hold several expressions while lambda is a uni-expression function
  • Def generates a function and gives a name to it to call it at later time. Lambda develops a function object and returns it.
  • While def can have a return statement Lambda can’t have these statements.

5. What Are The Optional Statements Possible Inside A Try-Except Block In Python?

You can use two optional clauses in the try-except block:

  • The “else” clause – It is helpful if you want to run a piece of code when the try block doesn’t form an exception
  • The “finally” clause – It is helpful when you wish to execute some steps which run, irrespective of whether an exception takes place or not.

6. What Is Docstring In Python?

  • A docstring is a text that is the first statement in the following Python constructs: Module, class, function, or method definition
  • A docstring gets included in the __doc__ of the string object.

7. What is the Dictionary?

  • Dictionary objects can be formed by applying curly braces or by calling dictionary function.
  • Dictionary objects can be mutable
  • Dictionary represents primary value base
  • Each key primary value pair of Dictionary is regarded as an item
  • Dictionary keys should be immutable
  • Dictionary values can be either mutable or immutable
  • Duplicate keys are not considered but values can be duplicate
  • There is no preservation of insertion order
  • Heterogeneous values and keys are allowed

8. Is It Compulsory For A Python Function To Return A Value?

It is not mandatory for a function to return any value, But if required, we can make use of None as a return value.

9. What is the significance of *Args in Python?

We use *Args in the role of a parameter in the function header. It lets one to pass N number of arguments. Keep in mind that this type of argument syntax doesn’t let passing a named argument to the function. Instances of using the *args:

# Python code to demonstrate# *args for dynamic arguments

def fn(*argList):

for argx in argList:

print (argx)

fn(‘I’, ‘am’, ‘working’, ‘sincererly’)

The output:




10. Does Python consist of A Main() Method?

  • The main() is the beginning point function which is called first in several programming languages. Python sequentially executes the lines of the code one-by-one because it is interpreter-based.
  • Python has a Main() method. However, it gets executed whenever we run Python in any of the two ways:
  1. By directly clicking it or
  2. Begin it from the command line
  • We can also override the Python default main() function applying the Python if statement. Use the following code:


print(“__name__ contains: “, __name__)

def main():

print(“Checking the main function”)

if __name__ == ‘__main__’:


The output:


__name__ contains:  __main__

Checking the main function

11. How Python is interpreted?

Python is an interpreted language, Python program runs straight from the source code. It changes the source code that is written by the programmer into an intermediate language. This is later translated into machine language that has to be executed.

12. Explain about memory management in Python

  1. Python memory is taken care by Python private heap space. All Python objects and data structures are situated in a private heap. The programmer cannot reach this private heap. The interpreter handles this Python private heap.
  2. The memory manager allocates Python heap space for Python objects. The primary API provides access to few tools for the programmers to code.
  3. Python also consists of an inbuilt garbage collector which recycles all the unused memory and later frees the memory for making it present to the heap space.

13. What are Python Decorators?

A Python decorator is a particular modification that we perform in Python syntax to change functions easily.

14. State the difference between list and tuple.

The difference between list and tuple is : List is mutable while tuple is not mutable. Tuple has the ability to be hashed as a key for dictionaries.

15. What is slicing in Python?

Slicing is the process to choose a range of items from sequence types including list, strings, tuples, etc.

16. What is module and package in Python?

Module is the means to structure program in Python. Each Python program file is regarded as a module which imports other modules including attributes and objects.

A package of modules comprises the folder of Python program. A package can consist of modules or sub folders.

17. List the rules for local and global variables in Python.

Local variables: Suppose a variable is assigned a new value in any place within the function’s body, it’s assumed to be local.

Global variables: Those variables are implicitly global that are only referenced inside a function.

18. How to make a Python script executable on Unix?

  • You have to perform two things to make a Python script executable on Unix:
  • Script file’s mode should be executable
  • The initial line must start with # ( #!/usr/local/bin/python)

19. How can you generate random numbers in Python?

For generating random numbers in Python, you should import command as

  1. import random
  2. random.random()

This action returns a random floating point number in the range  [0,1]

20. Explain the difference between Django, Pyramid and Flask.

  1. Flask is a micro framework majorly formed for a small application with no complicated requirements. In Flask, you have to make use of external libraries. Flask is ready for usage.
  2. .Pyramid is developed for the purpose of big applications. It offers flexibility and allows the developer to apply the appropriate tools for their project. The developer can select the database, UTL structure, template style etc. Pyramid has the nature of being heavy configurable.
  3. Similar to Pyramid, Django is also applied for big applications. It consists of an ORM,

21. How is Multithreading achieved in Python?

  • Python consists of a multi-threading package but if you wish to multi-thread to increase the speed of your code, then it’s generally not a good idea to use it.
  • Python consists of a construct named the Global Interpreter Lock (GIL). It ascertains that only one of your threads can execute at any one point of time. A thread gets the GIL, performs some work, then passes the GIL to the next thread.
  • This takes place in a swift manner. All these GUI passing produces overhead to execution; This implies that if you wish to make your code run quickly then using the threading package is not a wise option.

22. Explain Inheritance in Python

Inheritance lets one class to gain all the members of another class. It offers code reusability. This makes it easier to form and maintain an application. The class from which we are inheriting is known as super-class and the class that is inherited is known as a derived/child class.

The various types of inheritance supported by Python are:

  • Single inheritance: here a derived class gets the members of a single super class
  • Multi-level inheritance: a derived class d1 is inherited from base class base1, and d2 is inherited from base2.
  • Hierarchical inheritance: You can inherit any number of child classes from one base class
  • Multiple inheritance: From more than one base class a derived class is inherited

23. What is the significance of help() and dir() function in Python?

  1. You can get help() and dir() functions from the Python interpreter, it is used for seeing a consolidated dump of built-in functions.
  2. The help() function is used to show the documentation string and also lets you to view the assistance related to modules, attributes, keywords, etc.
  3. The dir() function is used to show the defined symbols.

24. Why isn’t all the memory de-allocated whenever Python exits?

  1. At the time of exiting of Python, especially those Python modules that consist of circular references to other objects or the objects that are referenced from the global namespaces are not generally de-allocated or freed.
  2. It is not possible to de-allocate those portions of memory that are reserved by the C library.
  3. Due to consisting of its own competent clean up mechanism, Python would attempt to deallocate/destroy every other object on exit.

25. Explain the process of compilation and linking in Python?

The compiling and linking lets the new extensions to be compiled properly without any problem, and the linking can be performed only when it passes the compiled procedure. Suppose the dynamic loading is used then it relies on the style that is being offered with the system. The Python interpreter can be used to offer the dynamic loading of configuration setup files. It will then rebuilt the interpreter.

26. Explain the difference between range and xrange

Xrange and range are similar with regard to functionality, for the most parts. They both offer a way to generate a list of integers for you to make use of in whatever way you want. The only difference lies in the fact that range returns a Python list object and x range returns an xrange object.This implies that xrange doesn’t produce a static list during run-time as range does.

It forms the values whenever you require them through a special technique called yielding. This technique is applied with a type of object called as generators. This implies that if you have a really big range that you would wish to generate a list then xrange should be the function of choice.

27. What are the supported data types in Python?

Python consists of five standard data types:-

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

28. What are negative indexed and what is their significance?

  • The sequences in Python are indexed and have positive and negative numbers. The positive numbers use 0. This is applied as the first index and 1 is the second index. The process continues like this.
  • The negative number index begins form -1 that represents the last index in the sequence. -2 is the penultimate index and the sequence continues like the positive number.

29. Explain Python module.

Being a Python script a module commonly consists of import statements, functions, classes and variable definitions. It also consists of Python runnable code.

30. How many types of sequences are supported by Python? List them.

Seven sequence types are supported by Python. They are str, list, tuple, byte array, Unicode, xrange, and buffer. Xrange is deprecated in Python 3.5X.

31. How to show the contents of text file in reverse order?

  • Convert the specific file into a list
  • Revese the list by applying reversed()

32. Is Python object-oriented? Explain Object-oriented programming.

  • Python is Object Oriented Programming language. OOP is the programming paradigm dependent on classes and instances of those classes known as objects. The features of OOP are:
  • Encapsulation, , Inheritance, Data Abstraction, Polymorphism.

33. Does Python support interfaces similar to Java? Elaborate.

Python does not offer interfaces as in Java. Abstract Base Class and its features are offered by the Python’s abc module. Abstract Base Class is a procedure intended to specify what methods must be executed by the implementation sub classes. The usage of ABC’s offers a sort of comprehension about methods and their expected behavior, This module was provided from Python 2.7 version on wards.

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

Both append() and extend() methods come under the methods of list. These methods are used again to include the elements at the end of the list.

  • append(element) – adds the specific element at the end of the list which has called this method
  • extend(another-list) – adds the specific elements of another list at the end of the list which is termed as the extend method.

35. What is database connection in Python Flask?

Flask supports database triggered application (RDBS). Such system needs forming a schema, which needs piping the schema sql file into a sqlite3 command. Hence you should install sqlite3 command so as to form or trigger the database in Flask.

Flask lets you to request database in three methods:

  • before_request(): They are called before a specific request and pass no arguments
  • after_request(): They are called after a specific request and pass the response that will be sent to the client
  • teardown_request(): They are called at times when exception is raised, and responses are not for surety. They are called after the response has been created. They are not allowed to change the request, and their values are ignored.

36. Explain retrieving data from a table in MySQL database through Python code.

  • import MySQLdb module as : import MySQLdb
  • establish a connection to the database.
  • db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”)
  • Initiate the cursor variable when there is established connection: c1 = db.cursor()
  • Retrieve the information after defining a required query string. s = “Select * from dept”
  • fetch the data with the help of fetch() methods and print it. data = c1.fetch(s)
  • close the database connection. db.close()

37. Which package is the quickest form of Python?

  • PyPy offers maximum compatibility while using CPython implementation for enhancing its performance.
  • The tests ascertained that PyPy is over five times quicker than the CPython. At present, it supports Python 2.7.

38. Explain the thread safety of Python.

Python makes sure that there is safe access to threads. It utilizes the GIL mutex to set synchronization. Suppose a thread loses the GIL lock at any point of time, then you have to make the code thread-safe.  For instance, several Python operations execute as atomic including calling the sort() method on a list.

39. Explain about assigning values for the class attributes at runtime.

We can specify the values for the given attributes at runtime. We should add an init method and pass input to the specific object constructor.

40. Explain errors and exceptions in Python program.

Coding concerns in a program are errors which may make it to exit abnormally. On the other hand, exceptions take place because of an external event which interrupts the regular flow of the program.

41. What are Python iterators?

Iterators in Python are objects that are array-like, They let moving on the next element. We apply them in traversing a loop. Python library has several iterators.. For instance, a list is also considered an iterator and we can have a for loop over it.

42. Explain the difference between an iterator and iterable.

The collection type including a list, dictionary, tuple and set are iterable objects. They are also considered iterable containers that return an iterator at the time of traversing.

43. Explain the usage of try, except, raise, and finally:

Try, except and finally blocks are applied in Python error handling. Code is executed in the try block till an error takes place. You can make use of a generic except block which will get control after all errors, or one can make use of a particular exception handling block for several error types. Control is transferred to the specific except block, The finally block is executed in every case. Raise may be made use of to raise your own exceptions.

44. What takes place when a function doesn’t consist of a return statement? Is this valid?

This is valid. The function will later return a None object. The end of a function is not defined by an explicit keyword but by the block of code that is executed.

45. State the difference between local and global namespaces.

Local namespaces are formed within a function and when the function is called. Global name spaces are formed when the program begins.

46. When do you use a while statement rather than a for statement?

The while statement is used in cases of simple repetitive looping. The for statement is used when you want to iterate through a list of items including database records, characters in a string etc.

47. When don’t signal handlers function?

The most frequently occurring issue is that signal handler is declared with the wrong argument list. It is called as: handler (signum, frame) . Hence it should be declared with a couple of arguments: def handler (signum, frame).

48. What to do when no thread is running? How should you make it function?

All threads are killed once the main thread exits. Your main thread is running fast, offering the thread no time to perform any action. A good fix is to add a sleep to the end of the program that’s long enough for all the threads to complete.

49. What is file handling?

  • File is a named location available on the disk which stores the data permanently. Python language offers several functions and methods to facilitate the communication between Python programs and files.
  • Python programs have the ability to open the file, perform the read or write operations on the file and later close the file.
  • We can open the files by calling open function belonging to the built-in modules
  • During opening the file, we have to specify the specific mode of the file
  • Mode of the file tells for what reason the file is going to be opened

50. What is garbage collection?

The concept of eliminating unused or unreferenced objects from the memory location is called as a garbage collection.

At the time of executing the program, if garbage collection occurs then more memory space is available for the program. The remaining program execution turns out quicker.

51. What is scheduling?

Schedule is an in-process scheduler for periodic activities that applies the builder pattern for configuration. Schedule allows you run Python functions periodically and also at pre-determined intervals through an easy and human-friendly syntax.

52. How ternary operators can be used in Python?

Ternary operators are used in python to display the conditional statements and it contains true or false values with a statement that has to be evaluated for it.


[on_true] if [expression] else [on_false] a,b = 25, 50 big = a if a < b else b.

53. Explain about len() method in python

Len() is the method used to determine the length of a list, a string, and an array, and so on.


stg = ‘XYZ’

len (stg)

54. Explain monkey patching in python

The monkey patching in python refers to dynamic modifications of a module or a class at run-time.


# m.py

class SampleMP:

def f(self):

print “f()”

The monkey patching test can be done as follows:

import b

def monkey_f(self):

print “monkey_f()”

b.SampleMP.f = monkey_f

obj = m.SampleMP()




55. Explain multiple inheritance

Multiple Inheritances is one of the types of inheritance supported by Python, unlike Java which means a class can be derived from more than one parent or base class.

56. Define Polymorphism

Polymorphism is a behavior that takes multiple forms. If the method of a base class has some behavior, it can be derived from child class with another behavior.

57. What is encapsulation in Python?

Encapsulation is binding the code and data together and the Python class is one of the best examples of encapsulation.

58. What is the use of access specifiers in Python?

Python does not access an instance variable or function but depends on the concept of prefixing the variable, method, or function name using single or double underscore to access the behavior and attributes of protected and private access specifiers.

59. What is empty class and how to create it in Python?

The class with no codes or statement defined in its block is called an empty class and it can be created in a python programming language using the pass keyword. The pass command in python does nothing but it executes as a null statement.


class s

&amp; amp; nbsp; pass

obj = s()

obj.name = “abc”

print (“Name = “, obj.name)


Name = abc

60. How to create hash triangle in python programming?

def pyfunc(t):

for x in range(t):

print (‘ ‘*(t-x-1)+’#’*(2*x+1))









61. Explain pickling and unpickling in Python

Python has a module called pickle to accept any python object and transform it into a string representation and junk it into a file using the dump function and this process is called pickling. The retrieval of the original python object from the stored string representation is referred to as unpickling.

62. Explain about generators in python

Generators are the functions that return an iterable collection of items for python programming.

63. How to capitalize the first letter of a string in python programming?

Python has a built-in method called capitalize() to capitalize the first letter of a string. It returns the original string if the string has already capitalized.

64. How to convert all letters of a string to lowercase?

The lower() function of python programming is used to convert all the letters of a string to lowercase.


Stg = “XYZ”




65. How to add multiple lines of comment in python programming?

Multiple lines are added in python programming using the # symbol at the beginning of all lines. It can be done in the shortcut method by pressing the ctrl key and left-click in every place wherever the comment lines are required.

66. Define the usage of is, not, and in operators

Not, in, and is operators are special functions and it produces the following results in python programming

Is operator: It returns true value while 2 operands are true (example: “x” is ‘x’)

Not operator: It returns the inverse of a boolean value

In operator: It verifies the elements that are present in some sequence.

67. How can you add values to a python array?

We can add elements in array using functions like append(), extend(), and insert(I,x).


b = arr.array(‘d’ , [1.1 , 2.1 , 3.1])



b.extend([4.5, 6.3, 6.8])





array(‘d’, [1.1 , 2.1 , 3.1 , 3.4])

array (‘d’, [1.1 , 2.1 , 3.1 , 3.4, 4.5, 6.3, 6.8])

array (‘d’, [1.1 , 2.1 , 3.8 , 3.1 , 3.4, 4.5, 6.3, 6.8])

68. Differentiate deep copy and shallow copy

Deep copy is used to store the values that are copied already and it does not copy the reference pointers to the objects. It makes the execution of a python program slower because of making several copies for each called object. Shallow copy on the other hand used when a new instance gets generated and keeps the value in the new instance. It allows the execution faster and it depends on the size of the used data.

69. What is the usage of the split() method in python?

The split() is the method of Python programming used to separate a given string.


s = “Welcome Home”

print (s.split())


[‘Welcome’ , ‘Home’]

70. How to calculate percentile with Python?

Percentile can be calculated using NumPy library with the following code

import numpy as np

per = np.array([1,2,3,4,5])

cent = np.percentile(per, 50)

print (cent)



71. List some difference between NumPy and SciPy

NumPy contains array data type and some fundamental operations like sorting, indexing, reshaping, and elementwise functions, etc. NumPy consists of linear algebra functions.

SciPy contains all numerical codes and it has the goal of making compatibility. It has all features supported by its predecessors. It consists of the fully-featured versions of linear algebra modules.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.