Python Interview Questions And Answers Pdf

1. What is Python good for?
Answer: Python is a high-level general-purpose programming language that can be applied to many different classes of problems.
The language comes with a large standard library that covers areas such as string processing like regular expressions, Unicode, calculating differences between files, Internet protocols like HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI programming, software engineering like unit testing, logging, profiling, parsing Python code, and operating system interfaces like system calls, file systems, TCP/IP sockets. ( tableau online training )

2. Name some of the features of Python?
Answer: Following are some of the salient features of python
It supports functional and structured programming methods as well as OOP.
It can be used as a scripting language or can be compiled to byte-code for building large applications.
It provides very high-level dynamic data types and supports dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

3. What Is Python? What Are The Benefits Of Using Python? What Do You Understand Of PEP 8?
Answer: Python is one of the most successful interpreted languages. When you write a Python script, it doesn’t need to get compiled before execution. Few other interpreted languages are PHP and Javascript.

Benefits Of Python Programming.

  • Python is a dynamic-typed language, this means that you don’t need to mention the date type of variables during their declaration. It allows to set variables like var1=101 and var2 =” You are an engineer.” without any error.
  • Python supports object-orientated programming as you can define classes along with the composition and inheritance. It doesn’t use access specifiers like public or private).
  • Functions in Python are like first-class objects. It suggests you can assign them to variables, return from other methods and pass as arguments.
  • Developing using Python is quick but running it is often slower than compiled languages. Luckily, Python enables to include the “C” language extensions so you can optimize your scripts.
  • Python has several usages like web-based applications, test automation, data modeling, big data analytics and much more. Alternatively, you can utilize it as a “glue” layer to work with other languages.
  • PEP 8.
  • PEP 8 is the latest Python coding standard, a set of coding recommendations. It guides to deliver more readable Python code.

4. What are the Runtime Errors?
Answer: The errors which occur after starting the execution of the programs are known as runtime errors.
Runtime errors can occur because of

1) Invalid Input
2) Invalid Logic
3) memory issues
4) Hardware failures and so on

  • With respect to every reason which causes to runtime error corresponding runtime error representation class is available
    Runtime error representation classes technically we call as an exception class.
  • While executing the program if any runtime error occurs corresponding runtime error representation class object is created
    Creating a runtime error representation class object is technically known as a rising exception
  • While executing the program if an exception is raised, then internally python interpreter verify any code is implemented to handle the raised exception or not
  • If code is not implemented to handle raised exception then the program will be terminated abnormally.

5. Mention what the Django templates consist of?
Answer: The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template.

6. Explain the use of session in Django framework?
Answer: Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client-side and storing all the related data on the server-side.

7. Is Python object-oriented? what is an object-oriented programming
Answer: Yes. Python is Object Oriented Programming language. OOP is the programming paradigm based on classes and instances of those classes called objects. The features of OOP are:
Encapsulation, Data Abstraction, Inheritance, Polymorphism.

8. Name few Python modules for Statistical, Numerical and scientific computations?
Answer: numPy – this module provides an array/matrix type, and it is useful for doing computations on arrays. scipy – this module provides methods for doing numeric integrals, solving differential equations, etc pylab – is a module for generating and saving plots
matplotlib – used for managing data and generating plots.

9. Explain how to overload constructors or methods in Python?
Answer: Python’s constructor – _init__ () is the first method of a class. Whenever we try to instantiate an object __init__() is automatically invoked by python to initialize members of an object.

10. Explain how to redirect the output of a python script from standout(ie., a monitor) on to a file?
Answer: They are two possible ways of redirecting the output from standout to a file.
Open an output file in “write” mode and the print the contents into that file, using sys.stdout attribute.

import sys
filename = “output file” sys.stdout = open() print “testing”
you can create a python script say .py file with the contents, say print “testing” and then redirect it to the output file while executing it at the command prompt.
Eg: has the following code:
print “Testing”
execution: python > output file.
Go through this Python tutorial to get a better understanding of Python Input & Output.

11. Explain the shortest way to open a text file and display its contents?
Answer: The shortest way to open a text file is by using “with” command as follows:

