Python Interview Questions

By | February 21, 2021
Python Interview Questions

Python is one of the most versatile and powerful programming languages of 2021. It has a very bright future and promises many opportunities for its developer. So, whenever you apply for a job as a Python Developer, you have to face the Python interview where the interviewer will test your python skills. It has often seen that during the interview interviewer asks questions from core python and the candidate not able to answer those. So it always recommended that make your basics concepts reliable. Here in this article, we have provided the Top 100+ Python Interview questions, which are frequently asked during python Interviews. We hope these Python Interview questions and answers would help you to crack the interview.

Top Python Interview Questions and Answers

Basic Python Interview questions

In mostly all the Python interviews the interviewer will first check your Python basic knowledge based on core Python Programming. In the basic Python interview, you face problems from Python core syntax and Python data structure. On the basis of your answer, the interview will estimate your python skills and may further ask you Python intermediate and advance questions related to your answer.


Let’s first have a look at some of the Python interview questions for freshers

Question: What is Python?
Answer: Python is the most popular, high-level, object-oriented, interpreted programming language. It’s easy to read and learn syntax make it one of the easiest programming languages and it also reduces its program maintenance cost.

Question: What do you mean by interpreted programming language?
Answer: An Interpreted programming language is a type of Programming language which uses an interpreter to execute the program code. And in an interpreted programming language the code gets directly executed without compiling into a machine language code.

Question: Name some main Features of Python for which it is Popular.

  1. It supports the Functional and structured Programming language, which also follows the concepts of OOP’s.
  2. It is a dynamic language.
  3. It has a feature of Automatic Garbage collection.
  4. It is very easy to interpret.

Question: Tell some benefits of Python.

  • It is a Dynamic language
  • It supports object-oriented programming languages
  • It does not have a concept of access modifiers like private, public, and protected but you can use magic functions to use the methods as public or private.
  • It has a very simple syntax which makes it easy to learn.
  • Apart from desktop application python is also used for web development.

Question: How Python is a Dynamic typed Language?
Answer: In Python, we do not need to define the type of variable we declare. The type of variable is unknown until the interpreter executes the code. So, the declaration of the variable type is of no use. The Python binds the value with the variable name and stores the value at the memory location. And using the variable name we can access the value of the variable and we can also change the value and data type of the variable throughout the program.


var1=10 # var1 is an integer type

var2 ="Hello world" # var2 is a string

Question: What pass keyword do and why do you use it?
Answer: The pass is a special keyword in the python that performs the NULL operation.

In python, if you declare an if statement or a function you have to define its body or statement, if you do not define them, the python interpreter will through an error. To overcome this error, you can use the pass keyword inside the if and functions statements.


remove_h= "hello world"

for i in remove_h:
    if i==h:


Question: Name all the inbuild datatype in python:
Answer: Python has 6 inbuilt data types

  1. Numbers in Python represent the numeric value.
  2. Strings in python represent the sequence of characters inside the double and single quotes.
  3. List is an ordered and mutable data structure that can store multiple data values.
  4. Tuples is an ordered, and immutable python data structure that can store multiple data values.
  5. Dictionaries is an unordered and mutable python data structure that stores elements in the form of key:value pair.
  6. Sets is an unordered and mutable python data structure that only contain unique element value.

Question: What are Mutable and Immutable Datatypes

  • Mutable are those data types in python whose value can be changed.e.g.list, Dictionaries, and Sets
  • Immutable are those data types once they have been assigned you cannot manipulate their values.e.g.Strings, Tuples and Numbers

Question: What are the sets in Python?
Answer: Sets are the unordered collections of data values that are immutable and do not accept the repetitive values. sets are iterable object but do not accept indexing.

#set syntax


{1,2,3,4,5,6} #it eliminates the repetitive values

Question: What are tuples in Python?
Answer: Tuple is an ordered and immutable Python inbuilt data structure Tuple can store heterogeneous elements but it is generally used to store heterogeneous data elements. Like a list tuple also supports indexing and slicing to retrieve elements.


tup=(1,2,3,4,5) # to declare a tuple we use parentheses



Question: What are Dictionaries in Python?
Answer: Python Dictionaries are the collections of keys and value pairs separated by a colon. A dictionary key can only be represented by an immutable data type whereas a value could be of any data type.


