KnowledgeBoat Logo
|
OPEN IN APP

Chapter 13

Modules and Packages in Python

Class 10 - KIPS Robotics & AI



Activity 13.2

Question 1

What would be the output of the following code?

import pandas as pd
# Create a DataFrame
data = {'Name':['Jai', 'Ella', 'Mike', 'Pihu'],
        'Age':[25, 28, 30, 22],
        'City':['New York', 'London', 'Paris', 'Sydney']}
df = pd.DataFrame(data)
print(df['Age'] > 29)

Answer

Output
0    False
1    False
2     True
3    False
Name: Age, dtype: bool
Explanation

1. import pandas as pd — The pandas library is imported and renamed as pd.

2. A dictionary named data is created. It contains three keys: Name, Age, and City. Each key has a list of values.

3. df = pd.DataFrame(data) — The DataFrame() function of the Pandas library is used to convert the dictionary into a DataFrame.

4. print(df['Age'] > 29) — The Age column is selected from the DataFrame. Each value in the Age column is compared with 29. The condition returns True if the age is greater than 29, otherwise False.

State True or False

Question 1

A module can be imported and used in another module or script to access its functions and variables.

Answer

True

Reason — A module can be imported and used in another module or script to access its functions and variables using the import statement.

Question 2

Packages are the sub-part of the modules.

Answer

False

Reason — A package is a collection of modules, not a sub-part of a module.

Question 3

A Package is a simple folder that can contain multiple modules.

Answer

True

Reason — A package can be defined as the collection of modules. It contains more than one module.

Question 4

Modules in Python help in code reusability.

Answer

True

Reason — Modules in Python help in code reusability by minimising the development of redundant codes.

Question 5

We cannot give any other name to Python libraries when we import them.

Answer

False

Reason — In Python, we can give another name to a library/module while importing it using the as keyword. This new name is called an alias. An alias is just a short/alternate name used only inside that program to make code easier to write and read (it does not change the actual library name).

Question 6

The Pandas library provides functions for data handling.

Answer

True

Reason — The Pandas library provides functions for data analysis, data handling and data filtering.

Question 7

The Matplotlib library helps in complex mathematical operations.

Answer

False

Reason — The Matplotlib library is used to create static, animated, and interactive visualisations and provides functions for different plots, not for complex mathematical operations.

Select the correct option

Question 1

A package in Python is

  1. a single Python file.
  2. the collection of related modules.
  3. the collection of variables.
  4. None of these

Answer

the collection of related modules.

Reason — A package can be defined as the collection of modules. It contains more than one module.

Question 2

A module in Python is

  1. the collection of Python code in a file.
  2. the collection of variables.
  3. a function.
  4. None of these

Answer

the collection of Python code in a file.

Reason — A module is a simple Python file that can contain functions, variables, and other objects.

Question 3

Which statement is used to include a package or module in a program?

  1. include
  2. import
  3. export
  4. None of these

Answer

import

Reason — The import statement can be used to add a module in a program. We can access the definitions inside it by using the dot operator.

Question 4

The main task of the Matplotlib library is

  1. equation solving
  2. data handling
  3. graph plotting
  4. None of these

Answer

graph plotting

Reason — The Matplotlib library is used to create static, animated, and interactive visualisations and provides many functions for creating various types of plots.

Question 5

Which library includes modules for optimisation, integration, and more?

  1. NumPy
  2. Matplotlib
  3. Pandas
  4. SciPy

Answer

SciPy

Reason — The SciPy library includes modules for optimisation, integration, interpolation, linear algebra, and more.

Fill blanks

Question 1

Fill in the blanks:

  1. ................ and ................ are used to organise Python project.
  2. Pandas is a Python library for ................ .
  3. ................ library supports mathematical operations.

Answer

  1. Packages and modules are used to organise Python project.
  2. Pandas is a Python library for data handling.
  3. NumPy library supports mathematical operations.

Short answer type questions

Question 1

Write a Python program to demonstrate the use of the NumPy library.

Solution
import numpy as np
data = [40, 36, 25, 35, 25, 89]
mean = np.mean(data)
standard_deviation = np.std(data)
print("Mean:", mean)
print("Standard Deviation:", standard_deviation)
Output
Mean: 41.666666666666664
Standard Deviation: 21.891144835805694

Question 2

Write a Python program to demonstrate the use of the SciPy library.

