Python Developer Interview Questions with Answers

Here we are with python developer interview questions and answers. This article includes 30 Python Interview questions with theoretical and coding questions. We will cover some basic topics with interesting examples and some advanced ones like web frameworks, data analyzing operations, plotting, oops, etc. Let’s start!!!

Python Developer Interview Questions

1. What is the difference between Microframeworks and Full-Stack Frameworks?

Ans. Full-stack frameworks are used to build larger and full-featured web applications. They can be used to communicate with databases, template your views, manage queues, and do other background jobs. Whereas microframeworks are generally used to build web applications that include small functionalities. These don’t offer database abstraction layers, form validation, specific tools, and hence these give much more control over the application.

2. Create a data frame with columns id, name, and age. Show the table with the rows arranged in the ascending order of age.

Ans. Example of viewing data frame in a sorted form:

import pandas as pd
data = [[1,'abc', 13], [2,'pqr',12], [3,'trq',15],[4,'ret',12],[5,'iou',14]]
df = pd.DataFrame(data, columns = ['id','name','age'])
print(df.sort_values('age'))

Output:

id name age
1 2 pqr 12
3 4 ret 12
0 1 abc 13
4 5 iou 14
2 3 trq 15

3. Write a program to get the maximum salary of employees in each group.

Ans. Example of applying group by on data frame:

import pandas as pd
data = [[1,'GRP1', 13000], [2,'GRP2',30000], [3,'GRP1',20000],[4,'GRP3',34000],[5,'GRP2',40000],[6,'GRP2',35000],
[7,'GRP1',25000],[5,'GRP3',45000],[5,'GRP2',25000],[5,'GRP3',35000]]
df = pd.DataFrame(data, columns = ['id','group','salary'])
print(df.groupby('group').salary.max())

Output:

group
GRP1 25000
GRP2 40000
GRP3 45000
Name: salary, dtype: int64

4. Write a program to read a table from a csv file, concatenate more rows from another data frame, say df2, and save the new data frame in the csv file.

Ans. Example of applying group by on data frame:

import pandas as pd
df1=pd.read_csv(‘data.csv’)
df= pd.concat([df1, df2], axis=1)
df.to_csv('file.csv')

5. Write a code to get a random element from a given list of values.

Ans. Example of getting random list element:

import random
list1=[1,2,3,4,5,6,7,8,9,10]
ind= random.randint(0, len(list1)-1)
print(list1[ind])

Output:

5

6. Why is Python called a dynamically typed language?

Ans. Python is a dynamically typed language as we do not need to declare any variable as int, str, etc. Instead, Python Interpreter automatically identifies the data type based on the value assigned to the variable.

7. What is the difference between is and ==?

Ans. The operator == is used to compare the values of the operands where as == is used to check if the operands are present in the same memory location.

Example to show difference between == and is:

var1=[]
var2=[]
var3=var1
print('var1==var2:',var1==var2)
print('var1 is var2:',var1 is var2)
print('var1==var3:',var1==var3)
print('var1==var3:',var1 is var2)

Output:

var1==var2: True
var1 is var2: False
var1==var3: True
var1==var3: False

8. How do we append elements of an array to another array without using loops?

Ans. We can use the extend function to append a list to another one.

Example to append arrays:

list1=list(range(5))
list2=list(range(5,10))
list1.extend(list2)
print(list1)

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

9. Write a program to get a pop up message on button click using PyQt.

Ans. Below is the program for the same:

import sys
from PyQt5.QtWidgets import QMainWindow,QApplication,QWidget,QPushButton,QAction,QLineEdit,QMessageBox
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtGui import QIcon

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title='Quit'
        self.left=10
        self.top=10
        self.width=300
        self.height=250
        self.initUI()
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left,self.top,self.width,self.height)
        self.button=QPushButton('Quit',self)
        self.button.move(100,100)
        self.button.clicked.connect(self.click_func)
        self.show()
    def click_func(self):
        QMessageBox.question(self, 'Confirm','Are you sure you want to Quit?', QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
if __name__=='__main__':
    app=QApplication(sys.argv)
    ex=App()
    sys.exit(app.exec_())

Output:

button clicked

10. Write a code that catches exceptions and gives corresponding messages.

Ans. Example to exception handling:

try:
    list1=[1,2,3,4,5]
    print(list1[5])
except Exception as ex:
    print(ex)

Output:

list index out of range

11. What are raise and assert statements in Python?

Ans. A raise statement is used to give a specific exception as an output. For example, raise SyntaxError gives SyntaxError as the output. Whereas the assertion tests the expression, and if the result comes up false, it raises an exception.

12. Write a code to read a particular excel sheet as a data frame.

Ans. Example of exception handling:

import pandas as pd
df = pd.read_excel(r'std.xlsx',sheet_name='Sheet1')

13. What is the difference between loc and iloc?

Ans. Both loc and iloc are used to slice the data frames. The loc() is used to select the columns/rows by passing those names of the row or column to the method.

And the iloc() is based on indexed and the selection is done by passing the integer index of the specific row/column.

14. Write code to get the details of those students, stored in a data frame, whose scores are greater than 80.

Ans. Example of selecting rows:

import pandas as pd
data = [[1,'abc', 78], [2,'pqr',45], [3,'trq',87],[4,'ret',90],[5,'iou',82]]
df = pd.DataFrame(data, columns = ['id','name','score'])
print(df[df['score']>80])

Output:

id name score
2 3 trq 87
3 4 ret 90
4 5 iou 82

15. What is the difference between histograms and bar plots?

Ans. A bar graph is used to compare data among different categories and it represents the values in the form of bars. The length of the bar represents the value and shows the changes over a period of time.

And histograms are the plots used to show a distribution of the values. These are used to show the frequency of values in a given interval in the form of bins.

16. Write any two ways to reverse a list.

Ans. Example to reverse the list:

list1=[1,2,3,4,5]
print(list1[::-1])
print(list1)
list1.reverse()
print(list1)

Output:

[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

17. Write a code to count the letters of a word, by considering a or A=1,b or B=2,…z or Z=26.

Ans. Example to count the string :

string='Python'
n=0
for i in string.lower():
    n=n+ ord(i)-ord('a')+1
print(n)

Output:

98

18. Write code to insert an element in a list at a given index.

Ans. Example to insert an element in the list :

list1=[1,2,3,5]
list1.insert(3,4)
list1

Output:

[1, 2, 3, 4, 5]

19. Write a code to take two integer inputs from a user and find the power of the first to the second number.

Ans. Example of taking integer input :

n1=int(input('Enter n1:'))
n2=int(input('Enter n2:'))

print(n1**n2)

Output:

Enter n1:5
Enter n2:4
625

20. Write a code to print odd factors of a number.

Ans. Example to find odd factors:

n1=30

for i in range(1,n1//2,2):
    if(n1%i==0):
        print(i,end=' ')

Output:

1 3 5

21. What is the use of the vstack() function? Give an example.

Ans. The vstack() function is used to vertically stack the arrays to form a single array.

Example of vstack():

import numpy as np
arr1 = np.array([ 1, 2, 3] )
arr2 = np.array([ -1,-2,-3] )

arr = np.vstack((arr1, arr2))
print (arr)

Output:

[[ 1 2 3]
[-1 -2 -3]]

22. What is pass by reference? Give an example.

Ans. In Python, all parameters are passed by reference. So, any parameter passed to a function, the change is done on the parameter also reflects back outside the function.

Example of pass by reference:

def func(list1):

    list1.pop()
    print("Inside the function, list1:",list1)
    return

list1=[1,2,3]
print("Before calling the function, list1:",list1)
func(list1);
print("After calling the function, list1:",list1)

Output:

Before calling the function, list1: [1, 2, 3]
Inside the function, list1: [1, 2]
After calling the function, list1: [1, 2]

23. What is inheritance and what are different kinds of inheritances?

Ans. Inheritance is the process of passing the attributes and methods of a class to another class. The class inheriting is a child class and the class from which a child class derives is called parent class.

There are four different kinds of inheritance in Python:

1. Single Inheritance: In this, child class derives from one parent class.

2. Multi-level Inheritance: The child class, C1 inherits from the parent class P. The features P and C1 are further inherited into the new class, C2. Here, P is the grandparent of C2.

3. Multiple Inheritance: This is the situation where the child class derives members from more than one parent class.

4. Hierarchical Inheritance: In this, more than one child class derives from a parent class.

24. What is PIP?

Ans. PIP (Python Installer Package) is a command-line tool used to install python modules. It searches for the package over the internet and installs them in the device at the working directory. The syntax to install any module is:

pip install <moduleName>

25. Write a code to count the number of unique letters of a string.

Ans. Example of counting unique characters:

string='abcabdc'
print(len(set(string)))

Output:

4

26. What is a ternary operator? Show an example.

Ans. Ternary operator, also known as conditional expression, is an operator that evaluates a condition and based on it executes a corresponding statement. It is a single line replacing the multiline if-else.

Example of ternary operator:

n1=5
n2=9

max_val = n1 if n1 > n2 else n2
print(max_val)

Output:

9

27. What is a decorator and what is its use?

Ans. A decorator of a function in Python is a function that takes another function as its argument and returns another function. These allow the extension of an existing function, without any modification to the original function. And these also help in dynamically altering the execution behavior of a function.

28. What is the enumerate() function? Give an example.

Ans. Enumerate() method adds a counter to an iterable and returns the enumerated object for that iterable.

Example of enumerate():

list1=['a','b','c','d','e']
seq=list(enumerate(list1))
print(seq)

Output:

[(0, ‘a’), (1, ‘b’), (2, ‘c’), (3, ‘d’), (4, ‘e’)]

29. What is the difference between /,// and % operators?

Ans. The / operator gives a float value obtained by dividing the operands. The // operator gives quotients and % gives reminders.

Example of /,// and %:

n1=7
n2=2

print('n1/n2=',n1/n2)
print('n1//n2=',n1//n2)
print('n1%n2=',n1%n2)

Output:

n1/n2= 3.5
n1//n2= 3
n1%n2= 1

30. What is the difference between abstraction and encapsulation in Python?

Ans.

Abstraction Encapsulation
Abstraction is the concept of hiding unnecessary data with the help of an interface and an abstract class. Encapsulation is the process of hiding the code and the data together to prevent misuse. This is done with the help of getters and setters.
It works on the design level. It works on the application level.
Abstraction shows the work of an object hiding how the object works. Encapsulation focuses on the details of how the object works.
Abstraction focuses on outside viewing, for example, shifting the car. Encapsulation focuses on internal working or inner viewing, for example, the production of the car.

Conclusion

This was all about the python developer interview questions with answers. These are frequently asked in interviews and will help you to crack your next Python Interview. Happy learning!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

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