>>> dict = {"one": "its one", "two" :  "its two", "three" : "its three"}
>>> print( dict["two"]) 
>>> its two # output

 Question: Can we use a list as a key of a dictionary?
Answer: No, the keys of the dictionary are supposed to be an immutable data type, but the list is a mutable data type. However, we can use a string and tuple as a dictionary key.

Question: Write a code to convert 144 into a string
Answer: To convert any data object or value to a string, we can use the Python str() method.


Question: What are *args?
Answer: *args is a special syntax that can accept a number of arguments pass to a function and treat those as a tuple.


def arg(*args):



<class ‘tuple’>

Question: What are **kwargs in python?
Answer: **kwargs are similar to *args, a special syntax which can accept a number of argument pass to function but in kwargs treats the passed argument as a Dictionary.


def kwa(**kwargs):

kwa(x="hello", y="world",z=4)


{'x': 'hello', 'y': 'world', 'z': 4}

<class 'dict'>

Question: What does the end statement do in python?
Answer: Whenever we use a print() method to print a statement the statement printed on a new line. The end is an additional parameter of the print() method which have a value of ‘\n’ by default that’s why every print() statement print on a new line. We can manipulate the value of the end to change the print statement format. The end parameter defines what would be the end of the print statement.


print("hello", end=" ")
print("world") #here end value id ‘\n’ by default
print("go for", end="-")


hello world
go for-it

Question: What is a lambda function in Python?
Answer: Lambda function in Python is also known as an anonymous function. An anonymous or lambda function represents a function without a name and it is widely used to write function statements in a single line.

To create a lambda function in Python we use the lambda keyword, and as a normal user-defined function it can accept arguments and return a value.


# Normal function in python

def mul(a,b):
    return a*b


#lambda function
mul=lambda a,b : a*b

Question: What is the difference between Python list and Python tuple?

Python list Python Tuples
Python list is a mutable data structure Python tuples are immutable data structure.
List consume more memory space as compared to tuples Tuples consume less space as compared to the Python list.
The iterating process takes more time in the Python list. Iterating processes take less time in Python tuple as compared to the python list.
An operation like insertion and deletion is much faster in a Python list. Accessing individual elements is faster in Python tuple.
List support more methods as compared to tuple. Tuple does not have many in-built methods.
List is widely used when we want to store heterogeneous data values. A tuple is generally used for homogeneous data values.
To define a list, we have to use the square bracket To define a tuple, we use the parenthesis.


list1=[0,1,2,3,4] #list

tuple1=(0,1,2,3,4) #tuples

list1[2]=4 #Mutable

tuple1[2]=4 # it will through an error because tuples are immutable

Question: What is negative indexing in python?

Answer: Python data-types such as list, tuples, and string support the positive as well as negative indexing. In negative indexing, we fetch the data values from the end of the data structure. for example if you pass -1 index it will call the last value of the list or if you call -2 indexing it will the second-last value of the list.







Question: What are the Exceptions in Python?
Answer: Exception in Python are the errors which generally occur during the runtime. FileNotFoundError, ZeroDivisionError, ValueError and ImportError, are some of the most common exceptions.


num = int(input("enter number: "))



enter number: one
Traceback (most recent call last):
num = int(input("enter number: "))
ValueError: invalid literal for int() with base 10: 'one'

Question: How can we raise an Exception in Python
Answer: In Python, we have the raise keyword which can be used to raise the error in a Program.

print(" hello ")

raise ValueError

print(" world ")




Question: How can we import modules in Python?

Answer: There are three methods we can use to import a module in a Python script.

import numpy #this import the numpy module

import numpy as np  # this import the numpy module with alias name np

from numpy import *  #this will import all the method and classes present in the numpy module

Question: Does Python have a concept of inbuilt Array?
Answer: However, Python does not have inbuilt support for Array Data structure, like it supports list, set, tuple, and dictionary. But python-support an inbuilt module array which provides an array data structure for python. The Python array module is not that much efficient and that’s why developers always prefer to use numpy array.


import array

arr = array.array(‘d’, [1,2,3,4])

Question: Name all the type conversion methods present in Python.


