Python Interview Questions

Harshad Koshti
6 min readMar 31, 2021

==>What are literals in python and explain different types of literals?

Ans: Literals are constants in python

→ String Literals

→ Numeric Literals

→ Boolean Literals

→ Special Literals

==> What is dictionary in python ?

Ans : Dictionary is used to store for key and value.

Example : dict = {‘data’:’value’}

==>What is the Classes and objects in python ?

Ans: Classes: A Class is like an object constructor, or a “blueprint” for creating objects.

Objects: An Object is an instance of a Class.

Example:

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

p1 = Person("John", 36)

print(p1.name)
print(p1.age)
Output :
John
36

==>What do you understand by __init__ method in python ?

Ans: It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class.

Example:

class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
Output:
Area of Rectangle: 19200 sq units
Cost of rectangular field: Rs.38400000

==>What do you mean by Inheritance in python ?

Ans: Inheritance enables us to define a class that takes all the functionality from a parent class and allows us to add more.

class Polygon:
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]

def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self,3)

def findArea(self):
a, b, c = self.sides
# calculate the semi-perimeter
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
t = Triangle()

>>> t.inputSides()
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4

>>> t.dispSides()
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0

>>> t.findArea()
The area of the triangle is 6.00

==> What do you mean by super() keyword in python?

Ans : Super() keyword allows us to access methods of the base class.

class Parent:
def __init__(self, txt):
self.message = txt

def printmessage(self):
print(self.message)

class Child(Parent):
def __init__(self, txt):
super().__init__(txt)

x = Child("Hello, and welcome!")

x.printmessage()
Output:Hello, and welcome!

==> What is mutable and immutable in python?

Ans : Mutable : It can be changed after it is created

Immutable : These are of in-built types like int, float, bool, string, unicode, tuple. In simple words, an immutable object can’t be changed after it is created.

==> What is numpy ?

Ans : Numpy is used to mathematical operation and features for dimensional array and matrics in python.

==> 1 D and 2 D array in python ?

Ans : 1 D array:

import numpy as np
a = np.array([1,2,3])
print(a)

Output: [1,2,3]

2 D array:

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print(a)

Output:

[[1,2,3]

[4,5,6]]

==> How can we add 2 array in python?

Ans :

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.sum((a,b),axis=0))
print(np.sum((a,b),axis=1))

Output:

[5,7,9]

[6,15]

==> Write a program for find the largest number in array.

Ans:

def largest(arr,n):
max = arr[0]
for i in range(1, n):
if arr[i] > max:
max = arr[i]
return max
arr = [10, 324, 45, 90, 9808]
n = len(arr)
Ans = largest(arr,n)
print (“Largest in given array is”,Ans)

Output:

Largest in given array is 9808.

==> How to convert list and dictionary into the dataframe.

Ans:

List: list = [1,2,3,4,5]

df = pd.DataFrame(list)

df

Output:

0
0 1
1 2
2 3
3 4
4 5

Dictionary:

import pandas as pd
dic = {‘fruits’:[‘mango’,’apple’,’orange’],’count’:[10,15,10]}
df = pd.DataFrame(dic)
print(df)

output:

fruits count
0 mango 10
1 apple 15
2 orange 10

==> How would you open and read a file in python?

f = open(“filename”,”r”):

print(f)

==>What is lambda function?

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

==> What is module in python?

Ans: A file containing a set of functions you want to include in your application.

Example:

Save this code in a file named mymodule.py

def greeting(name):
print(“Hello, “ + name)

→ main.py

import mymodule

mymodule.greeting(“Jonathan”)

==>What is shuffle in python?

Ans : The shuffle() method takes a sequence, like a list, and reorganize the order of the items.

Example:

from random import shuffle
x = [‘marry’,’had’,’a’,’little’,’lamp’]
shuffle(x)
print(x)

Output:

[‘had’, ‘lamp’, ‘a’, ‘marry’, ‘little’]

==>How to find length of string using for loop?

Ans:

s = “Helloworld”

c = 0

for i in s:

c=c+1

print(c)

Output: 10

==>Write a program to Replace all the odd number with -1.

import numpy as np
a = np.arange(0,10,1)
a[a%2==1]=-1
print(a)

Output: [ 0 -1 2 -1 4 -1 6 -1 8 -1]

==>How to get common values from two ?

a1 = np.array([1,2,4,6,3,6,7,8,2,9])

a2 = np.array([10,1,5,3,5,9,10,11,12])

np.Intersect1d(a1,a2)

Output:

[1,3,5,9]

==>How do you convert first character into upper case?

import pandas as pd
arr = pd.Series([‘it’,’is’,’the’,’example’,’of’,’python’])
print(arr)
print(arr.map(lambda x: x.title()))

Output:

0 it
1 is
2 the
3 example
4 of
5 python
dtype: object
0 It
1 Is
2 The
3 Example
4 Of
5 Python
dtype: object

==>How do you find the length of character in series?

import pandas as pd
arr = pd.Series([‘it’,’is’,’the’,’example’,’of’,’python’])
print(arr.map(lambda x: len(x)))

Output:

0 2
1 2
2 3
3 7
4 2
5 6
dtype: int64

==> difference between list and array.

Ans:

List:

It is mutuable.

→ Consuming more memory.

→ List is built_in .

→ If we perform any operation on list , it gives error.

→ We can use different data types in list.

Array :

→ It is mutable.

→ Consuming less memory.

→ We must declare numpy library to perform array.

→ If we perform any operation on array, we get output.

→ We can used simillar data types in array.

==> What are the function in python?

Ans: A function is a block of code which is executed only when it is called. To define a python function, the def keyword is used.

Example:

def Newfunc():

print("Hi, Welcome to Example")

Newfunc();

Output: Hi, Welcome to Example

==>What is self in Python?

Ans: Self is an instance or an object of a class.

==>What are python iterators?

Ans: Iterators are objects which can be traversed though or iterated upon.

==>What are the generators in python?

Ans: Functions that return an iterable set of items are called generators.

Example:

def simpleGeneratorFun():

yield 1

yield 2

yield 3

for value in simpleGeneratorFun():

print(value)

Output :

1

2

3

==>What are the decorators in python?

Ans: A decorator takes in a function, adds some functionality and returns it.

Example:

def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return

return func(a, b)
return inner


@smart_divide
def divide(a, b):
print(a/b)
Output:
>>> divide(2,5)
I am going to divide 2 and 5
0.4

>>> divide(2,0)
I am going to divide 2 and 0
Whoops! cannot divide

==>How to remove values to a python array?

Ans: Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not.

Example:

a=arr.array('d', [1.1, 2.2, 3.8, 3.1, 3.7, 1.2, 4.6])

print(a.pop())

print(a.pop(3))

a.remove(1.1)

print(a)

Output:

4.6

3.1

array(‘d’, [2.2, 3.8, 3.7, 1.2])

==> What is thread ?

A thread is a separate flow of execution. This means that your program will have two things happening at once.

==>What is Polymorphism in Python?

Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.

Example:

def add(x, y, z = 0):

return x + y+z

# Driver code

print(add(2, 3))

print(add(2, 3, 4))

==> What is the abstract method in python?

Ans: The method have declaration but not definition it is called as abstract method.

Example:

from abc import ABC,abstractmethod
class computer(ABC):
@abstractmethod
def process(self):
print(“It is computer”)
class Laptop(computer):
def process(self):
print(“It is laptop”)

l = Laptop()
l.process()

Output:

It is laptop

==>Write a program in Python to check if a sequence is a Palindrome.

a=input("enter sequence")

b=a[::-1]

if a==b:

print("palindrome")

else:

print("Not a Palindrome")

Output:

enter sequence 323 palindrome

--

--