Modules and Packages in Python

ICSE Class 10 Robotics & AI · KIPS Robotics & AI · 24 solved questions

Exercise
1Activity 13.2

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)
Show SolutionHide Solution↓
0    False
1    False
2     True
3    False
Name: Age, dtype: bool

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.

1State True or False

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

Show SolutionHide Solution↓

True

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

2State True or False

Packages are the sub-part of the modules.

Show SolutionHide Solution↓

False

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

3State True or False

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

Show SolutionHide Solution↓

True

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

4State True or False

Modules in Python help in code reusability.

Show SolutionHide Solution↓

True

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

5State True or False

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

Show SolutionHide Solution↓

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).

6State True or False

The Pandas library provides functions for data handling.

Show SolutionHide Solution↓

True

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

7State True or False

The Matplotlib library helps in complex mathematical operations.

Show SolutionHide Solution↓

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.

1Select the correct option

A package in Python is

Show SolutionHide Solution↓

the collection of related modules.

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

2Select the correct option

A module in Python is

Show SolutionHide Solution↓

the collection of Python code in a file.

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

3Select the correct option

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

Show SolutionHide Solution↓

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.

4Select the correct option

The main task of the Matplotlib library is

Show SolutionHide Solution↓

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.

5Select the correct option

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

Show SolutionHide Solution↓

SciPy

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

1Fill blanks

Fill in the blanks:

Show SolutionHide Solution↓
  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.
1Short answer type questions

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

Show SolutionHide 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)
Mean: 41.666666666666664
Standard Deviation: 21.891144835805694
2Short answer type questions

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

Show SolutionHide 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)
X = -2.0
Y = 1.5
3Short answer type questions

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

Show SolutionHide 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)
       Name  Roll No      Address
0        Jai       10    New Delhi
1       Anny       11       Mumbai
2     Akshat       12  Los Angeles
3  Priyanshi       13      Chicago
4Short answer type questions

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

Show SolutionHide Solution↓
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.
1Long answer type questions

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

Show SolutionHide Solution↓

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.

2Long answer type questions

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

Show SolutionHide Solution↓
# 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)
Enter the total number of days: 100
Total number of months:  3
Remaining days:  10
3Long answer type questions

Explain any four functions of the Matplotlib library.

Show SolutionHide Solution↓

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.

4Long answer type questions

Write a Python program to solve the following linear equations:

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

Show SolutionHide 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)
x = 1.3999999999999997
y = 2.2
1Higher Order Thinking Skills (HOTS)

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

Show SolutionHide Solution↓

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.

2Higher Order Thinking Skills (HOTS)

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

Show SolutionHide Solution↓

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.

Press ↓ to reveal a solution and move to the next question. Back to KIPS Robotics & AI.

Free sample bank