Type conversion method Description
int() convert the object into integer
float() convert the object into floating point number
list() convert the object into list
dict() convert the object into dictionary
tuple() convert the object into tuple
str() convert the object into string
ord() convert the character into corresponding ASCII value.
chr() Convert the ASCII value to character.
oct() convert the integer to octal value
complex(real, imag) convert the integer value to complex number.
hex() convert the integer value to hexadecimal.

Question: What is namespace in Python?

Answer: Namespace is a naming system that allows us to have the same name for different values that are present at different scopes.


a  =70  #global scope
def func():
    a = 30 #local scope



Question: What range function does in python?
Answer: range() is a special function python, it is used to iterate over a number of the sequence. range function can accept 3 arguments initial state, last state and the steps taken to reach the last point.


for i in range(2,10,2)



Question: What are dictionaries in python and how they are different from a list?
Answer: A dictionary is an in-built data type in python which stores elements in the form of key and values pair separated by a colon(:).

Dictionary syntax:

dic= {“key1”: “value1”, “key2″:”value2”}

Python list Python dictionary
Python list is an ordered data structure. Python dictionary is an unordered data structure.
In list, we use indexing to access the individual element. In dictionary, we use the key name to access the individual element.
To initialize a list, we use the square brackets To initialize a dictionary, we use curly brackets.
List occupies less memory as compared to a dictionary. A dictionary occupies more memory as compared to a list

Question: What is slicing in python?
Answer: Slicing provides a special syntax that allows the user to retrieve a specific sequence of elements from the list. With the help of indexing we can retrieve a single element from the list and string, but using slicing we can retrieve a sequence of elements.


# List slicing

lis=[1, ”hello”,3, ”world”,5,6,7, ”I am”,”here”]




[“world”,6,”I am”]

Question: Does python have a compiler?
Answer: Yes, python does have the compiler. It’s works automatically.

Question: What is an index in python?
Answer: In python to retrieve a specific value from a list, sting, or tuples we use the index. An Index is an integer that starts from 0 and up to n-1, where n represents the total number of elements present in the data structure.

Question: What does a map() function do in python?
Answer: A map() is an inbuilt Python method that takes 2 arguments, a function and the iterable object. The map function passes all the values of the iterable through the function one by one and returns a map object. The map() function comes very usefully when we want to perform a function on every element of the list.


def mul3(num):
    return n*3




Question: Explain filter() function.
Answer: filter() is an inbuilt Python method that is used to filter iterable object elements based on a function. It accepts two parameters, a function name and an iterable object. It passes the iterable object’s elements to the function one by one and returns an iterable object containing only those elements which satisfy the function.

#filter syntax

res=list(filter(lambda x: x%2==0,lis))




Question: Does python support procedural programming?
Answer: Yes, though python is known for its object-oriented programming, python does support procedural programming.

Question: What is a function in Python?
Answer: A function is a set of code that is used to perform a specific task. the function helps us to enhance the reusability of code. In python to declare a function, we use a def keyword.

Question: How many types of Function does python have?
Answer: Like another programming, language python has 2 types of functions

  1. Built-in functions (functions already provided by the python)
  2. User-defined functions

Question: What are the Local variables?
Answer: When a variable is assigned inside a function is known as Local variable and only that specific function is allowed to use that variable.


def func():
    local_var = 30

Question: What are the global variables?
Answer: All those variables which are not defined inside a function are known as a global variable and any function can access a global variable.


global_var =70

def func():
    local_var = 30



Question: If we declare a function and do not define it what will happen?
Answer: If we only declare a function and do not define its body then the python interpreter will throw an error. But using the pass keyword we can declare a function and later define its body.

Question: If a Python function does not have a return statement then what it returns?
Answer: If a function does not have a return statement then it returns None.


def func():
    a =20




Question: What a break statement does in Python?
Answer: A break statement terminates the loop statement and stops the iteration.


#break syntax

for i in range(4):
    if i==2:



Question: If a break statement is used inside the nested loop then which loop it will terminate?
Answer: If we use a break statement inside a nested loop then it will terminate the innermost loop.


for i in range(5):
    print("outer loop", i)
        for j in range(5):
            if j ==2:

