Career Development Programming Python

Top 30 Python Interview Questions 2019

Here we bring you some top questions that can be asked during the Python interview. If you are preparing for an interview in 2019-2020, then it is a great chance that you might be get selected if you read all these questions and Answers.

1. What do you mean by python?

Answer:  Python is a general-purpose and high- level programming language that was designed by Guido Van Rossum ( a Dutch programmer known as the best author for python language) in 1991. It has an object-oriented strategy that aims to help the programmers write clear and logical codes for various projects. It is generally used in software development, System Scripting, Mathematics, Web development, etc.

2. What is PEP 8 in Python?

Answer: PEP 8 is described as a document that assists us in providing guidance on how to write the Python code. Guido van Rossum, Barry Warsaw, and Nick Coghlan published it in 2001.

It stands for the Python Enhancement Proposal, and its main task is to improve Python code readability and reliability.

3. Explain Dynamic typed Language?

Answer: We must think about what typing is before we know what a dynamically typed language is. Typing refers to programming language type checking. “1” + 2 would result in a type error in a strongly typed language such as Python, as these languages do not permit “type-coercion” (implicit conversion of data types). On the other hand, a language that is weakly typed, like Javascript, will be simple.

Type verification can be done in two stages

Static– Data types are checked prior to execution.

Dynamic– Data types during execution are tested.

Since Python is an interpreted language, each statement line by line is executed and therefore type-checking is done on the fly during execution. Therefore, Python is a language that is dynamically typed.

4. Explain Scope in Python?

Answer: Every Python object works within a Scope. A scope is a block of code that remains relevant to an object in Python. Namespaces define all objects within a program in a unique way. Such namespaces, however, also have a fixed scope for them to use their objects without any prefix. The following are a few examples of the context generated in Python during code execution:

  • A local Scope is defined as local objects present in the current function
  • A module-level Scope is defined as global objects of current function accessible in the program.
  • A global Scope is defined as the objects that are accessible since the execution of this program.
  • An Outermost scope is defined as the objects that are searched last to find the name referenced. And it includes all the built-in names that are callable in the program

5. What do you mean by [::-1] in python?

Answer: [: -1 ] is used to reverse the array or sequence order.

For instance:

import array as arr

Output: array(‘i’, [5, 4, 3, 2, 1])

6. Define the negative indexes and why are they used?

Answer: The Python sequences are indexed and consist of both positive and negative numbers. The positive numbers include ‘ 0 ‘ which is used as the first index and ‘ 1 ‘ as the second index, and this is how the process goes on.

The negative number index ends with ‘-1‘ being the last index in the sequence and ‘-2’ as the penultimate index and the series carries forward as the positive number.

The negative index is also used to denote the index to be represented in the right order.

7. Differentiate between xrange and range in Python?

Answer: The functionality of xrange() and range() is quite different. both generate an integers string, with the only difference being that range returns a Python array, while xrange() returns an xrange() object.

So, does it make any difference? It definitely does, since xrange() does not produce a static list unlike range(), it generates the value on the go. Typically, this technique is used with an object type generator and known as ‘Yielding’.

In systems where memory is a constraint, yielding is necessary. In such conditions, constructing a static list as in range() can result in a Memory Error, while xrange() can handle it optimally by using just enough generator memory (significantly less compared to the generator).

xrange() can be illustrated with python2 and not with python3.

 Let’s look at an example:

for i in xrange(10):    # numbers from o to 9
    print (i)       # output => 0 1 2 3 4 5 6 7 8 9

for i in xrange(1,10):    # numbers from 1 to 9
    print (i)       # output => 1 2 3 4 5 6 7 8 9

for i in xrange(1, 10, 2):    # skip by two for next
    print (i)       # output => 1 3 5 7 9

8. Define the use of the break statement?

Answer: We will understand this with the help of a flow chart

even = [2,4,6,8,10,11,12,14]  
odd = 0  
for val in even:  
    if val%2!=0:  
        odd = val  
print("Odd value found ",odd)  







Odd value found 11

9. What is the use of Split in python?