with open(“file-name”, “r”) as fp:
file data =
#to print the contents of the file print(fileData)

12. How do you create a dictionary which can preserve the order of pairs?
Answer: We know that regular Python dictionaries iterate over <key, value> pairs in an arbitrary order, hence they do not preserve the insertion order of <key, value> pairs.

Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the same interface like the general dictionaries but it traverses through keys and values in an ordered manner depending on when a key was first inserted.

from collections import OrderedDict
d = OrderDict([(‘Company-id’:1),(‘Company-Name’:’Intellipaat’)])
d.items() # displays the output as: [(‘Company-id’:1),(‘Company-Name’:’Intellipaat’)]

13. When does a dictionary is used instead of a list?

  • Dictionaries – are best suited when the data is labeled, i.e., the data is a record with field names.
  • lists – are a better option to store collections of un-labeled items say all the files and subdirectories in a folder. List comprehension is used to construct lists in a natural way.
  • Generally, Search operation on dictionary object is faster than searching a list object.

14. How are Inheritance and Overriding methods are related?
Answer: If class A is a subclass of class B, then everything in B is accessible in /by class A. In addition, class A can define methods that are unavailable in B, and also it is able to override methods in B. For Instance, If class B and class A both contain a method called func(), then func() in class B can override func() in class A. Similarly, a method of class A can call another method defined in A that can invoke a method of B that overrides it.

15. What is a Python module?
Answer: A module is a Python script that generally contains import statements, functions, classes and variable definitions, and Python runnable code and it “lives” file with a ‘.py’ extension. zip files and DLL files can also be modules. Inside the module, you can refer to the module name as a string that is stored in the global variable name.

A module can be imported by other modules in one of the two ways.

16. Name the File-related modules in Python?
Answer: Python provides libraries/modules with functions that enable you to manipulate text files and binary files on the file system. Using them you can create files, update their contents, copy, and delete files. The libraries are os, os.path, and shutil.
Here, os and os.path – modules include functions for accessing the filesystem.

17. Executing DML Commands Through Python Programs?
Answer: DML Commands are used to modify the data of the database objects

Whenever we execute DML Commands the records are going to be modified temporarily
Whenever we run “rollback” command the modified records will come back to its original state
To modify the records of the database objects permanently we use “commit” command
After executing the commit command even though we execute “rollback” command, the modified records will not come back to its original state
Create the emp1 table in the database by using the following command
Create table emp1 as select * from emp;
Whenever we run the DML commands through the python program, then the no.of records which are modified because of that command will be stored into the rowcount attribute of the cursor object
After executing the DML Command through the python program we have to call the commit method of cursor object.

18. How to display the contents of the text file in reverse order?
Answer: convert the given file into a list.
reverse the list by using reversed()
Eg: for line in reversed(list(open(“file-name”,”r”))):

19. Which statement of Python is used whenever a statement is required syntactically but the program needs no action?
Answer: Pass – is no-operation / action statement in Python
If we want to load a module or open a file, and even if the requested module/file does not exist, we want to continue with other tasks. In such a scenario, use a try-except block with pass statement in the except block.

try:import mymodulemyfile = open(“C:myfile.csv”)except:pass

20. Explain the use of with statement?
Answer: In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

The general form of with:

with open(“filename”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()

21. Explain all the file processing modes supported by Python?
Answer: Python allows you to open files in one of the three modes. They are:

read-only mode, write-only mode, read-write mode, and append mode by specifying the flags “r”, “w”, “we”, “a” respectively.
A text file can be opened in any one of the above said modes by specifying the option “t” along with
“r”, “w”, “we”, and “a”, so that the preceding modes become “rt”, “wt”, “we”, and “at”.A binary file can be opened in any one of the above said modes by specifying the option “b” along with “r”, “w”, “we”, and “a” so that the preceding modes become “RB”, “wb”, “rwb”, “ab”.

22. What is the Difference Between Methods & Constructors?
Methods Constructor
Method name can be any name Constructor name should be
The method will be executed whenever we call a method Constructor will be executed automatically whenever we create an object
With respect to one object, one method can be called for ‘n’ members of lines
With respect to one object, one constructor can be executed only once

Methods are used to represent business logic to perform the operations Constructors are used to defining & initializing the nonstatic variable. 

23. What is Encapsulation?
Answer: The concept of binding or grouping related data members along with its related functionalities is known as an Encapsulation.

24. What is Garbage Collection?
Answer: The concept of removing unused or unreferenced objects from the memory location is known as a Garbage Collection.
While executing the program, if garbage collection takes place then more memory space is available for the program and rest of the program execution becomes faster.

  • The garbage collector is a predefined program, which removes the unused or unreferenced objects from the memory location
  • Any object reference count becomes zero then we call that object as an unused or unreferenced object
  • Then no.of reference variables which are pointing the object is known as a reference count of the object.
  • While executing the python program if any object reference count becomes zero, then internally python interpreter calls the garbage collector and garbage collector will remove that object from memory location.

25. Whenever Python exists Why does all the memory is not de-allocated / freed when Python exits?
Answer: Whenever Python exits, especially those python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always deallocated/freed/uncollectable.
It is impossible to deallocate those portions of memory that are reserved by the C library.
On exit, because of having its own efficient cleanup mechanism, Python would try to deallocate/
destroy every object.

26. What is JSON? How would convert JSON data into Python data?
Answer: JSON – stands for JavaScript Object Notation. It is a popular data format for storing data in NoSQL
databases. Generally, JSON is built on 2 structures.

  • A collection of <name, value> pairs.
  • An ordered list of values.
  • As Python supports JSON parsers, JSON-based data is actually represented as a dictionary in Python. You can convert JSON data into Python using load() of the JSON module

27. What are negative indexes and why are they used?
Answer: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is used as the first index and ‘1’ as the second index and the process goes on like that.

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.

28. Explain the use of decorators?
Answer: Decorators in Python are used to modify or inject code in functions or classes. Using decorators, you can wrap a class or function method call so that a piece of code can be executed before or after the execution of the original code. Decorators can be used to check for permissions, modify or track the arguments passed to a method, logging the calls to a specific method, etc. ( oracle apex training online  )

29. What is the difference between NumPy and SciPy?
Answer: 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.

30. Does Python support interfaces like in Java?
Answer: Discuss.

Python does not provide interfaces like in Java. Abstract Base Class (ABC) and its feature are provided by the Python’s “ABC” module. Abstract Base Class is a mechanism for specifying what methods must be implemented by its implementation subclasses. The use of ABC’s provides a sort of “understanding” about methods and their expected behavior. This module was made available from Python 2.7 version onwards.

31. What is Multithreading?
Answer: Thread Is a functionality or logic which can execute simultaneously along with the other part of the program
Thread is a lightweight process
Any program which is under execution is known as process
We can define the threads in python by overwriting run method of the Thread class
Thread class is a predefined class which is defined in the threading module
Thread in the module is a predefined module
If we call the run method directly the logic of the run method will be executed as a normal method logic
In order to execute the logic of the run method as we use the start method of thread class.


Import threading
Class x(threading.Thread):
Def run(self):
For p in range(1, 101):
Class y(threading.Thread):
Def run(self):
For q in range(1, 101):

32. How would you define a protected member in a Python class ?
Answer: All the members of a class in Python are public by default. You don’t need to define an access specifier for members of the class. By adding ‘_’ as a prefix to the member of a class, by convention you are telling others please don’t this object, if you are not a subclass the respective class.
Eg: class Person:
empid = None
_salary = None #salary is a protected member & it can access by the subclasses of Person.

33. Name a few methods that are used to implement Functionally Oriented Programming in Python?
Answer: Python supports methods (called iterators in Python3), such as filter(), map(), and reduce(), that are very useful when you need to iterate over the items in a list, create a dictionary, or extract a subset of a list.
filter() – enables you to extract a subset of values based on conditional logic.
map() – it is a built-in function that applies the function to each item in an iterable.
reduce() – repeatedly performs a pair-wise reduction on a sequence until a single value is computed.30 Essential Python Interview Questions You Should Know.

34. How is Python executed?
Answer: Python files are compiled to bytecode. which is then executed by the host.
Alternate Answer:
Type python .pv at the command line.

35. What is the difference between .py and .pyc files?
Answer: python files are Python source files. .pyc files are the compiled bytecode files that are generated by the Python compiler.

36. How do you invoke the Python interpreter for interactive use?
Answer: python or python.y where x.y is the version of the Python interpreter desired.

37. What is the process of compilation and linking in python?
Answer: The compiling and linking allows the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter.

The steps that are required in this as:

  • – Create a file with any name and in any language that is supported by the compiler of your system. For example comp.c
  • – Place this file in the Modules/ directory of the distribution which is getting used.
  • – Add a line in the file Setup.local that is present in the Modules/ directory.
  • – Run the file using spam comp.o
  • – After a successful run of this rebuild the interpreter by using the make command on the top-level directory.
  • – If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’.

38. What are tuples in Python?
Answer: A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

39. What happens if an error occurs that is not handled in the except block?
Answer: The program terminates. and an execution trace is sent to sys.stderr.

40. How are Phon blocks defined?
Answer: By indents or tabs. This is different from most other languages which use symbols to define blocks. Indents in Python are significant.

41. How do you execute a Python Script?
Answer: From the command line, type python .py or where the x.y is the version of the Python interpreter desired.

Learn how to use Python, from beginner basics to advanced techniques.

42. How to use GUI that comes with Python to test your code?
Answer: That is just an editor and a graphical version of the interactive shell. You write or load code and run it, or type it into the shell.
There is no automated testing. ( data science online training )

43. How will you convert a string to all lowercase?
Answer: lower() − Converts all uppercase letters in a string to lowercase.

44. What is the Dictionary?
Answer: Dictionary objects can be created by using curly braces {} or by calling dictionary function

  • Dictionary objects are mutable objects
  • Dictionary represents a key-value base
  • Each key-value pair of Dictionary is known as an item
  • Dictionary keys must be immutable
  • Dictionary values can be mutable or immutable
  • Duplicate keys are not allowed but values can be duplicate
  • Insertion order is not preserved
  • Heterogeneous keys and heterogeneous values are allowed.

45. How does the Python version numbering scheme work?
Answer: Python versions are numbered A.B.C or A.B.

A is the major version number. It is only incremented for major changes in the language.
B is the minor version number, incremented for less earth-shattering changes.
C is the micro-level. It is incremented for each bugfix release.

  • Not all releases are bug fix releases. In the run-up to a new major release, ‘A’ series of development releases are made denoted as alpha, beta, or release candidate.
  • Alphas are early releases in which interfaces aren’t finalized yet; it’s not unexpected to see an interface change between two alpha releases.
  • Betas are more stable, preserving existing interfaces but possibly adding new modules, and release candidates are frozen, making no changes except as needed to fix critical bugs.
  • Alpha, beta and release candidate versions have an additional suffix.
  • The suffix for an alpha version is “aN” for some small number N,
  • The suffix for a beta version is “bN” for some small number N,
  • And the suffix for a release candidate version is “CN” for some small number N.
  • In other words, all versions labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled 2.0cN, and those precede 2.0.
  • You may also find version numbers with a “+” suffix, e.g. “2.2+”. These are unreleased versions, built directly from the subversion trunk. In practice, after a final minor release is made, the subversion trunk is incremented to the next minor version, which becomes the “a0” version, e.g. “2.4a0”.

46. How do you perform pattern matching in Python?
Answer: Regular Expressions/REs/ regexes enable us to specify expressions that can match specific “parts” of a given string. For instance, we can define a regular expression to match a single character or a digit, a telephone number, or an email address, etc. The Python’s “re” module provides regular expression patterns and was introduce from later versions of Python 2.5. “re” module is providing methods for search text strings, or replacing text strings along with methods for splitting text strings based on the pattern defined.

Note: Browse latest Python Interview Questions and Python Tutorial Videos. Here you can check Python Training details and Python Training Videos for self learning. Contact +91 988 502 2027 for more information.

Leave a Comment

Scroll to Top