print("inner loop", j)


outer loop 0
inner loop 0
inner loop 1
outer loop 1
inner loop 0
inner loop 1
outer loop 2
inner loop 0
inner loop 1
outer loop 3
inner loop 0
inner loop 1
outer loop 4
inner loop 0
inner loop 1

Question: What does continue keyword do in python?
Answer: The continue statement jump back to the loop without executing the next statements.

#continue syntax

for i in range(10):
    if i>3:



Question: What ord() and chr() methods do in python?

  • The ord() method return an ASCII code for the character.
  • The chr() perform adverse of ord(), it returns the corresponding value for the given ASCII code.


>>> ord("a")

>>> chr(98)

Question: What does isaplha() method do in python?
Answer: isalpha() is a string method that checks if the string contains only alphabets. If the string contains only alphabets the method will return true else it will return False.



print(“Hello 2”.isalpha())




Question: What does a split() method do in Python?
Answer: split() is a Python string method that split a string into a list of words. By default, the split function split the string into list values by using the white space.


str=’hello world I am here’




['hello', 'world', 'I', 'am', 'here']
['h', 'llo world I am h', 'r', '']

Question: What is the difference between title() and capitalize() methods in Python?

The title() is a string method that uppercase every word first letter and lowercase the rest of the letters.


>>> title = "this iS a TiTlE"

>>> title.title()

'This Is A Title'

The capitalize() is also a string method but it only uppercase the first letter of first word, and lowercase the rest of the string.


>>> title = "this iS a TiTlE"

>>> title.capitalize()

'This is a title'

Question: What is string concatenation and why do we use it?
Answer: String concatenation is a method that concatenates two strings. It is used to combine two strings together.


>>> k= "hello"
>>> l= "world"
>>> p= k+l #string concatenation:
>>> print(p)

Question: What dir() method do in Python?
Answer: The dir() method can return all the properties and methods of an object. With the help of dir() the method, we can find out all the properties a method supported by an object.


>>> dir(tuple)

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

Question: In python how can we use third-party libraries?
Answer: To use a third-party library in Python we first need to install the library. And to install the library we can either go to the python documentation or use the pip install command.

 Question: What is list comprehension in python?
Answer: A list comprehension is a method of creating a new list from an iterable object(list, tuple, set, etc). List comprehension provides an elegant and one line technique to create a list out of the iterable object.


#List comprehension Syntax:


new_list=[i*2 for i in old_list]



[2, 4, 6, 8, 10, 12]

Question: What does help() function do in python?
Answer: help() function shows the documentation related to the object passed in the help parenthesis.



Question: Name the library used to generate a random number?

Answer: Random Library


from random import randint



Question: What is recursion in Python?
Answer: Recursion is a concept in which a function calls itself again and again until the base condition gets satisfied. If there is no base condition the recursion fall in an infinite call.


#Recursion Syntax in python

def fac(n):
    if n==1:
        return 1 # Base Case
        return n*fac(n-1)




Question: What is the base case of recursion and why do we need it?
Answer: A base case in a recursion refers to that statement that does not allow the function to further call itself. A base case is necessary for each recursion if you do not provide a base case to the recursion it will keep calling itself until infinity.

Question: How errors are different from the exception in python?
Answer: Error rise in a program due to some coding issue while exception occurs due to an interruption in the program by unusual inputs.

Question: Can we directly access a function that is defined inside another function?
Answer: No.


def func1():
    def func2():

Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
NameError: name 'func2' is not defined

Question: What are decorators in python?
Answer: Decorators are one of the most powerful tools of python, which allow wrapping a function or class into another function to enhance its functionality.


def  new_decorator(main_func):
    def wrap_func():
        print("Thank Q for Decorating me!")
    return wrap_func

def need_decorator():
    print("I want to decorate")



I want to decorate
Thank Q for Decorating me!

Question: What are the Generators in python?
Answer: Generators are similar to the iterators such as list and tuples, which can be iterate with the help of for loop. To create a generator, we use functions and a special statement called yield. In simple words, generators are the function which yield output instead of returning.

#Generator Syntax

def rev():
    while i>0:
        yield i

for i in rev():