Answer: This is used to separate a given string in the python.

For example :

a= “Codersera python”

OUTPUT : [‘Codersera’ , ‘python’]

10. What is Encapsulation?

Answer: Encapsulation means that the code and the data are bound together. A Python class is an example of encapsulation.

11. Define data abstraction?

Answer: Data Abstraction contains only the necessary details and hides the world’s implementation. It can be attained by using interfaces and abstract classes in python too.

12. Explain Python decorator?

Answer: Decorators are very powerful and useful tools in Python that allow programmers to change the behavior of any class or function. It allows us to wrap up another function in order to extend the behavior of the wrapped function without permanently modifying it.

Basically, a decorator takes in a function, adds some functionality and returns it.


def make_pretty(func):
    def inner():
        print("I got decorated")
    return inner

def ordinary():
    print("I am ordinary")

13. Define namespaces in python?

Answer: A Namespace is defined as a system that is used to control the names in a program. This avoids the duplication and leads to the uniqueness of names in a program.

A namespace is a basic idea for structuring and organizing software that is more useful in large projects. However, if you are new to programming, it could be a bit difficult concept to grasp. Therefore, we tried to make namespaces a little easier to understand.

14. Define Slicing in Python?

Answer: Slicing is a method used to pick a range of items such as array, tuple, and string from the sequence type. Using slice way, it’s helpful and simple to get elements from a set. It requires a: (colon) separating the field index start and end.

All the List or tuple forms of data collection allow us to use slicing to collect items. While we can obtain elements by defining an index, we only obtain a single element, whereas we can obtain a collection of elements by slicing.

15. What is PHYTHONPATH?

Answer: PYTHONPATH is a variable environment that can be configured to add additional directories where Python is looking for modules and packages. This is especially useful in keeping Python libraries that you don’t want to download in the default global place.

16. Define docstring in Python?

Answer: Documentation string or docstring is a multiline string that is used to document a particular segment of code.

The docstring must explain the work of method and function.

17. What does len() do?

Answer: ‘len()’ is used to measure the length of a string, an array a list, etc.

For example:


18. Name the built-in types of python?


  • Boolean
  • Built-in function
  • Integers
  • Floating point
  • Strings
  • Complex numbers

19. What do you mean by ‘pass’ in python?

Answer: Pass defines an operation-free Python expression. In a complex phrase, it’s a placeholder. This code allows transferring the control without error if we want to create an empty class or function.

For example:

mutex = True
if (mutex == True) : 
else : 

20. Define the use of help() and dir() function?

Answer: The functions Help() and dir() are accessible from the Python interpreter and are used to view a compiled function dump.

Help() function: The help() function is used to view the documentation string and also helps us to see the file, keyword, and attribute-related support.

Dir() function: to show the specified symbols, the dir() function is used.

21. What do you mean by Iterators in python?

Answer: In python, Iterators, like a list, is used to iterate a set of elements. Iterator is a process of collection of objects, and that can be a list, a tuple, or a dictionary. To iterate the stored elements, Python iterator implements _itr_  and the next() method. We normally use loops in Python to iterate over the collections (list, tuple).

22. How you can create a Unicode string in python?

Answer. In Python 3, the old Unicode type has replaced by “str” type, and the string is treated as Unicode by default. We can make a string in Unicode by using art.title.encode (“utf-8”) function.

23. Define the Functions in python?

Answer: A Function is a block of code that is executed only when it is called. The def keyword is used to define the Python function.

For example

