Top 20 Python Interview Questions And Answers

02 Sep 2022
16 min read  
  1. What is Python?

    Python is a dynamic, interpreted, easy to learn, readable high-level programming language. It was created in 1991 by Guido van Rossum. It is a versatile programming language and allows you to do many things, both big and small. Python is being used in different areas like Machine learning, Data analysis, Web Development, Automation and many more. If you are beginner in programming, then python suits for your career.

  2. What are the major features of Python?

    There are following Features of Python:

    • Dynamic Typing - Python doesn't have something like type declaration of variable, it automatically tracks the objects when your program runs.

    • No Manual Memory Management - Python uses garbage collector rather than manual memory management. The allocation and reclamation of memory from objects which are not referenced further are collected by Pythons garbage collector.Objects grow and shrink on demand.

    • Essential object types - Python provides basic data structures such as lists, dictionaries tuples, and string as an essential part of language and they are versatile and easy to use.

    • Useful Packages - Python has large collection of packages for different purposes and has great support in the community. Python has packages for everything searching, sorting, data analysis, web development, machine learning, socket programming, NLP and many more.

    • Programming-in-large-support - Python includes tools such as class, modules, and exceptions. These tools enable you to modularize your system and use OOP to reuse and use your logic in code for customization, handle events and errors.

  3. How Python is different from other languages like Perl or Java?

    Python is often compared to similar tools whereas there are numerous tools that can be used like Tcl, Pearl, and Java. But Python is:

    • More powerful than Tcl so it is suitable for large system developments.

    • More readable and simple to understand syntax as compared to Perl. The readability is high and easy to maintain large code base

    • We can't compare it with java at head-on. Python is a scripting language whereas Java is system language like C++.

  4. What is the difference between a Python module and package?

    A module in Python is a single file that you can import in your Python program and use it by using the "import" keyword followed by the filename. A package is a collection of modules that means it contains more than one Python module. Packages can be nested up to any depth with directories containing a special file called Modules are created and used when you want to share small code of functions everywhere in your project. Suppose you have a bunch of functions querying database so you can put all at one place and can import that file wherever you want that will make it more maintainable and easier to debug. Packages are vaster and contain lots of features some of popular packages are opencv, pandas etc. Packages have special purpose to server in program.

  5. How to declare and access a docstring?

    Declaring: Docstrings are declared using """ triple double quotes and ends with """ triple double quotes. All functions should have a docstring.

    Accessing: Docstrings can be accessed via help function of Python to access the docstring or you can use __doc__ method.

    def new_function(): 
     """Piece of information a docstring."""
     return None
    print("with __doc__:")
    print("with help:")
    with __doc__:
    Piece of information a docstring..
    with help:
    Help on function new_function in module __main__:
     Piece of information a docstring.
  6. What is LGB rule for name resolution in Python?

    References are searched at most 3 scopes: local, global, and built -in. When a name reference inside a function then it’s in local scope by default. If you want to use global variables then before use declare them as global inside function. This concept of name resolution called LGB rule. When you use a named reference inside function python first search it in Local(L) scope, then the Global(G) and then the built-in (B) and will stop at first place where name is found.

      Built in (Python)
    • Predefined names - open, len, etc.

    • Global (Module)
    • Names assigned at top - level of a module.

    • Name declared "global" in function.

    • Local (Function)
    • Name assigned inside a function (def)

    # global scope
    A = 56 # A and fun assigned in module: global
    def fun (B): # B and D assigned inside function: locals
     # local scope
     D = A + B # A is not assigned, so it's a global
     return D
    fun(1) # fun in module: result = 57
  7. What is global declaration in python?

    There is only one thing in python that is like declaration is the "global" keyword. "global" means a name has a scope at the top level of module file. If you want to use a value of that variable inside a function then only you should declare it as Global. Global names can be referenced inside function without declaration. The global keyword is followed one or more names comma separated inside a function body only. The names which are assigned or referenced inside function body are mapped to module level scope.

    A, B = 1, 2 # global values
    sum = 0 
    def global_values():
     global sum # Global declaration
     sum = A + B # no declaration needed as not an assignment
    Explanation: -

    Here sum, A and B are all global inside function global_values. A and B are global because we haven't assigned it and "sum" is global because we declared it so and listed it in a global statement.

  8. What is Lambda in Python?

    Beside def python provides lambda that can generate function objects. "def" keyword in Python is used for declaration of a function whereas lambda is basically to create an anonymous function. Lambda function contains one or more arguments followed by an expression. Function objects by def and lambda are exactly the same. But lambda has few things that makes it different from normal function.

    • Lambda is an expression, not a statement

    • Lambda can appear in places where a def can't like inside a list constant. Lambda returns a function that can be assigned a name.

    • Lambda bodies are a single expression, not a block of statements

    • Lambda is not like block of statements in def but similar to what you write in return statement of def.

    It follows following syntax

     def func(a, b, c) : return a + b + c
     func( 1, 2, 3)
     f = lambda a, b, c: a + b + c
     f(2, 3, 4)
  9. What is the equivalent of procedures in python?

    In python it's not mandatory that you return something at end of function when you don't return the function returns None object automatically. Functions with such behavior in Python are equivalent to procedures in some languages. Procedure are meant to do their work without computing a useful result. For example, appending an item to a list won't and assigning it to a name won't raise error but you do get 'None' object.

    Example Code
     mylist = [1, 2, 3 ]
     mylist = mylist.append(4)
     print mylist
  10. What are decorators?

    A Python decorator is to add functionality to an existing code. A decorator takes a function as argument adds some functionality and returns the function.

    Example Code
    def safe_divide(func):
     def inside(a,b):
     print("Dividing two values",a,"and",b)
     if b == 0:
     print("You can not divide by zero")
     return func(a,b)
     return inner
    def divide(a,b):
     return a/b

    We can use the symbol '@' then the decorator name to wrap a function. In layman term we can say our divide function is a gift and safe divide is wrapper i.e, a decorator for the function.

  11. Why to use modules in Python?

    In simplest way module provides a way to organize components into system. Modules do have an important role in python:

    Code reusability

    Code in a module files is persistent and can be reused, reloaded as many times as needed. Modules can be easily imported in any python file and used.

    System namespace partitioning

    Modules are highest level or program organization unit. Everything lives in a module code you execute and some objects. Modules are natural tool for grouping components.

    Implementing shared service or data

    We can provide a global data structure that can be used by more than one function, and can be imported by many clients

  12. How to achieve multi-threading in Python?

    Python do gives you a multi-threading package and you can use it, but it’s not considered as a good idea. Python has Global Interpreter Lock (GIL). GIL makes sure that only one thread executes at a time and then it will switch to another thread. The switching between the threads may seem like multi-threading but it’s just faster switching which human eye can't recognize and we think like they are getting executed parallel. But all will be executing the same CPU core. The switching actually puts extra overhead in code execution. So, if you are thinking of speeding up your code with Python's threading library then it's not a good idea.

  13. What is the significance of subprocess in Python?

    The subprocess module in Python is useful in executing programs or piece of code that is written in some other language. You can create a subprocess and execute the file or code. It helps to obtain input/output/error pipes with exit codes.

    Example: C Program

    #include< stdio.h> 
    int main() 
     printf("Hello World from C Program"); 
     // returning with 0 would raise an exception in Python
     return 0; 

    Python 3 program to execute C program

    import subprocess 
    import os 
    def executeC(): 
     s = subprocess.check_call("gcc helloworld.c -o out1;./out1", shell = True) 
     print(", return code : -", s) 
    Hello World from C Program, return code : - 0
  14. What is init method in a python class?

    __init__: Reserved method in python classes. It is similar to writing a constructor in other object oriented languages.This method called when you create an instance of a class and you can pass parameters that will be used to initialize the attributes.

    Usage: Let's say you are creating a car racing game. For that we should have a car and car have some basic attributes like "color", "company", "top speed", "mileage" etc.

    class Taxi(object):
     def __init__(self, name, domain, total_employee, founder): = name
     self.domain = domain
     self.total_employees = total_employee
     self.founder = founder
     def create_company(self):
     print("company created")
     def increment_employee(self, gear_type):
     print("employees increased")
     " add employee functionality here"
    Let's create different cars.
    car1 = Company("honda city", "Infrastructure", 100, "rahul")
    car2 = Company("Numberica", "IT", 180, "rajiv")

    We have created two different types of company objects with the same class. While creating the instance we passed arguments "honda city", "Infrastructure", 100 these arguments are passed to "__init__" method to initialize the instance of car class. "self" points or can be used to access the instance of the class. It maps and ties the attributes with the given arguments.

  15. Explain the inheritance in Python with example?

    Re-usability is one of the major advantages of Object-Oriented Programming. To achieve re-usability Inheritance is one of the mechanisms. Inheritance is a mechanism where a class usually called as parent class or super class is inherited by another class which is known as child class or subclass. Subclass can add some attributes to its own class as well use the attributes of parent class. We will try to understand more on inheritance with the help of below example

    Example to demonstrate inheritance:
    class People(object): 
     # constructor 
     def __init__(self, name): = name 
     # To get name 
     def get_name(self): 
     # To check if this person is employee 
     def is_staff(self): 
     return False
    # Inheriting People Class
    class Staff(People): 
     #return true 
     def is_staff(self): 
     return True
    staff1 = People("Staff1") # Object of People 
    print(staff1.get_name(), staff1.is_staff()) 
    staff2 = Staff("Staff2") # Object of Staff
    print(staff2.get_name(), staff2.is_staff())
    (Staff1, False)
    ('Staff2', True)
  16. How you can check if a class is a subclass of another class?

    Python provides method "issubclass" that returns true if a class is a subclass of another class.

    Example: Below example illustrating the use of "issubclass" method.

    class Parent(object): 
    class Child(Base): 
    print(issubclass(Child, Parent)) 
    print(issubclass(Parent, Child)) 
    a = Child() 
    b = Parent() 
    # b is not an instance of Child 
    print(isinstance(b, Child)) 
    # a is an instance of Parent 
    print(isinstance(a, Parent)) 
  17. What are Errors and Exceptions in Python?

    There are two types of errors.

    • syntax error
    • exceptions.

    Syntax Error

    These kind of error mainly occurs when you forgot some syntax for a statement let's say you are writing an "IF ELSE" statement and you forgot to put a colon after the "IF" condition then python parser would throw a syntax error and will exit abnormally displaying the line number and error statement. These errors are also known as parsing error.


    Exceptions in a program occurs when the normal flow of the program is interrupted due to an external event. Even with correct syntax, there are chances that your program flow can stop due to external or dynamic changes inside program. Example: - some where you are doing some calculations and your value became zero which is going to divide a number this will throw a "ZeroDivisionError". Some of the examples of exceptions are - ZeroDivisionError, TypeError and NameError.

  18. What are custom errors in Python?

    Python has good amount of built-in functions to generate exceptions. But sometimes you require to raise some custom exceptions. To create your own custom exception, you need to derive indirectly or directly the class "Exception". Built-in exceptions are derived from "Exception" class. When developing a large Python application its good practice to define all your user defined exception in "" or "" file. Most widely used standard to define "User defined Exceptions" is creating a base class and inheriting all other exception from that class.

    Example: In below example we will create a user defined error that will raise an error if the value is lower than expected or bigger than expected.

    # define Python user-defined exceptions
    class Error(Exception):
     """Base class other exceptions will inherit this class"""
    class ValueSmallError(Error):
     """Raised when Input value is small"""
    class ValueLargeError(Error):
     """Raised when input value is large"""
    # user will guess a number until the guess is right
    # number to be guessed
    value = 15
    while True:
     num = int(input("Guess a number: "))
     if num ? value:
     raise ValueSmallError
     elif num > value:
     raise ValueLargeError
     except ValueSmallError:
     print("This value is smaller than number, try again!")
     except ValueLargeError:
     print("This value is larger than number, try again!")
    print("Congratulations! You guessed the value correctly.")
    Enter a number: 11
    This value is smaller than number, try again!
    Enter a number: 20
    This value is larger than number, try again!
    Enter a number: 16
    This value is larger than number, try again!
    Enter a number: 15
    Congratulations! You guessed the value correctly.

    Above is one of the standard ways of defining user defined errors. We have defined "Error" as our base class.

  19. What is the end parameter in Python?

    Python's print() function has an argument called 'end'. By default, it is set to '\n', i.e. the new line character. You can specify your own value in 'end' parameter.

    print("Welcome" , end = ' ') 
    print("Rahul", end = ' ')
     Welcome Rahul 
  20. How can you find bugs or perform static analysis in Python?

    There are certain tools available to do static analysis and bug finding in Python program one of them is PyChecker which is a static analysis tool that can detect bugs in source code and the style and complexity of the bug. Pylint is handy which tells you unused variable errors or syntactical errors while writing the code. Pylint is helpful in maintaining coding standard.


I hope above mentioned questions and answers will help you to prepare yourself for your Python interview. These interview Questions have been taken from our new released eBook Python Interview Questions & Answers. This book contains more than 100+ Python interview questions.

This eBook has been written to make you confident in Python with a solid foundation. Also, this will help you to turn your programming into your profession. It's would be equally helpful in your real projects or to crack your Python Interview.

Buy this eBook at a Discounted Price!

Python Interview Questions & Answers eBook
About Author
Rahul Jain (Author and Developer)

He is an Author, developer and an enthusiastic learner. He has a great experience in development and analytics with python. As a Professional, he is passionate and always ready to learn new technology and & sharing them with others.
Learn to Crack Your Technical Interview

Accept cookies & close this