python interview question
python interview question
Q4. What are the comments in python? What are the advantages of comments?
Ans:
Comments are used to write the description about the application to understand the
logics easily.
The main objective of comments are the project maintenance will become easy.
The comments are non-executable code.
There are two types of comments in python
Single line comments :
# this is filter logics
Multiline comments: Below two syntax are valid & same.
"""hey ratan sir"""
'''hi durga sir'''
Q5. What is the meaning of Dynamically typed? How to check the type of the data?
Ans: Other languages every variable must declare the data type.
int num1 = 100;
int num2 = 200;
python is dynamically typed language, So no need to declare the data type. At
runtime it will take the type automatically.
num1 = 100
num2 = 200
Ans: 2
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
2 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
Q8. what is the difference between the is,is not & ==,!=?
Ans:
Is, is not : To perform memory comparison.
== != : is comparison of data
d1 = [10,20,30]
d2 = [10,20,30]
print(d1==d2)
print(d1!=d2)
Print(d1 is d2)
Print(d1 is not d2)
Q11. In Application when to use for loop & while loop Give the scenario?
Ans: If we know the number of iteration use for loop.
for x in range(10):
print("hi ratna sir")
If we don’t no how many times to repeat the loop then use while.
while True:
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
logics
if num==25:
break
Q12. What is the Difference between mutable & immutable data?
Ans: mutable data : The data allows modifications.
ex: list, set,dict....
Immutable data : It does not allows modifications.
ex: int, float, str, tuple....etc
Q14. What is the diff between getting the data using index base & slicing?
Ans: data = [10,20,30,40,50]
print(data[0])
print(data[2])
#print(data[9]) IndexError: list index out of range
print(data[2:4])
print(data[:4])
print(data[2:])
print(data[:])
print(data[1:4:2])
print(data[1::2])
print(data[:4:2])
print(data[::2])
data = [10,20,30,40]
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
4 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
a,b,*c = data
print(a,b,c)
*c : will get the data in list format.
names = ["ratan","anu","sravya","naresh"]
names.sort(reverse=True)
print(names)
fruits = ['apple',"mango","banana","orange"]
print(sorted(fruits))
print(fruits)
fruits = ['apple',"mango","banana","orange"]
print(sorted(fruits,reverse=True))
print(fruits)
t1 = ("anu","ratan","anu")
t2 = ("anu","ratan","ani")
print(t1>t2)
print(t1<t2)
t1 = (10,10,"ratan")
t2 = (10,"ratan","anu")
print(t1>t2)
print(t1<t2)
Tuple data :
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
store the multiple elements : (10,20,30) : ordered collection : index base :
immutable data
Q19. What are the ways to remove the data from list?
Ans: a. remove()
b. pop()
c. del
d. clear
fruits = ['mango','banana','apple']
fruits.remove("banana")
#fruits.remove("anu") ValueError: list.remove(x): x not in list
print(fruits)
names = ["ratan","anu","sravya","radha"]
names.pop(2)
names.pop()
#fruits.pop(10) IndexError: pop index out of range
print(names)
Q20: How to get the predefined functions are present in python like
list,tuple,set,dict...etc?
Q21. Define the module in python? What is the Difference between normal import & from
import?
Ans: python file is called module
When we are accessing other module data we have to import that module
There are two ways to import the data,
Normal import :
We have to access the data using module name.
import operations
From import :
we can access the module data directly without module name.
from operations import add,mul
Q23. What is the difference between local import & global import?
Ans: There are two types of import
1. global import : Entire module can access the imported data.
2. local import : Only specific function can access the import data.
#operations.py
add() function
mul() function
#client.py : 1. global import:Entire module can use this import
from operations import add,mul
class Myclass:
def my_func1(self):
add(10,20)
mul(3,4)
def my_func2(self):
add(10,20)
mul(3,4)
if __name__ == "__main__":
c = Myclass()
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
c.my_func1()
c.my_func2()
Q24. What is the class & Object?
Ans:
class vs. object :
a. class is a logical entity it contains logics.
where as object is physical entity it is representing memory.
c. Based on single class it is possible to create multiple objects but every object occupies
memory.
There are three types of methods we can declare inside the class.
1. instance methods : first argument is self : access using obj-name
2. static methods : use @staticmethod qualifier : access using class-
name
3. cls methods : use @classmethod qualifier & cls argumnet: access using object name &
class-name
class MyClass:
def wish(self):
print("Good morning....")
@staticmethod
def disp():
print("hi Students")
@classmethod
def info(cls):
print("Welcome to Durgasoft...")
if __name__ == "__main__":
c = MyClass()
c.wish()
MyClass.disp()
c.info()
MyClass.info()
print(type(10))
print(type(10.5))
print(type("ratan"))
print(type([10,20,30]))
if __name__ == "__main__":
e1 = Emp(111,"ratan",10000.45)
print(e1)
import json
json_data = '{"name": "ratan", "hobbies": ["cricket", "eating"], "id": 111, "email":
null, "status": true}'
py_data = json.loads(json_data)
print(py_data)
class MyClass:
def __init__(self):
print("This is constructor")
def __str__(self):
return "ratan"
def __del__(self):
print("object destroyed...")
if __name__ == "__main__":
c = MyClass()
print(c)
del c
Q32. When to use instance & static variables give the scenario?
Ans:
a. instance variables every object separate memory created.
ex: eid,ename, esal
static varaibles for all object single memory created.
ex: country,company_name,School_name.
b. static variables data common for all objects,if one object change the data then all
objects are reflected.
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
10 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
instance variable is specific to object, here one object change the data only
that object is reflected.
Q33. What are the Different ways to call the parent class Constructors?
Ans: There are two ways to call the parent class constructor.
a. using super()
super().__init__()
b. using class-name
A.__init__(self)
class A:
def __init__(self,num):
print("A class constructor..",num)
class B(A):
def __init__(self):
super().__init__(10)
print("B class constructor")
if __name__ == "__main__":
b = B()
Q34. Define the variable? what are the different types of variables in python?
Ans: Variables used to store the data & it is fixed memory location storing the value.
Variable is a named memory location.
ex : eid = 111
ename = "ratan"
esal= 10000.45
#function call
disp(10,20,30,i=11,j=22,k=33)
b. required arguments
def emp_details(eid,ename,esal):
print(eid,ename,esal)
emp_details(444,"sravya",30000.45)
c. keyword arguments
def emp_details(eid,ename,esal):
print(eid,ename,esal)
#function call
emp_details(eid=111,ename="ratan",esal=10000.45)
d. variable arguments
def disp(*arg):
print(arg)
disp(10,20,30)
Q40. How to add the Set inside the set & dict inside the dict?
Ans: To Add the Set inside the Set use : update() function.
s = {10,20,30}
s.update({1,2,3})
print(s)
To add the Dict inside the Dict use update() function.
d1={1:"ratan",2:"anu"}
d2={3: "ratan",4:"anu"}
d1.update(d2)
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
print(d1)
Q41. How take the list,tuple,set,dict inputs from end user?
Ans: To take the multiple inputs from end-user use eval() Function.
eval() function used to evalute the expressions also.
Q42. Define dict? When we will use dict give the scenario?
Ans: a. dict is a data type to store the group of key=value pairs
the key=value pairs also known as item. The dict contains group of items.
b. declare the data using : {}
{key:value,key:value,key:value}
c. keys must be unique but values can be duplicates.
case 1:
ratan ---- 5 anu ------ 2 is ----- 5
{"ratan":5,"anu":2,"is":5}
case 2:
10.5.6.4 ----- 5
10.5.4.2 ----- 10
78.90.45.4 ----- 5
{"10.5.6.4":5,"10.5.4.2":10,"78.90.45.4":5}
case 3:
e1 ---> 111 ratan 10000.45 e2 ---> 222 anu 20000.45
The references are keys,The object becomes values
t1 = (1,2,3)
t2 = ("aaa","bbb","ccc")
res = dict(zip(t1,t2))
print(res)
data = [4,5,6,22,3,9,8]
res = list(filter(lambda num : num%2==0,data))
print(res)
data = ["ratan","raju","rani","durgasoft","anu"]
res = list(filter(lambda name : name.startswith('r') and len(name)<=4 ,data))
print(res)
marks = [34,56,34,23,67,33]
print(list(map(lambda x : x+2 ,marks)))
names = ("ratan","durga","sravya")
print(list(map(lambda x:x+"good" ,names)))
names = ["ratan","durga","raju"]
res = reduce(lambda x,y:x+y,names)
print(res)
Q48. Define the Exception? What is the main objective of exception handing?
Ans: The dictionary meaning of the exception is abnormal termination.
exception is is a object raised during the execution of the application to disturb
the normal flow of execution is called exception.
try:
n = int(input("Enter a num:"))
print(10/n)
except ZeroDivisionError as e:
print("Exception info....",e)
print("rest of the app....")
Q51. What are the possible ways to handle the multiple exception in python?
Ans:
Below all cases can handle multiple exceptions
except BaseException as a:
except Exception as a:
except (ZeroDivisionError,ValueError) as a:
except (IndexError,KeyError,TypeError) as a:
except: (this is default except can handle all the exceptions)
f = open("ratan.txt","w")
f = open("ratan.txt","r")
To read the data file is mandatory. But to write & append the data file is
optional.
Note : By default the file is open in read mode.
Q56. What are the different ways to read the data from the file?
Ans: There are three ways to read the data from file.
1. using read() : char by char
2. using readline() : reads single line
3. using readlines() : reads all lines in list format.
f = open("ratan.txt",'r')
res = f.read(5)
print(res)
f = open("anu.txt",'r')
res = f.readline()
print(res)
f = open("durga.txt",'r')
res = f.readlines()
print(res)
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
f.close()
Note: The readlines() read the data in list format, so we can apply
indexing & slicing to the get the specefic lines.
2.when we open the file using with statement once the with statement is completed
file is automatically closed.
with open("sample.txt") as f:
data = f.read()
print(data)
print(f.closed) #True
3.when we reassing existing file reference to new file then existing file will be
automatically closed.
f1 = open("sample.txt")
f1 = open("ratan.txt")
here sample.txt file is closed automatically.
if the directory already available, But we are trying to create the new directory
with same name we will get FileExistsError
To delete the directory that directory should be empty.
if the directory contains files we can not delete the directory. So first delete the
files then delete the directory.
import os
os.mkdir("ratan")
os.chdir("ratan")
print(os.getcwd())
os.rmdir("ratan")
print("operatios are completed")
b. instance variable is specific to object, here one object change the data only that
object is reflected. Instance variable modifications reflect on specific object.
Local Variables:
Any variable declared inside a function is known as a local variable. This
variable is present in the local space and not in the global space.
Use a tuple to store a sequence of items with duplicates that will not
change(immutable).
Use a dictionary when you want to associate pairs of two items "key:value".
2. def myEmptyFunc():
pass
myEmptyFunc()
Q66. What are the PEP8 standard we need to fallow while writing the comments?
Ans: Comments PEP-8:
a. Limit the line length of comments and docstrings to 72 characters.
b. Use complete sentences, starting with a capital letter.
c. Make sure to update comments if you change your code.
d. after # give one white space
print("**********")
for x in range(1,11):
if x==5:
continue
print(x)
class Parent:
def eat(self): #Overridden method
print("idly...")
class Child(Parent):
def eat(self): #Overridden method
print("poori...")
if __name__ == "__main__":
c = Child()
c.eat()
Note: Method implementation already present in parent class, Rewriting the parent
method implementation in child class is called overriding.
Normal methods:
Normal methods contains method declaration & implementation.
def disp(self):
print("Good Morning")
abstract methods:
The abstract method contains only method declaration but not
implementation.
To represent your method is a abstarct use @abstractmethod.
@abstractmethod
def disp(self):
pass
print(10 in [10,20,30])
print(100 not in (10,20,30))
print(5 in {10,20,30})
print(111 in {111:"ratan",222:"durga"})
Unit testing means testing different components of software separately.The unit test
is important. Imagine a scenario, you are building software that uses three
components namely A, B, and C. Now, suppose your software breaks at a point time.
How will you find which component was responsible for breaking the software?
Maybe it was component A that failed, which in turn failed component B, and this
actually failed the software. There can be many such combinations.
This is why it is necessary to test each and every component properly so that we know
which component might be highly responsible for the failure of the software.
import unittest
class SimpleTest(unittest.TestCase):
def test(self):
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
Q73. Define abstraction? Difference between normal class & abstract class in python?
Ans:
Abstraction is a process highlighting service details but not implementation details.
There are two types of classes,
1. Normal classes : The class contains only normal methods.
class MyClass:
def m1(self):
print("....")
2. Abstract class : The class contains some abstract methods.
case 1: The class contains at least one abstract method is called abstract class.
class MyClass(ABC):
@abstractmethod
def wish1(self):
pass
case 2: The below abstract class contains zero abstract methods.
class MyClass(ABC):
def m1(self):
print("....")
Note : abstract class may contains abstract methods or may not contains abstract
methods, but for the abstract classes object creations are not possible.
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
26 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
import array
homo = array.array('i', [1, 2, 3])
for i in homo:
print(i)
Declaring Docstrings:
The docstrings are declared using ”’triple single quotes”’ or “””triple
double quotes””” just below the class, method or function declaration.All functions
should have a docstring.
Accessing Docstrings:
The docstrings can be accessed using the __doc__ method of the object
or using the help function.
def my_function():
'''
List is mutable can change
tuple is immutable can not change
set is mutable can change
dict is mutable can change
'''
if __name__ == "__main__":
print("Using __doc__:")
print(my_function.__doc__)
print("Using help:")
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
help(my_function)
Q76. How to print the most common occurred character in string/list/tuple?
Ans: To get the most common data use Counter class in collections module.
from collections import Counter
print(Counter("durgaduu").most_common())
print(Counter("durgaduu").most_common(1))
print(Counter("durgaduu").most_common(2))
print(Counter([10,20,10,10,30,10]).most_common())
print(Counter([3,4,6,7,6,7,4,4,4]).most_common(1))
print(Counter([3,4,6,7,6,7,4,4,4]).most_common(2))
import sys
print(sys.argv)
print(sys.argv[1]+sys.argv[2])
print(int(sys.argv[1])+int(sys.argv[2]))
D:\>python first.py 10 20 30 40
['first.py', '10', '20', '30', '40']
1020
30
import names
for x in range(5):
print(names.get_first_name())
for x in range(5):
print(names.get_last_name())
for x in range(5):
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
28 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
print(names.get_full_name())
Q79. What is the purpose of assertion in python?
Ans: Assertion is used to debug the application.
Assert statements are a convenient way to insert debugging assertions into a
program.
bebug : identifying the error & rectify the error.
logging.basicConfig(filename='log.txt',level=logging.ERROR)
this file contains ERROR & CRITICAL
logging.basicConfig(filename='log.txt',level=logging.INFO)
this file contains ERROR & CRITICAL & WARNING & INFO
private modifier:
To represent private use two underscores(__) at starting :: __num = 10
private is only for variables , functions
private Permission only with in the class even child can not access the parent
private data.
protected modifier:
To represent protected use one underscores :: _num = 10
It is only for variables , functions
with in the package all modules can access + outside pkg also we can access
but only in child classes.
Q84. What are negative indexes and why are they used?
Ans: Negative indexes are the indexes from the end of the list or tuple or string.
data[-1] means the last element of array.
data = [1, 2, 3, 4, 5, 6]
# -6 -5 -4 -3 -2 -1
print(data[-1]) #get the last element
print(data[-2]) #get the second last element
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
30 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
print(data[-4:-1])
print(data[-4:])
print(data[ :-1])
print(data[ : ])
print(data[ : :-1])
name = "ratan"
print(name[ : :-1])
print(string.octdigits)
print(string.hexdigits)
print(statistics.median([1,2,3,8,9]))
print(statistics.median([1,2,3,7,8,9]))
print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6]))
print(statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5]))
for p in itertools.permutations('12'):
print(p)
for p in itertools.permutations('123'):
print(p)
print(list(itertools.combinations([1,2,3],2)))
Q94.What is the purpose of pandas? What Are The Different Types Of Data
Structures In Pandas?
Ans:
Pandas is the most popular python library that is used for data analysis &
manipulate.
Pandas is a high-level data manipulation tool developed by Wes McKinney.
Q95. What is Series in pandas? What are the Different ways create the Series
pandas?
Ans: A series object can contain any type of data.
Series is a one-dimensional array that can hold data values of any type (string,
float, integer, python objects, etc.). It is the simplest type of data structure in Pandas
here, the data’s axis labels are called the index.
Creating Series:
import pandas as pd
DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
35 88 85 25 26 27, 72 07 21 24 27/28 | www.durgasoftonline.com
Maii: durgasoftonline@gmail.com
Python Interview Questions
#Creating Series with predefined index
data = [3,2,5,7,9,3,2]
res = pd.Series(data)
print(res)
#Creating Series with user-defined index
s= pd.Series(["ramu","anu","raju","rani"],['i','ii','iii','iv'])
print(s)
#Creating Series using dict data type.
if we are passing dict to Series
The dict keys becomes indexes, The dict values becomes data series
s = pd.Series({1:"a",2:'b',3:'c',4:'d'})
print(s)
#Combineing two series
s = pd.Series((1,2,3)) + pd.Series([10,20,30])
print(s)
Q96. What is DataFrame in pandas? What are the different ways to create
DataFrame in pandas?
Ans: A DataFrame is a 2-dimensional array in which data is aligned in a tabular
form with rows and columns. With this structure, you can perform an
arithmetic operation on rows and columns.
import pandas as pd
names = ['ratan', 'anu','durga','sravya']
df = pd.DataFrame(names)
print(df)
Q97. How to Append the one data frame to another?How to write the dataframe to
CSV file?
Ans: To add one data frame to another use append() function it is deprecated.
To add one data frame to another use pandas.concat() function.
To write the DataFrame to csv file use to_csv() function.
import pandas as pd
df1 = pd.DataFrame({
"Company Name":["Google", "Microsoft", "SpaceX","Amazon","Samsung"],
"Founders":['Larry Page','Bill Gates','Elon Musk','Jeff Bezos', 'Lee Byungchul'],
"Founded": [1998, 1975, 2002, 1994, 1938],
"Number of Employees": [103459, 144106, 6500647,50320,67145]})
print(df1)
df2 = pd.DataFrame({
'Company Name':['WhatsApp'],
'Founders':['Jan Koum, Brian Acton'],
'Founded': [2009],
'Number of Employees': [5000]}, index=['i'])
result = pd.concat(frames)
print(result)
result.to_csv("company.csv",index=False)
Q98. Define numpy in python? How to convert list to arrays? How to create
Different array using numpy functions?
Ans: NumPy is a python library used for working with arrays.
NumPy was created in 2005 by Travis Oliphant. It is an open source project
and you can use it freely.NumPy stands for Numerical Python.
NumPy arrays are stored at one continuous place in memory unlike lists, so
processes can access and manipulate them very efficiently.
install the numpy using pip command :: pip install numpy
a = np.zeros((2,2)) print(a)
b = np.ones((2,3)) print(b)
c = np.full((2,2), 7) print(c)
d = np.eye(2) print(d)
Q99. what is the purpose of matplotlip? How to create the pie chart?
Ans: matplotlip is python module used plot the the graphs.
Matplotlib is an amazing visualization library in Python for 2D plots of arrays.
Matplotlib is a multi-platform data visualization library built on NumPy arrays
case 2:
import tkinter as tk
window = tk.Tk()
window.title("GUI")
window.geometry("400x200")
tk.Label(window,text="Login Application....").grid(row=0,column=1)
tk.Label(window,text="User Name:").grid(row=1,column=0)
tk.Entry(window).grid(row=1,column=1)
tk.Label(window,text="User Password:").grid(row=2,column=0)
tk.Entry(window,show='*').grid(row=2,column=1)