Question: What does yield statement do in python?
Answer: Yield statement used to define a generator, in the normal function we use return statement but in generators, we use yield statement to retrieve a result from a generator.

Question: How the yield statement is different from the return?
Answer: When we call a function if it has a yield statement then it will provide a sequence of results whereas a return statement will provide a specific value. A return statement terminates the function whereas the yield cannot.

Question: Write a code which shows equivalence to this code my_fun=my_dec(my_fun)
Answer: @my_dec

Question: What is a floor division?
Answer: It is similar to the normal division but it returns the floor integer value of the quotient.


print(6//9) #floor division

print(6/9) # Normal division



Question: What is NumPy?
Answer: NumPy is one of the most popular Python libraries, it stands for numerical python and commonly used in Python Data Science. It comes with many powerful built-in methods and NumPy array is one of those. A NumPy array is 10 times faster than the Python list.

Question: What is a Docstring in python?
Answer: Docstring means documentation string and it is used to provide some additional information regarding the Python modules, Functions, Classes and Methods.

Question: What are ternary operators in python?
Answer: Ternary operators are similar to the conditional operator and provide an alternative method to write the conditional operator code in one line.


x= 35
min = x if x < y else y


Question: What is functional programming?
Answer: In functional programming, we can use a function or subroutine as an argument and pass it to another function.


#Functional Programming
def fun1(fun2,arg):
    return fun2(fun2(arg))

def mul(n):
    return n*2




Question: What does del keyword do in python?
Answer: The del the keyword is used to delete the object from the memory.

Python Intermediate and experienced  Interview Questions

By far we have discussed only the Python interview questions for the freshers because in most of the Python interviews the interviewer first checks the basic Python skills of the candidate. Once the interview feels that the candidate’s basic Python skills are strong then he/she starts asking some intermediate and advanced Python interview questions. Now let’s look at some of the Python interview questions for an experienced developer.

Question: Why this statement often use in python if __name__==”__main__”: ?
Answer: __name__ is a special variable in the python which executes first before anything else. It uses with the if statement to check whether the file is executing directly or it’s being imported. If the file is running directly the __name__ variable will be automatically assigned “__main__” if not it assigned as the name of the file.

The __name__==”__main__” statement will return True if the file is executed directly, if this file is imported the __name__==”__main__” statement return False.

Question: What is Python GIL?
Answer: GIL stands for Global Interpreter Lock, and it is a muter or lock which allows only one thread to hold the control of the Python interpreter. This means at a time only one thread of Python is allowed to be in an execution state.

Question: Can we do multithreading in Python?

Answer: Yes, Python has some multi-threading packages which allow us to perform multi-threading in Python. But multi-threading will only be useful to us when the two modules which are running parallel have nothing to do with each other.

Question: What is Polymorphism in Python?

Answer: Polymorphism means multiple forms, and it is one of the properties of Object-Orientation programming. According to this property, two different objects can have the same property or method name but can have a different implementation. For instance, the + operator performs addition for integer objects and concatenation for string objects.

Question: What is encapsulation in Python?

Answer: Encapsulation is one of the object-oriented programming properties, and it means binding the code and data together. Python class is an example of OOP’s encapsulation.

Question: What is Data abstraction in Python?

Answer: Data Abstraction is an extension of Data Encapsulation, and it deals with hiding the inner functionality of a program from the user. In Python, data abstraction can be achieved by using Private properties and methods.

Question: How the python list is different from a linked list.
Answer: The Python list uses the contiguous memory location to store the list values like an array, whereas the linked List values do not store in a contiguous memory location.

 Question: Name some tools which can be used to find a bug in Python


PyChecker is one of the open-source static analysis tool, which can be used to find the bug in a Python source code.

Pylint is another very popular python debugger tool that can warn us about the bugs and error present in the Python source code.

Question: What are predicates?
Answer: A predicate is a function which that returns a True value based on some condition, for example, the Python filter() method uses a predicate function to filter out the elements from an iterable object.


filter(predicate, iter)


def is_even(num):
    return num%2==0




 Question: What Assert statement does in python?
Answer: The assert statement checks whether the statement is True or False. If the assert statement is True nothing happens but if it is False the statement throws an AssertError.



assert 2+2==4


assert 2+2==5  #error




Question: What are tried and except statements in Python?
Answer: try and except statements are the part of Python exception handling. The try and except statements are similar to if and else statements but the difference is we use to try and except statements for the error handling.

The try block represents the part of code that may contain error or through error during runtime and the except block represent the code what to do if there is an error in the try block. The except block get executed if there is an error in the try block.

#syntax for trying and execute statements

    print('hello world')
    print('2'/3)   #error
    print(“there is an error in the above statement”)


hello world
there is an error in the above statement

Question: Write code to get the current file directory.

import os


Question: Comment on Python Memory management.
Answer: Python interpreter handles memory management. It uses private heaps to control and maintain a memory. In python the user does not get any access related to its memory management, python memory management takes control of all the memory action by itself with the help of Python automatic garbage collector.

Question: What is the difference between shallow and deep copy in Python?


Shallow Copy: The shallow copy creates a new object for the copied object but it does not create a new object for the nested elements.


old = [[1,2,3], [4,5,6], 7]

new = old.copy()   #shallow copy

#the outer layer is copied new
print("Old is New: ",old is new)

#but nested elements are same reference
print("Old 1st element is New 1st element:" ,old[0] is new[0] )


Old is New:  False
Old 1st element is New 1st element: True

Deep Copy: The deep copy creates a new copy object for the outer as well as the nested elements.


import copy

old = [[1,2,3], [4,5,6], 7]

new = copy.deepcopy(old)

#the outer layer is created as new object
print("Old is New: ",old is new)

#nested elements are created as new objects
print("Old 1st element is New 1st element:" ,old[0] is new[0] )


Old is New:  False
Old 1st element is New 1st element: False

Question: How the Python interpreter work?
Answer: The Python interpreter consists of two things one is the compiler and the second is a virtual machine. First, the compiler takes your source code and converts it into the Byte code. Byte code is simply a lower-level code that is platform-independent. Then the byte code is fed into the PVM(Python Virtual Machine). The PVM executes the Byte code and gives the output.

Question: Write all errors that occurred in python.

  • Import error: it occurs when the import statement fails
  • IndexError: when the indexing of any list fails
  • NameError: undefined or unknown variable
  • SyntaxError: when the code is not written properly
  • TypeError: when an unappropriated variable is a call.
  • ValueError: There are many other exceptions or errors in python. There are several exceptions in the third-party libraries.

Question: Explain the .py and .pyc file extension.
Answer: the .py is the file extension of the Python program, and .pyc is the file extension of the compiled byte code file which is generated by python.

Question: What are the module and packages in Python?
Answer: Module: Module is the Python Program file that can be imported to other python Program by using the import keyword

Packages: Packages are the folders which contain a bunch of python module and subfolders. Subfolders also contain modules.

Question: What is a class in Python?
Answer: A class is a blueprint of an object or instance that consists of a set of methods and properties. A class has no existence until its object or instance gets created. In Python to create a class, we use the class keyword followed by the arbitrary class name, and by convention, the class name starts with a capital letter.

Syntax of a class

class Animal:
    def method(self)

Question: What are the methods in Python programming?
Answer: In general methods are the functions that are defined inside a class. Python is an object-oriented programming language and for every data structure there is a defined class in python, that’s why we have many built-in methods for different data structures. But using the class keyword in python we can define our own methods and properties.


class Animal:    def method_1(self):        pass    def method_2(self):        print(“hello world”)

Question: What is an __init__ method?
Answer: __init__() method is a reserved method of a class and it is also known as the constructor of a class. Whenever you initialize an instance of a class the __init__() method of the class automatically get called.


class Animal:
    def __init__(self):
        print(“I am an Animal”)
    def method_1(self):
dog=Animal() #instance of a class


I am an Animal

Question: What is the object of a class?
Answer: An object is an instance of a class and a tool to access the properties and method of the class.


class Human:
    def __init__(self, name): = name

sam = Human("sam") # sam is an object of class Human

joey = Human("joey") # joey is another object of Human class

Question: What self keyword does in python classes?
Answer: self is a conventional variable name that is used as the first argument of every class method and it is used to hold the instance of the object The self represent the object of the class.

Question: What do you understand by inheritance of class in python?
Answer: Inheritance is a way that helps to share the functionality of one class with another class. To perform the inheritance in Pythons we pass the base class name in the parentheses of the drive class.


class Human:
    def __init__(self):
        self.species  ="Homo sapiens"

class Man(Human):
    def __init__(self, name): = name

ram = Man("ram")


Homo sapiens


Question: What are dunders in python?
Answer: Dunders stands for double underscores, and these are the special magic methods used in python which has 2 underscores at the beginning and end of their name. Dunders are generally used for operator overloading in Python.

some e.g. of dunders methods are __init__, __str__, __del__,etc

Question: What error will be shown if you index a key that is not a part of the dictionary?
Answer: KeyError.

Question: What open() and close() functions do in python?

The open() function is used to open a text file for reading, writing and appending purposes. It accepts two parameters the filename which needs to open and the mode of opening the file.

file_object = open(“filename”, mode)

The mode could be r (read), w (write), a(append), and r+(read and write).

The close() method is used to close the file object which is opened using open() method. It is very important to close the file once you are done working with it, the close() method close the file and terminate all the resources used by the file.


Question: How python can be used for web development?
Answer: Python is well known for its web-framework. A web-framework is a tool which is used to create dynamic web application and python has many powerful web frameworks. Django and flask are the two most popular Python frameworks, and Django is the second most stared web-framework on the GitHub.

Question: What is Django?
Answer: Django is one of the most popular Python web frameworks. It can be used to create powerful and robust web-application using Python. It supports Model View Template architecture and uses Object Relational Mapping to perform relational database queries.

Question: What is Flask?

Answer: Flask is a Python micro web-framework and it uses jinja2 for web-templating.  As compared to Django, Flask has fewer libraries dependency which makes it a light weighted web-application.

Question: Give the major difference between Flask, Pyramid, and Django.


Flask is a microframework, and it is generally used for small web-application. And it requires additional libraries to work with.

Pyramid is larger than Flask, that’s why it is used for big web-applications. It allows developers to work with different databases, templates, and URL structure.

Django is a full-stack web framework, and it is generally used for big projects. It comes with many built-in features such as built-in authentication, and an Admin panel. Django can also work with multiple relational databases.

Also Check: Click here for all Django interview questions

Question: Write a python program to save an image locally from the internet which URL is known.


url =""
import urllib.request
urllib.request.urlretrieve(url, "local-image.jpg")

Question: What are virtualenvs in Python?

Answer: The virtualenv stands for the virtual environment, and it is a python package that is used to create an isolated environment for the development, debugging, and execution of a Python program.

It can be installed using the pip command

pip install virtualenv

Python command to create a virtual environment

python -m venv environment_name

Question: What does global keyword do in Python?

Answer: The Python global keyword allows us to use the global scope variable inside a local scope or function. However, we can access the global variable inside any user-defined local scope or function but we cannot rewrite the actual global variable but with the help of global keyword, we can do that.


g_var = 100

def change_global():
    global g_var   #accessing the global variable
    g_var +=200


print("Now the value of  g_var is:", g_var)


Now the value of  g_var is: 300

Question: What does nonlocal keyword do in Python?

Answer: The Python nonlocal keyword working is similar to the global keyword; the difference is the nonlocal keyword is used in the nested function to grab the local variable of the outer function.


def outer_function():
    count =200

    def nested_function():
        nonlocal count  # it will grab the count variable of its outer scope
        count +=100
        return count

    print("The value of count is: ", count)


The value of count is:  300

Question: What are context managers in Python?

Answer: In Python, the context manager is defined using with a keyword. The with keyword provides an elegant and clean way for writing file and exception handling code.

For example in general file handling code we have to first write the open() statement to open the file, then write some code to read and write between the file, and at last we have to mention the close() method to close the file. This complete process is exception prone and many times developers find it hard to code with this syntax. But in Python, we get context managers that provide an alternative way to write file handling code.


with open("file.txt") as file:
    data =

Question: What is CPython?

Answer: CPython is the default implementation of Python Programming language, the Python we installed from the Python official website is CPython. This is known as CPython because it is written in C Programming language.

>>>import platform
>>> platform.python_implementation()

Question: What is Monkey Patching In Python?

Answer: Monkey patching in python also known as Dynamic or runtime modification. According to the monkey-patching in Python, we can modify a class and its module during runtime.


class monkey:
    def func_method(self):
        print("func() method of monkey class")

def func(self):
    print("function method ")

#replace the monkey method with a new function func
monkey.func_method = func

obj = monkey()


function method

Python Coding Interview Questions

Often during the Python interviews, the company also organise the coding test in which they ask coding-related questions to check the coding skill of the candidate. In the Python coding interview, the format of the questions could be anything, you might have to debug a Python code snippet or write a python program to solve a problem or implement some data structures using Python. Here are some of the most frequent Python coding interview questions.

Question: What will be the output of the following code?




Question: What would be the output of this code 


Answer: 5555

Question: What would be the output of the following code



[3, 4, 5]

Question: what would be the output?

for i in range(4):


[2, 4, 6]

Question: what would be the output of the following code?



[[4], [4], [4]]

Question: what would be the output of the following code?

print(Lis1 is Lis2)



Question: What would be the output of the following code?


Answer: None

Question: What would be the output of the following code?




Question: What would be the output of the following code?


if a==b:



Question: Write code to add a delay of 1 min.

import time
def func():
    print("Print after 60 seconds")


Question: What would be the output of the following code?


if id(lis1)==id(lis2):



Question: What would be the output of the following code?



[1, 2, 3]

Question: What would be the output of the following code?


Answer: 3

Question: What would be the output of the following code?

def re():

    return "Hello"





 Question: What would be the output of the following code?

if lis[1]in lis[0]:


Question: What would be the output?


Answer:[1, 2, 3, 1, 2, 3, 1, 2, 3]

Question: Name the type of error for this syntax:

l = "hello world"

Answer: TypeError, you cannot concatenate an integer and string directly, to do so you have to change the type of integer to string first.

Question: Write a Python code to randomize the items of a list.


from random import shuffle
my_list = ["pen", "book", "pencil", "ink", "notebook", "eraser"]

Answer: ['eraser', 'pen', 'ink', 'book', 'pencil', 'notebook']

Question: Write a Python program to delete a file present in the same directory of the python script.

Answer: Using the python os module and .remove method we can delete the file from our system

import os

Question: Implement bubble sort in Python.


arr =[]
num= int(input("How many elements you want to enter in the array: "))
print("Enter the elements in the array")

for i in range(num):
    elements = int(input())

for k in range(len(arr)):
    for i in range(0, num-k-1):
        if arr[i] > arr[i+1]:

for i in range(len(arr)):
    print(arr[i],end=' ')

Question: Write a Python program to create a Fibonacci series.


n = int(input("How many numbers you want to pick from the Fibonacci series: "))
first, second = 0, 1

print("Fibonacci sequence:")
for i in range(n):
    now = first + second
    first = second
    second = now


How many numbers you want to pick from the Fibonacci series: 7
Fibonacci sequence:

Question: Write a Python program to check if a number is Prime.


num = int(input("Enter a Number: "))
if num > 1:
    for i in range(2,(num//2)+1):
        if num%i==0:
            print(num, "is a not prime number")
            break     #this if statement checks if the for loop is completely executed
     if i==num//2:
        print(num, "is a prime number")
    print(num,"is not a prime number" )


Enter a Number:1313 
1313 is a prime number

Question: Write a python program to check if a sequence is a palindrome or not.



string = input("Enter the String: ").lower()
temp = string[::-1]
if string == temp:    
    print(string ," is a palindrome string ")
    print(string, " is not a palindrome")


Enter the String:daddad
daddad is a palindrome string


There are many job roles for a python developer. A python developer could be a web-developer, Data Analyst, Data Scientist, Machine learning, and Artificial Intelligent engineer. All the Python interview questions we have provided here cover mostly all the core python concepts with some advance python libraries. If you are going for a specific Job role and Python is just a tool you are using, then we suggest you read that Job interview questions. For instance, if you have a Django interview, we recommend you first read the Python interview questions and then read Django interview questions. This will help you to refresh your Python as well as Django skills.

If you like this article or have any suggestions regarding Python Interview Questions, please let us know by commenting down below.

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *