close

Informatics Practices Exam Questions to Score High Marks

July 11, 2025 By @mritxperts
Informatics Practices Exam Questions to Score High Marks

Here’s a list of important questions and answers on Python, Pandas, and Matplotlib. Use them to practice for your Class 11 and 12 board exams and get better marks.


How to Use These Questions

For Students 🧑‍🎓

For Teachers 🧑‍🏫

Python Fundamentals

1. What is the difference between a list and a tuple in Python? A list is mutable, meaning you can change its contents (add, remove, or modify elements). A tuple is immutable, meaning once it’s created, you cannot change its elements.


2. What are the key features of Python? Python’s key features include its simple and readable syntax, dynamic typing (no need to declare variable types), being an interpreted language (executed line by line), and having a large standard library.


3. How do you write comments in Python? You use the hash symbol (#) for single-line comments. For multi-line comments, you can enclose the text in triple quotes ("""...""" or '''...''').


4. What are the main data types in Python? The main data types are:


5. How do you open and close a file in Python safely? The best way is to use the with statement, as it automatically handles closing the file even if errors occur.

with open('data.txt', 'r') as file:
    content = file.read()

6. What is the difference between the = and == operators? The = operator is for assignment (e.g., x = 5 assigns the value 5 to x). The == operator is for comparison (e.g., x == 5 checks if the value of x is equal to 5).


7. Explain the break and continue statements in a loop.


8. What is a dictionary in Python? Give an example. A dictionary is an unordered collection that stores data in key-value pairs.

student = {'name': 'Rohan', 'class': 12, 'stream': 'Science'}

9. How do you define a function in Python? You use the def keyword, followed by the function name, parentheses (), and a colon :.

def calculate_sum(a, b):
    return a + b

10. What does the len() function do? The len() function returns the number of items (length) in an object like a string, list, or dictionary.


Pandas

11. What is Pandas used for in Python? Pandas is a library used for data manipulation and analysis. It provides data structures and functions needed to work with structured data seamlessly.


12. What are the two primary data structures in Pandas? The two main data structures are the Series (a 1D labeled array) and the DataFrame (a 2D labeled table with columns of potentially different types).


Test Your Python Code Instantly 🚀

Want to try out the code yourself? Use our free AI-based Python IDLE right in your browser—no installation needed!

Launch Free Python IDLE

13. How do you create a Pandas Series from a Python list?

import pandas as pd
my_list = [10, 20, 30, 40]
my_series = pd.Series(my_list)
print(my_series)

14. How do you create a Pandas DataFrame from a dictionary?

import pandas as pd
data = {'Name': ['Aisha', 'Ben', 'Carla'], 'Marks': [85, 92, 78]}
df = pd.DataFrame(data)
print(df)

15. What is the use of the head() and tail() methods?


16. How do you read a CSV file into a Pandas DataFrame? You use the pd.read_csv() function.

import pandas as pd
df = pd.read_csv('students.csv')

17. How do you select a single column named ‘Marks’ from a DataFrame df? You can use square brackets:

marks_column = df['Marks']

18. How do you select multiple columns, ‘Name’ and ‘Marks’, from a DataFrame df? You pass a list of column names inside the square brackets.

subset_df = df[['Name', 'Marks']]

19. What is the difference between loc and iloc?


20. How would you add a new column named ‘Grade’ to a DataFrame df?

df['Grade'] = ['A', 'A+', 'B']

21. How can you handle missing data in a DataFrame? You can use dropna() to remove rows/columns with missing values or fillna(value) to fill missing values with a specific value.


22. What does the groupby() method do? The groupby() method is used to split the data into groups based on some criteria, apply a function (like sum(), mean()) to each group, and then combine the results.


23. How do you get a summary of statistics for a DataFrame df? Use the describe() method. It provides statistics like count, mean, std, min, and max for numeric columns.

print(df.describe())

24. How do you rename a column from ‘Marks’ to ‘Score’ in a DataFrame df? Use the rename() method.

df = df.rename(columns={'Marks': 'Score'})

25. How do you sort a DataFrame df based on the ‘Marks’ column in descending order? Use the sort_values() method.

df_sorted = df.sort_values(by='Marks', ascending=False)

Matplotlib

26. What is Matplotlib? Matplotlib is a plotting library for Python used to create high-quality static, animated, and interactive visualizations and graphs.


27. What is Pyplot? pyplot is a collection of functions within Matplotlib that provides a simple interface for creating plots, similar to MATLAB. It’s typically imported as plt.


28. How do you create a basic line plot?

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [2, 4, 6, 8]
plt.plot(x, y)
plt.show()

29. How do you create a bar chart?

import matplotlib.pyplot as plt
subjects = ['Physics', 'Chemistry', 'Math']
marks = [88, 91, 95]
plt.bar(subjects, marks)
plt.show()

30. How would you create a histogram for a list of numbers data?

import matplotlib.pyplot as plt
data = [80, 85, 90, 91, 92, 95, 98, 100]
plt.hist(data, bins=5)
plt.show()

31. How do you add a title and labels for the X and Y axes?

plt.title("Student Performance")
plt.xlabel("Subjects")
plt.ylabel("Marks Obtained")

32. How do you create a scatter plot?

import matplotlib.pyplot as plt
study_hours = [2, 3, 5, 1, 6]
exam_scores = [65, 70, 85, 60, 90]
plt.scatter(study_hours, exam_scores)
plt.show()

33. How do you add a legend to a plot? You must add a label to each plot command and then call plt.legend().

plt.plot(x1, y1, label='Class A')
plt.plot(x2, y2, label='Class B')
plt.legend()

34. How do you save a plot to an image file? Use the savefig() function before show().

plt.savefig('my_chart.png')

35. How do you create a pie chart?

import matplotlib.pyplot as plt
labels = ['India', 'China', 'USA']
population = [139, 144, 33]
plt.pie(population, labels=labels, autopct='%1.1f%%')
plt.axis('equal') # Ensures the pie is circular
plt.show()

36. How do you change the color and style of a line in a plot? Pass the color and linestyle arguments to the plot() function.

plt.plot(x, y, color='green', linestyle='--')

37. How can you create multiple plots in one figure? Use the subplot() function. For example, plt.subplot(1, 2, 1) creates a figure with 1 row, 2 columns and sets the first plot as active.


38. What is the purpose of plt.show()? plt.show() displays all the figures you have created. It should typically be called once at the end of your script.


39. How do you set the size of a figure? Use plt.figure(figsize=(width, height)). For example:

plt.figure(figsize=(10, 6)) # 10 inches wide, 6 inches tall

40. How do you create a horizontal bar chart? Use the plt.barh() function instead of plt.bar().

plt.barh(subjects, marks)

Mixed Practice Questions

41. Write code to read a CSV file ‘data.csv’ into a DataFrame and display its first 5 rows.

import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())