def Newfunc():
print("Hi, Welcome to Codersera”)
Newfunc(); #calling the function

Output: Hi, Welcome to Codersera.

24. Differentiate between pickling and unpickling in python?

Answer: Pickle module accepts and transforms any Python object into a string representation and dumps it into a file using the dump function, this process is called pickling. While the method of retrieving original Python objects from the stored string representation is called unpickling.

25. Define generators?

Answer: Generators are functions that return an iterable array of items.

26. How to Capitalize the first letter of string?

Answer: The capitalize() method in Python capitalizes a string’s first character. If at the end of the string is already a capital letter, then it returns the initial string.

27. Differentiate between python 2.0 and python 3.0?

Answer: Python 2.x is Python’s older version. The new and updated version of Python 3.x. Python 2.x is now heritage. Python 3.x is the language’s present and future.

The Print statement (function) is the most visible difference between Python2 and Python3. It looks like “Hello” in Python 2, and it’s written in Python 3 (“Hello”).

String in Python2 is ASCII implicitly, and in Python3 it is Unicode.

28. What is the output of [‘!!Welcome!!’]*2?

Answer: The output would be [‘!!Welcome!! ‘, ‘!!Welcome!!’]

29. How to write comments in Python?

Answer: Comments start with a # character in Python. Additionally, however, comments are sometimes made using docstrings (strings enclosed in triple quotes).

#Comments in Python start like this
print("Comments in Python start with a #")

Output:  Comments in Python start with a #

30. How will you import modules in Python?

Answer: Modules would be imported with import keyword. Let us look at the coding

import array           #importing using the original module name
import array as arr    # importing using an alias name
from array import *    #imports everything present in the array  module

Read about this also

Backend Developer Cloud Database Python

The complete guide for Python and Django-Part1 Python

Note: In this tutorial, we will be using Python3 instead of Python2. The reason for this choice is that Python2 is slowly getting deprecated from the development world and the developers are developing new libraries strictly for the use with Python3.

Starting with Python3


  1. Installation
  2. DataTypes
  3. Comparison operators
  4. Control flow:
    1. IF ELIF and ELSE statements
    2. WHILE
    3. FOR loop statements
  5. Functions
  6. Object-Oriented Programming
  1. Installations:

Mac installation:

Linux Installation:

Windows Installation:

2. Data Types:


In Python 3, there is effectively no limit to how long an integer value can be. Of course, it is constrained by the amount of memory your system has, as are all things, but beyond that an integer can be as long as you need it to be:

a = 123123123123123123123123123123123123123

Notice that we don’t have to specify the type of the variable ‘a’ in the above code. type of the variable will be dynamically handled by python on the basis of the value being stored in the variable.

Floating Point:

The float type in Python designates a floating-point number. float values are specified with a decimal point. Optionally, the character e or E followed by a positive or negative integer may be appended to specific scientific notation:

print( type(a) )

In the above code, the last line will print ‘float’ , which is the type of variable ‘a’.


We need to import “cmath” to use this data type.

Let us look at the code below and try to understand how it works.

#importing cmath 
import cmath 

#initialising the variable 'z' with the value '2+3i'

#accessing the real part of variable 'z'
print("real part of z is: " + ,end="")

#accessing the imag part of 'z'
print("imaginary part of z is: " + ,end="")


Sets represent the mathematical notion of sets. Sets are mutable, iterable and don’t have any duplicate value. Python provides us, along with ‘set’ datatype, the mathematical functions associated with the sets such as intersection, union, difference, etc.

Let us look at the following code to understand the sets better.

#creating a set 'mySet' with values 1, 2 , and 3
mySet = set([1, 2, 3]) 
# Adding an element to mySet by the function 'add()' 


#creating another set with the name 'anotherSet'
anotherSet = set([3,4,5])

union_of_sets = mySet.union(anotherSet)

#this will print {1, 2, 3, 4 ,5 ,6}

intersection_of_sets = mySet.intersect(anotherSet)

#this will print the set {3}

difference_of_two_sets = mySet.difference(anotherSet)

#this will print {1, 2 , 6}


In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. Dictionary holds a pair of values, one being the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable.

# Creating an empty Dictionary 
Dict = {} 
print("Empty Dictionary: ") 
# Adding elements into the dictionary 
Dict[2] = 'alpha'
Dict[3] = 1

#this will print { 2: 'alpha'  , 3: 1}
# Updating existing Key's Value 
Dict[2] = 'Welcome'

the following line will print { 2: 'welcome'  , 3: 1}
# Adding Nested Key value to Dictionary 
Dict[5] = {'Nested' :{'1' : 'Life', '2' : 'Geeks'}} 
print("\nAdding a Nested Key: ") 


A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.

It can have any number of items and they may be of different types (integer, float, string etc).

# creating a empty list
my_list = []

my_list = [1, 2, 3]

#overwriting the privious list [1 , 2 ,3 ] with the new list [1,"Hello",3.4]
my_list = [1, "Hello", 3.4]

#adding values to the list

#now the new list is [1,"Hello",3.4, 5]
print (my_list)

my_list = ['a','b','c','d','e']

# Output: e

# Output: a

Negative indexing:


A tuple in Python is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas, in a list, elements can be changed. In other words, tuples are immutable.

A tuple is created by placing all the items (elements) inside parentheses(), separated by commas. The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list, string, etc.). Let us look at the following code to understand tuples in a better way:

