Python Practical Questions – 1 to 15
Complete solutions covering NumPy, Pandas, Matplotlib and OpenCV, with Python code, sample outputs and explanations.
Practical Notes
This page contains all 15 questions in one document. Open any question to view its complete solution. Use the Copy Code button to copy a program into your Python editor.
Required libraries: NumPy, Pandas, Matplotlib and OpenCV.
pip install numpy pandas matplotlib opencv-pythonImportant: OpenCV programs that use cv2.imshow() need a desktop environment. Keep the sample image flower.jpg in the Python script's working directory for Questions 7, 11, 12 and 13. Keep MelaSales.csv in the working directory for Question 6.
01
Arithmetic operators on a 2D NumPy array
Write a Python program to perform all arithmetic operators on two 2D arrays.
Question
Write a Python program to perform all arithmetic operators on two 2D arrays.
Python Solution
import numpy as np
# Creating two 2D arrays
A = np.array([[10, 20, 30],
[40, 50, 60]])
B = np.array([[2, 4, 5],
[5, 10, 3]])
print("First 2D Array:")
print(A)
print("\nSecond 2D Array:")
print(B)
print("\nAddition:")
print(A + B)
print("\nSubtraction:")
print(A - B)
print("\nMultiplication:")
print(A * B)
print("\nDivision:")
print(A / B)
print("\nModulus:")
print(A % B)
print("\nFloor Division:")
print(A // B)
print("\nExponentiation:")
print(A ** B)Sample Output / Expected Result
Explanation
- `np.array()` creates NumPy arrays.
- The operators `+`, `-`, `*`, `/`, `%`, `//` and `**` perform element-wise addition, subtraction, multiplication, division, modulus, floor division and exponentiation.
- Both arrays have the same shape, so corresponding elements are operated on.
02
Create a DataFrame for interview candidates
Create a DataFrame with Name, Score, Attempts and Qualify columns. Use C001, C002, and so on as row indexes.
Question
Create a DataFrame with Name, Score, Attempts and Qualify columns. Use C001, C002, and so on as row indexes.
Python Solution
import pandas as pd
# Creating a dictionary to store candidate details
data = {
'Name': ['Hardik', 'Rahul', 'Priya', 'Amit', 'Neha'],
'Score': [85, 72, 90, 65, 78],
'Attempts': [1, 2, 1, 3, 2],
'Qualify': ['Yes', 'Yes', 'Yes', 'No', 'Yes']
}
# Creating custom row indexes
index = ['C001', 'C002', 'C003', 'C004', 'C005']
# Creating a DataFrame
df = pd.DataFrame(data, index=index)
print("Interview Candidates DataFrame:")
print(df)Sample Output / Expected Result
Explanation
- A dictionary stores the candidate details as columns.
- The `index` list supplies custom row labels.
- `pd.DataFrame(data, index=index)` converts the dictionary into a DataFrame with the specified indexes.
03
Filter players with more than 1000 runs
Create a DataFrame named player with Team, Matches, Runs and Average. Use player names as row indexes and display players whose runs exceed 1000.
Question
Create a DataFrame named player with Team, Matches, Runs and Average. Use player names as row indexes and display players whose runs exceed 1000.
Python Solution
import pandas as pd
# Creating a dictionary to store player details
data = {
'Team': ['India', 'India', 'Australia', 'England', 'India'],
'Matches': [100, 80, 90, 70, 60],
'Runs': [4500, 3200, 2800, 950, 850],
'Average': [45.0, 40.0, 31.1, 13.5, 14.2]
}
# Assigning player names as row indexes
names = ['Virat', 'Rohit', 'Smith', 'Root', 'Rahul']
# Creating a DataFrame named player
player = pd.DataFrame(data, index=names)
print("Original Player DataFrame:")
print(player)
# Displaying players whose runs are more than 1000
print("\nPlayers with Runs More Than 1000:")
print(player[player['Runs'] > 1000])Sample Output / Expected Result
Explanation
- `player['Runs'] > 1000` creates a Boolean condition.
- Using it inside `player[...]` filters and displays only rows where the Runs value is greater than 1000.
04
Bar chart of mobile game ratings
Represent the ratings of PUBG, FreeFire, MineCraft, GTA-V, Call of Duty and FIFA 22 using a bar chart.
Question
Represent the ratings of PUBG, FreeFire, MineCraft, GTA-V, Call of Duty and FIFA 22 using a bar chart.
Python Solution
import matplotlib.pyplot as plt
games = ['PUBG', 'FreeFire', 'MineCraft',
'GTA-V', 'Call of Duty', 'FIFA 22']
ratings = [4.5, 4.8, 4.7, 4.6, 4.1, 4.3]
plt.bar(games, ratings)
plt.title("Ratings of Mobile Games")
plt.xlabel("Mobile Games")
plt.ylabel("Ratings")
plt.show()Sample Output / Expected Result
Explanation
- `plt.bar()` creates vertical bars.
- `plt.title()`, `plt.xlabel()` and `plt.ylabel()` add the chart title and axis labels.
- `plt.show()` displays the chart.
05
Line chart of average height and weight
Plot weight on the X-axis and height on the Y-axis. Use a green dashed line, star markers of size 10 and line width 2.
Question
Plot weight on the X-axis and height on the Y-axis. Use a green dashed line, star markers of size 10 and line width 2.
Python Solution
import matplotlib.pyplot as plt
height = [121.9, 124.5, 129.5, 134.6, 139.7,
147.3, 152.4, 157.5, 162.6]
weight = [19.7, 21.3, 23.5, 25.9, 28.5,
32.1, 35.7, 39.6, 43.2]
plt.plot(weight, height, color='green',
marker='*', markersize=10,
linestyle='dashed', linewidth=2)
plt.title("Average weight with respect to average height")
plt.xlabel("Weight in kg")
plt.ylabel("Height in cm")
plt.show()Sample Output / Expected Result
Explanation
- `plt.plot(weight, height, ...)` assigns weight to the X-axis and height to the Y-axis.
- `color`, `marker`, `markersize`, `linestyle` and `linewidth` control the line's appearance.
06
Menu-driven Mean, Mode and Median for MelaSales.csv
Smile NGO recorded day-wise sales for three weeks in MelaSales.csv. Read the CSV and calculate the mean, mode and median for each week.
Question
Smile NGO recorded day-wise sales for three weeks in MelaSales.csv. Read the CSV and calculate the mean, mode and median for each week.
Python Solution
import pandas as pd
# Reading data from CSV file
df = pd.read_csv("MelaSales.csv")
while True:
print("\n----- SMILE NGO SALES ANALYSIS -----")
print("1. Calculate Mean")
print("2. Calculate Mode")
print("3. Calculate Median")
print("4. Exit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
print("\nMean of Sales:")
print(df.mean(numeric_only=True))
elif choice == 2:
print("\nMode of Sales:")
for col in df.select_dtypes(include='number').columns:
modes = df[col].mode()
if modes.empty:
print(col, ": No Mode")
elif df[col].value_counts().max() == 1:
print(col, ": No repeated value (no mode)")
else:
print(col, ":", modes.tolist())
elif choice == 3:
print("\nMedian of Sales:")
print(df.median(numeric_only=True))
elif choice == 4:
print("Thank you!")
break
else:
print("Invalid Choice! Please enter 1 to 4.")Sample Output / Expected Result
Explanation
- `pd.read_csv()` loads the CSV file into a DataFrame.
- `mean()` calculates the arithmetic average, `mode()` returns the most frequent value(s), and `median()` returns the middle value after ordering the data.
- The loop repeats until option 4 is selected.
07
OpenCV image loading, colour conversion, inspection, cropping and saving
Load an image, display it, convert its colour representation and grayscale version, inspect its shape and pixel range, crop it and save the results.
Question
Load an image, display it, convert its colour representation and grayscale version, inspect its shape and pixel range, crop it and save the results.
Python Solution
import cv2
# Loading an image
img = cv2.imread("flower.jpg")
if img is None:
print("Image not found!")
else:
# Displaying the original image
cv2.imshow("Original Image", img)
# Converting BGR to RGB
color_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Converting image into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Grayscale Image", gray)
# Printing the shape
print("Shape of Image:", img.shape)
# Displaying maximum and minimum pixel values
print("Maximum Pixel Value:", img.max())
print("Minimum Pixel Value:", img.min())
# Cropping the image (rows 50-199, columns 50-199)
crop = img[50:200, 50:200]
cv2.imshow("Cropped Image", crop)
# Saving the images
cv2.imwrite("gray_image.jpg", gray)
cv2.imwrite("cropped_image.jpg", crop)
print("Images saved successfully!")
cv2.waitKey(0)
cv2.destroyAllWindows()Sample Output / Expected Result
Explanation
- `cv2.imread()` loads the image; `cv2.imshow()` displays it.
- `cv2.cvtColor()` converts BGR to RGB or grayscale.
- `img.shape` gives height, width and channels.
- `img.max()` and `img.min()` return the largest and smallest pixel values.
- NumPy slicing crops the image, and `cv2.imwrite()` saves the output.
08
Histogram chart using Matplotlib
Draw a histogram to show the frequency distribution of students' marks.
Question
Draw a histogram to show the frequency distribution of students' marks.
Python Solution
import matplotlib.pyplot as plt
marks = [45, 56, 67, 78, 89, 90, 55, 65,
75, 85, 95, 40, 50, 60, 70, 80]
plt.hist(marks, bins=5, color='skyblue',
edgecolor='black')
plt.title("Histogram of Students Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()Sample Output / Expected Result
Explanation
- `plt.hist()` creates the histogram.
- `bins=5` divides the range into five intervals.
- `color` sets the bar fill and `edgecolor` sets the bar outline.
09
Pie chart using Matplotlib
Draw a pie chart to represent the values for Python, Java, C++, HTML and SQL.
Question
Draw a pie chart to represent the values for Python, Java, C++, HTML and SQL.
Python Solution
import matplotlib.pyplot as plt
subjects = ['Python', 'Java', 'C++', 'HTML', 'SQL']
marks = [30, 25, 20, 15, 10]
plt.pie(marks, labels=subjects, autopct='%1.1f%%')
plt.title("Students Subject Preference")
plt.show()Sample Output / Expected Result
Explanation
- `plt.pie()` creates the pie chart.
- `labels` supplies category names, and `autopct='%1.1f%%'` prints each sector's percentage to one decimal place.
10
Scatter chart using Matplotlib
Draw a scatter chart showing the relationship between study hours and marks obtained.
Question
Draw a scatter chart showing the relationship between study hours and marks obtained.
Python Solution
import matplotlib.pyplot as plt
hours = [1, 2, 3, 4, 5, 6, 7, 8]
marks = [35, 40, 50, 55, 65, 70, 80, 90]
plt.scatter(hours, marks, color='blue',
marker='o', s=50)
plt.title("Study Hours vs Marks")
plt.xlabel("Study Hours")
plt.ylabel("Marks Obtained")
plt.show()Sample Output / Expected Result
Explanation
- `plt.scatter()` plots individual points.
- `color` sets their colour, `marker='o'` selects circular markers, and `s=50` sets marker size.
11
Read and display original and grayscale images using OpenCV
Read an image using cv2 and display both the original image and its grayscale version.
Question
Read an image using cv2 and display both the original image and its grayscale version.
Python Solution
import cv2
# Reading the original image
img = cv2.imread("flower.jpg")
if img is None:
print("Image not found!")
else:
# Displaying the original image
cv2.imshow("Original Image", img)
# Converting the image into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Displaying the grayscale image
cv2.imshow("Gray Scale Image", gray)
cv2.waitKey(0)
cv2.destroyAllWindows()Sample Output / Expected Result
Explanation
- `cv2.imread()` reads the image.
- `cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)` converts it to grayscale.
- `cv2.waitKey(0)` waits for a key press, and `cv2.destroyAllWindows()` closes the windows.
12
Crop and resize an image using OpenCV
Crop a selected part of an image, resize the original image and save both results.
Question
Crop a selected part of an image, resize the original image and save both results.
Python Solution
import cv2
# Reading the original image
img = cv2.imread("flower.jpg")
if img is None:
print("Image not found!")
else:
cv2.imshow("Original Image", img)
# Cropping the image
crop = img[50:200, 50:200]
cv2.imshow("Cropped Image", crop)
# Resizing the image (width=300, height=300)
resize = cv2.resize(img, (300, 300))
cv2.imshow("Resized Image", resize)
# Saving cropped and resized images
cv2.imwrite("cropped.jpg", crop)
cv2.imwrite("resized.jpg", resize)
cv2.waitKey(0)
cv2.destroyAllWindows()Sample Output / Expected Result
Explanation
- `img[50:200, 50:200]` extracts rows 50–199 and columns 50–199.
- `cv2.resize(img, (300, 300))` changes the image to 300 pixels wide and 300 pixels high.
- `cv2.imwrite()` saves each result.
13
OpenCV image inspection and processing
Load and title an image, convert it to grayscale, print its shape and maximum/minimum pixel values, crop it and save the processed images.
Question
Load and title an image, convert it to grayscale, print its shape and maximum/minimum pixel values, crop it and save the processed images.
Python Solution
import cv2
# Loading an image
img = cv2.imread("flower.jpg")
if img is None:
print("Image not found!")
else:
# Displaying the original image with a title
cv2.imshow("Original Flower Image", img)
# Converting image into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Grayscale Image", gray)
# Printing the shape of the image
print("Shape of Image:", img.shape)
# Displaying maximum and minimum pixel values
print("Maximum Pixel Value:", img.max())
print("Minimum Pixel Value:", img.min())
# Cropping the image
crop = img[50:200, 50:200]
cv2.imshow("Cropped Image", crop)
# Saving the images
cv2.imwrite("gray_image.jpg", gray)
cv2.imwrite("cropped_image.jpg", crop)
print("Images saved successfully!")
cv2.waitKey(0)
cv2.destroyAllWindows()Sample Output / Expected Result
Explanation
- This combines the OpenCV operations: `imread()` loads, `imshow()` displays, `cvtColor()` converts to grayscale, `shape` reports dimensions, `max()` and `min()` inspect pixel intensity, slicing crops, and `imwrite()` saves images.
14
Menu-driven NumPy program
Create a menu-driven program to perform common array operations using NumPy.
Question
Create a menu-driven program to perform common array operations using NumPy.
Python Solution
import numpy as np
# Initializing an empty array
arr = np.array([])
while True:
print("\n========== NUMPY MENU ==========")
print("1. Create an Array")
print("2. Display Array")
print("3. Find Sum of Array")
print("4. Find Mean of Array")
print("5. Find Median of Array")
print("6. Find Maximum and Minimum")
print("7. Sort Array")
print("8. Reverse Array")
print("9. Find Standard Deviation")
print("10. Find Variance")
print("11. Reshape Array")
print("12. Perform Arithmetic Operations")
print("13. Search an Element")
print("14. Count Elements")
print("15. Exit")
choice = int(input("\nEnter your choice: "))
if choice == 1:
n = int(input("Enter number of elements: "))
values = []
for i in range(n):
value = int(input("Enter element: "))
values.append(value)
arr = np.array(values)
print("Array Created Successfully!")
elif choice == 15:
print("Thank You!")
break
elif arr.size == 0:
print("Please create an array first!")
elif choice == 2:
print("Array:", arr)
elif choice == 3:
print("Sum of Array:", np.sum(arr))
elif choice == 4:
print("Mean of Array:", np.mean(arr))
elif choice == 5:
print("Median of Array:", np.median(arr))
elif choice == 6:
print("Maximum Element:", np.max(arr))
print("Minimum Element:", np.min(arr))
elif choice == 7:
print("Sorted Array:", np.sort(arr))
elif choice == 8:
print("Reversed Array:", arr[::-1])
elif choice == 9:
print("Standard Deviation:", np.std(arr))
elif choice == 10:
print("Variance:", np.var(arr))
elif choice == 11:
r = int(input("Enter number of rows: "))
c = int(input("Enter number of columns: "))
if r > 0 and c > 0 and r * c == arr.size:
matrix = arr.reshape(r, c)
print("Reshaped Array:")
print(matrix)
else:
print("Invalid dimensions!")
elif choice == 12:
num = int(input("Enter a number: "))
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
op = int(input("Select operation: "))
if op == 1:
print("Result:", arr + num)
elif op == 2:
print("Result:", arr - num)
elif op == 3:
print("Result:", arr * num)
elif op == 4:
if num != 0:
print("Result:", arr / num)
else:
print("Division by zero is not allowed!")
else:
print("Invalid operation!")
elif choice == 13:
num = int(input("Enter element to search: "))
if num in arr:
print("Element Found!")
print("Position:", np.where(arr == num)[0])
else:
print("Element Not Found!")
elif choice == 14:
print("Total Number of Elements:", np.size(arr))
else:
print("Invalid Choice! Please try again.")Sample Output / Expected Result
Explanation
- The program first creates a NumPy array.
- The menu then allows the user to display it, calculate sum/mean/median, find maximum and minimum, sort or reverse it, calculate standard deviation and variance, reshape it, perform scalar arithmetic, search for an element and count elements.
15
Menu-driven Pandas program
Create a menu-driven program to perform common DataFrame operations using Pandas.
Question
Create a menu-driven program to perform common DataFrame operations using Pandas.
Python Solution
import pandas as pd
# Creating an empty DataFrame
df = pd.DataFrame()
while True:
print("\n========== PANDAS MENU ==========")
print("1. Create a DataFrame")
print("2. Display DataFrame")
print("3. Display First 5 Records")
print("4. Display Last 5 Records")
print("5. Display DataFrame Information")
print("6. Display Statistical Summary")
print("7. Find Maximum and Minimum")
print("8. Calculate Mean")
print("9. Calculate Median")
print("10. Sort DataFrame")
print("11. Add a New Column")
print("12. Delete a Column")
print("13. Search / Filter Records")
print("14. Display Column Names")
print("15. Count Rows and Columns")
print("16. Exit")
choice = int(input("\nEnter your choice: "))
if choice == 1:
n = int(input("Enter number of students: "))
names = []
marks = []
ages = []
for i in range(n):
print("\nEnter details of student", i + 1)
name = input("Enter name: ")
mark = int(input("Enter marks: "))
age = int(input("Enter age: "))
names.append(name)
marks.append(mark)
ages.append(age)
data = {
'Name': names,
'Marks': marks,
'Age': ages
}
df = pd.DataFrame(data)
print("\nDataFrame Created Successfully!")
elif choice == 16:
print("Thank You!")
break
elif df.empty:
print("Please create a DataFrame first!")
elif choice == 2:
print("\nComplete DataFrame:")
print(df)
elif choice == 3:
print("\nFirst 5 Records:")
print(df.head())
elif choice == 4:
print("\nLast 5 Records:")
print(df.tail())
elif choice == 5:
print("\nDataFrame Information:")
df.info()
elif choice == 6:
print("\nStatistical Summary:")
print(df.describe())
elif choice == 7:
print("\nMaximum Values:")
print(df.max(numeric_only=True))
print("\nMinimum Values:")
print(df.min(numeric_only=True))
elif choice == 8:
print("\nMean of Numeric Columns:")
print(df.mean(numeric_only=True))
elif choice == 9:
print("\nMedian of Numeric Columns:")
print(df.median(numeric_only=True))
elif choice == 10:
col = input("Enter column name for sorting: ")
if col in df.columns:
print("\nSorted DataFrame:")
print(df.sort_values(by=col))
else:
print("Column not found!")
elif choice == 11:
col = input("Enter new column name: ")
values = []
for i in range(len(df)):
value = input("Enter value: ")
values.append(value)
df[col] = values
print("New Column Added Successfully!")
print(df)
elif choice == 12:
col = input("Enter column name to delete: ")
if col in df.columns:
df.drop(columns=[col], inplace=True)
print("Column Deleted Successfully!")
print(df)
else:
print("Column not found!")
elif choice == 13:
col = input("Enter column name: ")
if col in df.columns:
value = input("Enter value to search: ")
if pd.api.types.is_numeric_dtype(df[col]):
value = pd.to_numeric(value, errors='coerce')
result = df[df[col] == value]
if not result.empty:
print("\nMatching Records:")
print(result)
else:
print("No matching record found!")
else:
print("Column not found!")
elif choice == 14:
print("\nColumn Names:")
print(df.columns.tolist())
elif choice == 15:
print("\nNumber of Rows:", df.shape[0])
print("Number of Columns:", df.shape[1])
else:
print("Invalid Choice! Please try again.")Sample Output / Expected Result
Explanation
- The menu lets the user create and display a DataFrame, inspect the first or last five rows, view its information and descriptive statistics, calculate maximum/minimum/mean/median, sort rows, add or delete a column, filter records, list column names and count rows and columns.