42. Given a DataFrame df with a column ‘Price’, create a new column ‘Tax’ that is 18% of the ‘Price’.

df['Tax'] = df['Price'] * 0.18

43. Write the code to create a line plot for the ‘Temperature’ column from a DataFrame df. Add the title “Daily Temperature”.

import matplotlib.pyplot as plt
plt.plot(df['Temperature'])
plt.title("Daily Temperature")
plt.ylabel("Temperature (Celsius)")
plt.show()

44. How do you find the total number of rows and columns in a DataFrame df? Use the shape attribute. It returns a tuple (rows, columns).

print(df.shape)

45. Write code to group a DataFrame df by ‘City’ and find the average ‘Salary’ for each city.

avg_salary_by_city = df.groupby('City')['Salary'].mean()
print(avg_salary_by_city)

46. How do you drop a column named ‘Redundant’ from a DataFrame df?

df.drop('Redundant', axis=1, inplace=True)
# axis=1 specifies column, inplace=True modifies the DataFrame directly

47. Write code to create a bar chart showing the average salary for each city calculated in the previous question.

import matplotlib.pyplot as plt
avg_salary_by_city.plot(kind='bar', color='skyblue')
plt.ylabel('Average Salary')
plt.title('Average Salary by City')
plt.show()

48. How do you select rows from a DataFrame df where the ‘Age’ is greater than 30?

senior_employees = df[df['Age'] > 30]

49. What is the output of the following code?

import pandas as pd
s = pd.Series([10, 20, 30], index=['x', 'y', 'z'])
print(s['y'])

Output:

20

50. Write code to create a scatter plot of ‘StudyHours’ vs ‘Marks’ from a DataFrame df.

import matplotlib.pyplot as plt
plt.scatter(df['StudyHours'], df['Marks'])
plt.xlabel('Hours Studied')
plt.ylabel('Marks Obtained')
plt.title('Study Hours vs. Marks')
plt.show()

51. How do you find and count the number of missing (NaN) values in each column of a DataFrame df?

print(df.isnull().sum())

Output Prediction & Error Finding

1. What will be the output of the following Python code?

my_tuple = (10, 20, 30, 40)
# my_tuple[1] = 25
print(len(my_tuple))

The code will raise a TypeError because tuples are immutable and the line my_tuple[1] = 25 attempts to change an element. If that line were commented out or removed, the output would be 4.


2. Predict the output of the following Pandas code.

import pandas as pd
s1 = pd.Series([1, 2, 3])
s2 = pd.Series([10, 20, 30])
print(s1 + s2)

Output:

0    11
1    22
2    33
dtype: int64

The series are added element-wise based on their integer index.


3. Find the error in the following code to create a DataFrame.

import pandas as pd
data = {'Name': ['Sid', 'Ria', 'Tom'], 'Score': [88, 91]}
df = pd.DataFrame(data)
print(df)

The code will raise a ValueError. The error is that the lists provided for the dictionary values have different lengths (‘Name’ has 3 elements, but ‘Score’ has 2). All arrays must be of the same length.


4. What is the output of the following code?

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['x', 'y', 'z'])
print(df.iloc[1, 1])

Output:

5

iloc[1, 1] accesses the element at the second row (integer position 1) and second column (integer position 1).


5. What is the output of the following?