# Empty tuple
myTuple = ()
print(myTuple)  # Output: ()

# Tuple having integers
myTuple = (1, 2, 3)
print(myTuple)  # Output: (1, 2, 3) 

# tuple with mixed datatypes
myTuple = (1, "Hello", 3.4)
print(myTuple)  # Output: (1, "Hello", 3.4)  

# nested tuple
myTuple = ("mouse", [8, 4, 6], (1, 2, 3))

# Output: ("mouse", [8, 4, 6], (1, 2, 3)) 

A tuple can also be created without using parentheses. This is known as tuple packing. For instance:

my_tuple = "Hello", 1.2, 6
print(my_tuple)   # Output: "hello", 1.2, 6 

Tuple unpacking is also possible

my_tuple = "Hello", 1.2, 6

# unpacking the tuple
a, b, c = my_tuple

print(a)      # 3
print(b)      # 4.6 
print(c)      # dog 


Strings are arrays of bytes representing Unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Slicing in a string:

String1 = "PythonIsFun"

# Printing 3rd to 12th character  using slicing
print("\nSlicing characters from 3-12: ") 
# Printing characters between  
# 3rd and 2nd last character 
print("\nSlicing characters between " +
    "3rd and 2nd last character: ") 


The bool() method is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure.

z=bool(x==y) #this statement will assign False to z as x is not equal to y

print( bool(x)) #this statement will print 'True' as x is true

print( bool(x)) #this statement will print 'False' as x is None

print( bool(x)) #this statement will print 'False' as x is None
#using bool() to find if the number is less than 5 or not
    print('num is less than 5')
    print('num is not less than 5')

3. Comparison Operator/Relational Operators

Comparison operators are used to compare the two values and establish a relationship between them. The expression always evaluates to True or False.