Solution
import numpy as np
from scipy.linalg import solve
coefficients = np.array([[1, 2], [2, 2]])
constants = np.array([1, -1])
solution = solve(coefficients, constants)
X = solution[0]
Y = solution[1]
print("X =", X)
print("Y =", Y)
Output
X = -2.0
Y = 1.5

Question 3

Write a Python program to demonstrate the use of the Pandas library.

Solution
import pandas as pd
data = {
    'Name': ['Jai', 'Anny', 'Akshat', 'Priyanshi'],
    'Roll No': [10, 11, 12, 13],
    'Address': ['New Delhi', 'Mumbai', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
Output
       Name  Roll No      Address
0        Jai       10    New Delhi
1       Anny       11       Mumbai
2     Akshat       12  Los Angeles
3  Priyanshi       13      Chicago

Question 4

Write a Python program to demonstrate the use of the Matplotlib library.

Answer

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Line Plot')
plt.show()

Output

Write a Python program to demonstrate the use of the Matplotlib library. Modules and Packages in Python, KIPS ICSE Robotics & Artificial Intelligence Solutions Class 9.

Long answer type questions

Question 1

How do modules help in code reusability? Explain with the help of an example.

Answer

Modules help in code reusability by allowing a program or part of a program to be used again without rewriting it.

One of the advantages of using modules is:

  • Reusability: It minimises the development of redundant codes.
  • Simplicity: It is simple to reuse a code than to write a program again from the beginning.

When related code such as functions and variables is stored in a module, it can be imported and reused in different programs, which saves time and effort.

Example:

The math module contains predefined mathematical functions and variables. It can be reused in a program as shown below:

import math
print("The value of pi is", math.pi)

Here, the value of pi is reused from the math module instead of writing the code again, which shows how modules help in code reusability.

Question 2

Create a Python package and one module under it. Write Python code to use this package.

Answer

# days.py
def calculate(total_days):
    months = total_days // 30
    remaining_days = total_days % 30
    return months, remaining_days
# calculate.py
from days import calculate

total_days = int(input("Enter the total number of days: "))
months, remaining_days = calculate(total_days)
print("Total number of months:", months)
print("Remaining days:", remaining_days)
Output
Enter the total number of days: 100
Total number of months:  3
Remaining days:  10

Question 3

Explain any four functions of the Matplotlib library.

Answer

The Matplotlib library provides various functions to create and customise plots. Four important functions are explained below:

  1. plot(): This function is used to plot data on a graph. It is used to draw line plots by specifying values for the x-axis and y-axis.

  2. xlabel(): This function is used to assign a label to the x-axis of the graph.

  3. ylabel(): This function is used to assign a label to the y-axis of the graph.

  4. title(): This function is used to assign a title to the graph, which describes what the graph represents.

Question 4

Write a Python program to solve the following linear equations:

2x + y = 5
x + 3y = 8

Solution
import numpy as np
from scipy.linalg import solve
coefficients = np.array([[2, 1], [1, 3]])
constants = np.array([5, 8])
solution = solve(coefficients, constants)
x = solution[0]
y = solution[1]
print("x =", x)
print("y =", y)
Output
x = 1.3999999999999997
y = 2.2

Higher Order Thinking Skills (HOTS)

Question 1

Explore the Matplotlib library for plotting bar charts, line charts and pi charts.

Answer

The Matplotlib library is used to create different types of plots for data visualisation.

Line chart:

A line chart is used to show trends or changes in data over a period of time. The plot() function is used to plot data points and join them with lines.

Bar chart:

A bar chart is used to compare different categories of data. The bar() function is used to represent data using rectangular bars.

Pie chart:

A pie chart is used to represent data in the form of percentages or proportions. The pie() function divides the data into slices to show each part’s contribution to the whole.

Question 2

Explore the Pandas library to read the data that is available in .csv or .xlsx files. Plot the data with the help of Matplotlib.

Answer

The Pandas library is used to read data from .csv files, and the Matplotlib library is used to plot the data.

# data.csv

X,Y
1,2
2,4
3,6
4,8
5,10

Program

import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("data.csv")
plt.plot(data['X'], data['Y'])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Plot using Pandas and Matplotlib')
plt.show()

Output

Explore the Pandas library to read the data that is available in .csv or .xlsx files. Plot the data with the help of Matplotlib. Modules and Packages in Python, KIPS ICSE Robotics & Artificial Intelligence Solutions Class 9.
PrevNext