import pandas as pd
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['x', 'y', 'z'])
print(df.loc['y'])

Output:

A    2
B    5
Name: y, dtype: int64

loc['y'] accesses the row with the label ‘y’ and returns it as a Series.


Data Manipulation with Pandas

6. Given a DataFrame of student scores, how would you select all students who scored more than 80 in ‘Maths’ and more than 85 in ‘Science’?

# Assuming df has 'Maths' and 'Science' columns
top_students = df[(df['Maths'] > 80) & (df['Science'] > 85)]
print(top_students)

7. You have a DataFrame df with a ‘DOB’ column containing dates as strings (e.g., ‘2005-10-25’). How do you convert this column to a proper datetime format? You can use the pd.to_datetime() function.

df['DOB'] = pd.to_datetime(df['DOB'])

8. How can you remove duplicate rows from a DataFrame df based on the ‘Email’ column? Use the drop_duplicates() method.

df.drop_duplicates(subset=['Email'], inplace=True)

9. You have two DataFrames, df1 (with student names and IDs) and df2 (with student IDs and marks). How do you combine them into a single DataFrame based on the student ID? You use the pd.merge() function.

merged_df = pd.merge(df1, df2, on='StudentID')

10. How do you find the number of unique values in the ‘City’ column of a DataFrame df? Use the nunique() method.

num_cities = df['City'].nunique()
print(num_cities)

11. How do you replace all occurrences of _ with a space in the column names of a DataFrame df?

df.columns = df.columns.str.replace('_', ' ')

12. Given a DataFrame df, how do you calculate the correlation between the ‘Age’ and ‘Salary’ columns? You can use the .corr() method.

correlation = df['Age'].corr(df['Salary'])
print(correlation)

Data Visualization with Matplotlib

13. How do you create a bar chart where the bars have different colors? You can pass a list of colors to the color parameter.

import matplotlib.pyplot as plt
products = ['A', 'B', 'C']
sales = [100, 150, 120]
colors = ['red', 'blue', 'green']
plt.bar(products, sales, color=colors)
plt.show()

14. How do you add text annotations to specific data points on a plot?

Use the plt.text() or ax.annotate() functions.

plt.plot(x, y)
# Add text 'Peak' at the coordinate (x_peak, y_peak)
plt.text(x_peak, y_peak, 'Peak')

15. Write the code to create two line plots on the same axes, one for ‘Sales’ and one for ‘Profit’ from a DataFrame df. Add a legend to distinguish them.

import matplotlib.pyplot as plt
plt.plot(df['Month'], df['Sales'], label='Sales', marker='o')
plt.plot(df['Month'], df['Profit'], label='Profit', marker='x')
plt.legend()
plt.show()

16. What is the difference between plt.bar() and plt.hist()?


17. How do you create a stacked bar chart in Matplotlib? You plot the second dataset with the bottom parameter set to the values of the first dataset.

import matplotlib.pyplot as plt
years = ['2021', '2022', '2023']
sales_online = [100, 120, 150]
sales_offline = [80, 90, 85]

plt.bar(years, sales_online, label='Online')
plt.bar(years, sales_offline, bottom=sales_online, label='Offline')
plt.legend()
plt.show()

Case Study / Application Questions

Scenario: A CSV file exam_scores.csv contains data about students with columns: StudentID, Name, Subject, Marks, Attendance_Percentage.

18. Write the code to load this CSV into a DataFrame and display the records of students who have less than 75% attendance.

import pandas as pd
df = pd.read_csv('exam_scores.csv')
low_attendance = df[df['Attendance_Percentage'] < 75]
print(low_attendance)

19. Write the code to calculate and display the average marks for each subject.

avg_marks = df.groupby('Subject')['Marks'].mean()
print(avg_marks)

20. Write the code to create a bar chart visualizing the average marks for each subject calculated in the previous step.

import matplotlib.pyplot as plt
avg_marks.plot(kind='bar')
plt.title('Average Marks per Subject')
plt.ylabel('Average Marks')
plt.xlabel('Subject')
plt.xticks(rotation=0) # Keeps subject names horizontal
plt.show()

21. A student with StudentID ‘S105’ had their ‘Maths’ paper re-evaluated, and their new score is 95. Write the code to update this specific student’s mark in the DataFrame.

df.loc[(df['StudentID'] == 'S105') & (df['Subject'] == 'Maths'), 'Marks'] = 95

22. How would you save the final, modified DataFrame back to a new CSV file named updated_scores.csv without the pandas index column?

df.to_csv('updated_scores.csv', index=False)

23. Create a scatter plot to show the relationship between Attendance_Percentage and Marks.

import matplotlib.pyplot as plt
plt.scatter(df['Attendance_Percentage'], df['Marks'], alpha=0.5)
plt.title('Attendance vs. Marks')
plt.xlabel('Attendance (%)')
plt.ylabel('Marks Obtained')
plt.grid(True)
plt.show()

Test Your Python Code Instantly 🚀

Want to try out the code yourself? Use our free AI-based Python IDLE right in your browser—no installation needed!

Launch Free Python IDLE