These are the following types of comparison operators used in Python3:

  • == (equal to)
  • != (not equal to)
  • < (less than)
  • > (greater than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

a = 21
b = 10

# '==' operator 
if ( a == b ):
   print ("a is equal to b")
   print ("a is not equal to b")

# '!=' operator
if ( a != b ):
   print ("a is not equal to b")
   print ("a is equal to b")

# '<' operator
if ( a < b ):
   print ("a is less than b" )
   print ("a is not less than b")

# '>' operator
if ( a > b ):
   print ("a is greater than b")
   print ("a is not greater than b")

#swapping of values
a,b = b,a 

# '<=' operator
if ( a <= b ):
   print ("a is either less than or equal to  b")
   print ("a is neither less than nor equal to  b")

# '>=' opeartor
if ( b >= a ):
   print ("b is either greater than  or equal to b")
   print ("b is neither greater than  nor equal to b")

4. Control Flow



if expression:
elif expression:

We can add as many elif as we want in-between if and else block. The count of elif blocks can also be zero. In that case, the else block will immediately follow the if block.

The following code illustrates the use of if elif and else

amount = int(input("Enter amount: "))

if amount<1000:
   discount = amount*0.05
   print ("Discount",discount)
elif amount<5000:
   discount = amount*0.10
   print ("Discount",discount)
   discount = amount*0.15
   print ("Discount",discount)
print ("Net payable:",amount-discount)


Enter amount: 3000
Discount 300.0
Net payable: 2700.0


In Python, while loops are constructed like so:

while [a condition is True]:
    [do something]

The something that is being done will continue to be executed until the condition that is being assessed is no longer true.

Here is the code to illustrate the use of a while loop:

count = 0
while (count < 3):     
    count = count + 1





for iterator_var in sequence:

Let us look at the following code to see understand the for loop better:

s = "HelloWorld"
for i in s : 



Here is another piece of code to traverse the dictionary

print("\nDictionary traversal")    
d = dict()  
d['first'] = 100
d['second'] = 200
for i in d : 
    print("%s  %d" %(i, d[i]))


first  100
second  200

5. Functions

A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

Here is a syntax to declare a function:

def function_name( parameters ):
   #some statements
   return [expression] #the return statement is optional

For example, let us create a simple function which computes the sum of two values which are passed to it (as a parameter). We will name that function ‘sum’.

def sum(x , y):
    return ans

Calling the defined function

We can call the defined function, like the above , as follows:

result = sum(4, 5) # the function 'sum' will return 9 which will be stored in 
                   # the variable 'result'  
print(result)      # this statement will print '9'



6. Object-Oriented Programming / OOP

To understand OOP, we need to understand what is class and object.

Classes are like a blueprint or a prototype that you can define to use to create object.

We define classes by using the class keyword, similar to how we define functions by using the def keyword.

Learn about advantages of python over other leading languages


class Class_name:
    # statements to define data members and methods of this class 

Let us create an empty class ‘Person’ for now.

class Person():

Important terms related to Class:

  • The Constructor Method: This is the method that executes first when we create a new instance of that class. We always have to name this function as ‘__init__‘.
class Person():
    def __init__(self):
        print('This is the constructor method')
  • Self: The argument to the __intit__ () functions is the keyword ‘self‘, which is a reference to objects that are made based on this class. To reference instances (or objects) of the class, self will always be the first parameter, but it need not be the only one.
  • Methods: Method is a special kind of function that is defined within a class. A class can have any number of methods. __init__() is also one of the methods.
  • Attributes: Attributes are data stored inside a class or instance and represent the state or quality of the class or instance. In short, attributes store information about the instance.

Let us add two attributes ‘name’ and ‘age’ to our class ‘Person’. We can do that using the __init__() function. Here is the code:

class Person():
    def __init__(self, name , age):

Now, as the __init__() function is receiving ‘name’ and ‘age’ attribute, it becomes compulsory to pass the name and age while creating the instance /object ‘Person’ object. This is how we can create an object of class Person

#Creating the Person 'p' with the name 'Susan' and age 22
p=Person('Susan' , 22)

As we can notice from the above code, we can access the attributes associated with the object using the . operator.

Let us now add a method to our class ‘Person’ which increments the age of that person by one.

We will call that method ‘IncreaseAge()’.

class Person():
    def __init__(self, name , age):
    def IncrementAge(self ):
        self.age= self.age+1;
p=Person('Susan' , 22)
print('The age before calling the method IncrementAge')

print('The age after calling the method IncrementAge')


The age before calling the method IncrementAge
The age after calling the method IncrementAge

Inheritance in classes

Inheritance is one of the mechanisms to achieve the same. In inheritance, a class (usually called superclass or Base Class) is inherited by another class (usually called subclass or Derived Class). The subclass adds some attributes to a superclass.

Let us understand it by extending our Person class by creating a Student class. A student is also a person with a name and the age but also has some additional properties such as roll number.

So basically, the Student class will inherit the ‘name’ and ‘age’ attribute from its base class which is Person.

This is the code to illustrate the concept of inheritance:

class Person():
    def __init__(self, name , age):
    def IncrementAge(self ):
        self.age= self.age+1;

#the Student class inherits the Person class
class Student(Person):
    def __init__(self,name , age ,RollNo ):
        Person.__init__(self , name , age)
        self.rollNumber= RollNo

print("student's information")

s=Student('Madara' , 10 , 123)


student's information

Notice that, the Student class has acquired the ‘name’ and ‘age’ property from the Person class. The ‘IncrementAge()‘ method can also be used with the Student object.

Part 2 of this article will be published soon.