Python Programming Interview Questions
Welcome to the Python Programming Interview Questions! In this article, you will be able to revise both theoretical and coding concepts on topics including functions, numpy, pandas, GUI, regular expressions, etc. Here we are with 30 Python Interview questions covering various Python concepts. Let’s start!!!
Python Programming Interview Questions
1. What are numpy arrays and write a code to multiply two numpy arrays?
Ans. NumPy arrays are the multi dimensional structures containing data of the same data type in the form of rows and columns.
Example of multiplying two numpy arrays:
import numpy as np arr1=np.array([1,2,3,4,5]) arr2=np.array([-1,-2,-3,-4,-5]) arr1*arr2
Output:
2. How do we get the first 3 elements of a data frame? And also write a code to get the last 3 elements from a data frame?
Ans. We can use the head() and tail() methods to get the first and the last few rows of a data frame respectively. These by default give 5 rows. So, to get 3 rows we give 3 inside the brackets.
Example of head() and tail():
import pandas as pd data = [[1,'abc', 10], [2,'pqr', 11], [3,'rtw', 10],[4,'htr',12],[5,'tre',11]] df = pd.DataFrame(data, columns = ['Id','Name', 'Age']) print("First 3 rows:") print(df.head(3)) print("Last 3 rows:") print(df.tail(3))
Output:
First 3 rows: Id Name Age
0 1 abc 10
1 2 pqr 11
2 3 rtw 10
Last 3 rows:
Id Name Age
2 3 rtw 10
3 4 htr 12
4 5 tre 11
3. What advantages do numpy arrays provide over the lists?
Ans. NumPy arrays provide the following advantages over lists:
a. Numpy arrays occupy less memory
b. Their operations are faster
c. They are also convenient to use, especially when we deal with multiple dimensions. And we can also perform some operations like multiplication, etc. easily.
4. Write a code to check if the given two strings are equal or not, ignoring the case?
Ans. Example of comparing two strings:
str1='Python' str2='PYTHON' if(str1.upper()==str2.upper()): print("The strings are equal") else: print("The strings are not equal")
Output:
5. What is recursion? Write a code to find the sum of all the digits of a given number using recursion.
Ans. Recursion is the process where a function calls itself directly or indirectly.
Example of recursion:
def sum_of_digits(n): if(n//10==0): return n return (n%10) + sum_of_digits(n//10) sum_of_digits(12345)
Output:
6. Write a function that takes the first name, optional middle, and last name then prints the complete name.
Ans. Example of function arguments:
def print_name(firstName,lastName,middleName=''): #Here middle name is default argument print(f"Hello {firstName} {middleName} {lastName}") print_name('abc','D')
Output:
7. Name one of the XML processing modules in Python and write the code to get the root of the XML file.
Ans. One of the XML processing Python modules is ElementTree. In this, the data of the file is stored in a tree-like structure and allows conversion to and from XML.
Let the xml file have the following data:
<?xml version=”1.0″?>
<Customer>
<Profile>
<Name>Abc</Name>
<Id>1</Id>
<Mail>[email protected]</Mail>
</Profile>
<Profile>
<Name>Pqr</Name>
<Id>12</Id>
<Mail>[email protected]</Mail>
</Profile>
<Profile>
<Name>Xyz</Name>
<Id>3</Id>
<Mail>[email protected]</Mail>
</Profile>
</Customer>
Example of getting root of XML file:
import xml.etree.ElementTree as ET parser = ET.parse('C:\\Users\\Ch Gayathri Lakshmi\\Downloads\\customer.xml') print(parser.getroot().tag)
Output:
8. Write a code to create a GUI using tkinter that takes a number and returns its cube.
Ans. Example of GUI with entries:
from tkinter import * def cube(): a=int(ent1.get()) output.insert(1.0,str(a**3)) win=Tk() #creating the main window and storing the window object in 'win' win.title('Cube of a Number') #setting the title of the window text=Label(win, text='Enter a numbers in the below field and click Find') ent1 = Entry(win) btn=Button(text='Find',command=cube) output=Text(win,height=1,width=6) text.pack() ent1.pack() output.pack() btn.pack() win.mainloop()
Output:
9. What is the difference between implicit and explicit data type conversion? Give an example for each of them.
Ans. In implicit type conversion, the python interpreter automatically converts the data type into another one without any user involvement.
Example of implicit type conversion:
a=4 b=5.5 print(a,":",type(a)) a=a*b print(a,":",type(a)) #a got converted from int to float
Output:
4 : <class ‘int’>22.0 : <class ‘float’>
Whereas, in explicit type conversion, the data type is changed by the user.
Example of explicit type conversion:
a=4 print(a,":",type(a)) a=float(a) print(a,":",type(a)) #a got converted from int to float
Output:
4.0 : <class ‘float’>
10. Write a code to implement a Log In page using Tkinter that gives a message on logging in.
Ans. Example of GUI with entries:
from tkinter import * import tkinter.messagebox win=Tk() win.geometry('300x300') lab1=Label(win,text='LogIn Page') lab2=Label(win, text='Email') lab3=Label(win, text='Password') ent1 = Entry(win) ent2 = Entry(win) def func():#function of the button tkinter.messagebox.showinfo("LoggedIn","You have logged into PythonGeeks!") btn=Button(win,text="LogIn", width=10,height=2,command=func) lab1.place(x=120,y=50) lab2.place(x=10,y=100) lab3.place(x=10,y=150) ent1.place(x=100,y=100) ent2.place(x=100,y=150) btn.place(x=120,y=250) mainloop()
Output:
11. What is the difference between multithreading and multiprocessing? Are these supported by Python?
Ans. In Multiprocessing, many processes execute simultaneously and thus CPUs are added for increasing computing power. Whereas in Multithreading, multiple threads are created under a single process and they run simultaneously.
The threads run in the same memory space, while the processes have separate memory. Therefore, it is a bit harder to share objects between processes. Since threads use the same memory, data can be shared easily but precautions have to be taken so that two threads will not write at the same time.
12. Write a program to count the number of occurrences of vowels using regular expressions.
Ans. Example of regex:
import re pattern=re.compile('[aeiou]') seq_of_vowels=re.findall(pattern,'abcedf') print(len(seq_of_vowels))
Output:
13. Write a program to substitute the word ‘abc’ with ‘ABD’ in the given paragraph using regular expressions.
Ans. Example of regex:
import re text="""Hello everyone. I am abc. I have a friend called abc. We both love Python programming language and graduated from abc college. To share our knowledge we opened an abc website. Hope you all encourage us! """ print(re.sub('abc','ABD',text))
Output:
We both love Python programming language and graduated from ABD college.
To share our knowledge we opened an ABD website. Hope you all encourage us!
14. Write a code to apply the following operation on matrix A2+3A+6.
Ans. Example of matrices:
import numpy as np A=np.array([[1,2,3],[4,5,6],[7,8,9]]) print('The matrix:') print(A) print('A2+3A+6:') I=np.eye(A.shape[0])#creating an identity matrix of 3x3 print(A*A+3*A+6*I)
Output:
[[1 2 3]
[4 5 6]
[7 8 9]]
A2+3A+6:
[[ 10. 10. 18.]
[ 28. 46. 54.]
[ 70. 88. 114.]]
15. What is docstring in Python? Write a function with a docstring and write code to get the function’s docstring.
Ans. Python docstring is a string in triple quotes that appears right after the definition of a function, method, class, or module describing their functionality. We can use the __doc__ attribute to get the docstring.
Example of docstring:
def sum_of_n(n): """Printing the sum of n natural numbers.""" print((n*n+1)/2) sum_of_n.__doc__
Output:
16. Write a program to do the dot product of two vectors.
Ans. Example of dot product of vector:
import numpy as np arr1 = np.array([1,2,3]) arr2=np.array([-3,-2,-1]) arr1.dot(arr2.T)
Output:
17. Describe different loop control statements in Python.
Ans. There are three loop control statements in Python and these are:
a. break: This statement terminates the loop and passes the control to the next statement after the loop.
b. continue: This statement skips the current iteration when a specific condition is met.
c. pass: This statement does nothing in the iteration of the loops and is also considered a null operation.
18. Write a program to implement bubble sort using Python loops.
Ans. Example of bubble sort:
seq=[1,4,22,6,5,7,23,9,2] n = len(seq) for i in range(n-1): for j in range(0, n-i-1): if seq[j] > seq[j + 1] : seq[j], seq[j + 1] = seq[j + 1], seq[j] print(seq)
Output:
19. Find the integration of a function using the scipy module in Python.
Ans. Example of doing integration:
from scipy import integrate func= lambda x:x**2+2*x+5 integral = integrate.quad(func, 0, 10) print(integral[0])
Output:
20. Explain the map() function in Python with an example.
Ans. The map() function takes a function and an iterable and applies the function to all the elements of an iterable. And then passes the resultant values to a variable (another iterable).
Example of map():
def positive(n): return n>=0 seq=[1,2,-4,5,-3,9,-8] res = map( positive, seq) print(list(res))
Output:
21. Rotate an image using Scipy by 45 degrees in the anticlockwise direction.
Ans. Example of rotating an image:
from scipy import misc,ndimage import matplotlib.pyplot as plt img = misc.face() fig=plt.figure() plt.imshow(img) rotated_img = ndimage.rotate(img, 45) fig=plt.figure() plt.imshow(rotated_img) plt.show()
Output:
22. Write a program to create a table, using MySQL module, with id, name, and age as columns with id as a primary key.
Ans. Example of creating a table:
query="CREATE TABLE tab (id INT(5) PRIMARY KEY, name VARCHAR(255), age INT(10))" my_cursor.execute(query)
23. Write the Python code to read an image and get the red regions of RGB from the image using OpenCV.
Ans. Example of map():
import cv2 pic = cv2.imread("D:/lena.png") grayPic = cv2.cvtColor(pic, cv2.COLOR_BGR2GRAY) cv2.imshow("Grayscale image",grayPic) cv2.waitKey(0) cv2.destroyAllWindows()
Output:
23. What are pickling and name a module provided by Python to pickle and unpickle?
Ans. Pickling is the process of converting the data into a byte stream and storing it in a file. And the reverse process of getting the original data is called unpickling. One of the modules that Python provides to do these operations is called Pickle.
24. Write a code to create a new column in a data frame that contains the values obtained by multiplying the two (cost and discount).
Ans. Example of data frames:
import pandas as pd data = [[1, 5], [2,3], [3,2],[9,5],[2,7]] df = pd.DataFrame(data, columns = ['cl1','cl2']) df['cl3']=df["cl1"]-df["cl2"] print(df)
Output:
0 1 5 -4
1 2 3 -1
2 3 2 1
3 9 5 4
4 2 7 -5
25. What is logging and also mention its different levels in Python?
Ans. Logging is the way of tracking the events going on when we run our program, used for debugging the program. There are five levels of logging and these are;
- Debug
- Info
- Warning
- Error
- Critical
26. Write a code to get alternate numbers from -10 to 10 in reverse order (end values included).
Ans. Example of range():
print(list(range(10,-11,-2))) #start,end,step
Output:
27. What is the PDB module? What is the command used to add a breakpoint to the code using this module?
Ans. The PDB (Python Debugger) module is the standard Python module used for interactive debugging of the code. We can add the breakpoint to any line with line number ‘n’ of the program by writing ‘b n’ or break ‘n’.
28. Write a code to find the number of unique values in a list.
Ans. Example of unique elements of a list:
list1=[1,2,3,1,2,4,5,12] print(list(set(list1)))
Output:
29. Write a code to open a file and print the text in the file.
Ans.
Example of print text in the file:
with open(r'info.txt','r') as f: print(f.read())
Output:
Welcome to PythonGeeks.
Conclusion
We are done with the most frequently asked Python Programming interview questions. Hope you liked going through this article. Happy learning!