Python #6 Packages

CS25C02 · Quick exam study material

Unit 6: Packages

Learn how Python modules and scientific-computing packages help you reuse code, organize programs, analyse data, and solve problems efficiently.

Study each concept, run the examples in the browser, complete the practicals, then plan and test both mini-projects.

6 core topics4 runnable practicals2 guided projects12-question quizMobile friendly
01 · Understand

Study notes

Modules, imports, packages and common data-science tools.

02 · Practise

Run Python

Use browser-based Python; selected labs load packages when needed.

03 · Apply

Build projects

Explore data analysis and a simple machine-learning workflow.

Your learning path

Choose a topic ๐ŸŒŸ

Tap any card to jump to its notes.

Topic 01

Built-in Modules

A module is a Python file containing reusable definitions such as functions, classes and variables. Python ships with a standard library of modules, so common tasks do not need to be programmed from scratch.

  • math provides mathematical functions and constants.
  • random generates pseudo-random values.
  • statistics provides common statistical calculations.
  • datetime handles dates and times; os and sys support operating-system and interpreter tasks.
import math import statistics values = [10, 12, 15, 18] print("Square root of 81:", math.sqrt(81)) print("Mean:", statistics.mean(values)) print("Pi:", round(math.pi, 4))
Remember: import module makes the module available under its name. Use module.member to access its functions or values.

Exam quick notes: A module improves reuse and organization. Standard-library modules are included with Python; third-party packages generally need to be installed in the environment.

Topic 02

User-Defined Modules

A user-defined module is Python code saved in a .py file. Functions and constants can be reused by importing the file into another program.

# file: helpers.py def rectangle_area(length, width): return length * width UNIT = "cm" # file: main.py import helpers print(helpers.rectangle_area(5, 3), helpers.UNIT)
  • Keep related functions together in a clearly named file.
  • Import with import helpers or selected names with from helpers import rectangle_area.
  • Avoid naming your file after a standard module (for example, random.py), because it can shadow the real module.
Browser lab note: the interactive editor runs code in a Python runtime without a normal local project folder. The practical demonstrates a user-defined module using types.ModuleType so it can run in the browser.

Remember: reusable functions, constants and classes can be placed in modules to reduce duplication and make testing easier.

Topic 03

NumPy

NumPy is a third-party package for efficient numerical computing. Its central object is the multidimensional ndarray, which supports vectorized operations and common mathematical tools.

import numpy as np marks = np.array([72, 85, 91, 68]) print("Marks:", marks) print("Mean:", marks.mean()) print("Above 80:", marks[marks > 80]) print("Plus 5:", marks + 5)
  • Create arrays using np.array(), np.zeros() or np.arange().
  • Array operations can apply to every element without writing an explicit loop.
  • Array shapes and data types matter when working with matrices and scientific data.
Exam tip: NumPy arrays are designed for numerical operations and generally store elements of a consistent data type.
Topic 04

SciPy

SciPy builds on NumPy and offers scientific algorithms for tasks such as optimization, integration, statistics, signal processing and linear algebra.

from scipy import integrate, optimize # Approximate integral of x² from 0 to 1 area, error = integrate.quad(lambda x: x*x, 0, 1) print("Integral:", round(area, 4)) # Find a value where x² - 9 = 0 near 2 root = optimize.root_scalar(lambda x: x*x - 9, bracket=[0, 5]) print("Root:", round(root.root, 4))

Use SciPy when: you need a ready-made scientific algorithm rather than implementing it manually. The exact submodule depends on the task, such as scipy.integrate, scipy.optimize or scipy.stats.

Package availability can vary by Python environment. If a SciPy example cannot import in a particular browser runtime, use a local Python environment where SciPy is installed.
Topic 05

Pandas

Pandas is used to work with labelled and tabular data. A Series is one-dimensional; a DataFrame is a two-dimensional table with rows and columns.

import pandas as pd data = {"Student": ["Asha", "Bala", "Chen"], "Mark": [78, 92, 85]} df = pd.DataFrame(data) print(df) print("Average:", df["Mark"].mean()) print("High scorers:") print(df[df["Mark"] >= 85])
  • Select a column with df["Mark"].
  • Filter rows with a condition such as df[df["Mark"] >= 85].
  • Use read_csv() and to_csv() for CSV data when file access is available.
Exam tip: Pandas is especially useful for cleaning, selecting, summarizing and analysing structured datasets.
Topic 06

Scikit-learn

Scikit-learn provides tools for machine learning, including classification, regression, clustering, preprocessing and model evaluation.

# Typical machine-learning workflow from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score # X = feature table; y = target labels # X_train, X_test, y_train, y_test = train_test_split( # X, y, test_size=0.25, random_state=42) # model = DecisionTreeClassifier(random_state=42) # model.fit(X_train, y_train) # predictions = model.predict(X_test) # print(accuracy_score(y_test, predictions))
  • fit() trains a model on examples.
  • predict() produces predictions for new inputs.
  • Keep test data separate from training data to estimate performance fairly.
  • Choose a metric appropriate to the task; accuracy alone may be misleading for imbalanced classes.
The machine-learning workflow above is a template. It needs a feature matrix X and target vector y before it can run. Package installation and memory availability depend on the runtime.
Learn by doing

Practical Python Lab ๐Ÿงช

Four practicals (minimum requested: three).

The first run downloads the Python runtime. Package-based examples may need additional downloads; allow a little time and keep the page open.

Practical 1 · Usage of Built-in and User-Defined Modules
Import standard modules and create a lightweight module in memory.
No extra package
Ready to run
Output will appear here.
Practical 2 · NumPy for Problem Solving
Compute statistics and filter a numerical array.
NumPy
Ready to run
Output will appear here.
Practical 3 · Pandas Data Analysis
Create a DataFrame, summarize values and select rows.
Pandas
Ready to run
Output will appear here.
Practical 4 · SciPy Scientific Calculation
Integrate a simple function and solve for a root.
SciPy
Ready to run
Output will appear here.
Apply your learning

Mini Projects ๐Ÿš€

Minimum two projects included.

Project 1

Student Performance Analyzer

Use NumPy and Pandas to calculate average marks, identify high performers and summarize subject-wise results.

Requirements

  • Represent marks as a table with student names and subject columns.
  • Calculate each student's average and each subject's mean.
  • Filter students whose average is at least 80.
  • Sort students by average in descending order.
  • Write a short conclusion based on the results.

Success criteria: correct calculations, clear tabular output, reusable functions, and readable variable names.

Project 2

Simple Flower Classifier

Explore a supervised machine-learning workflow using Scikit-learn's built-in Iris dataset.

Requirements

  • Load the Iris dataset and inspect its features and target classes.
  • Split data into training and testing sets.
  • Train a simple classifier such as a decision tree or k-nearest neighbors.
  • Predict the test labels and calculate accuracy.
  • Explain why a test set is needed and state one limitation of accuracy.

Success criteria: reproducible split, correct use of fit() and predict(), evaluation, and a brief interpretation.

Project 1 starter · Student Performance Analyzer
Editable runnable starter with NumPy and Pandas.
Project starter
Ready to run
Output will appear here.
Project 2 starter · Iris Classification
A compact Scikit-learn model-training and evaluation workflow.
Project starter
Ready to run
Output will appear here.
Project note: NumPy/Pandas/SciPy/Scikit-learn package downloads depend on the Pyodide build and browser memory. If Scikit-learn cannot load in the browser, run Project 2 in a local Python environment with the package installed.
Check your understanding

Unit 6 Quiz ๐Ÿง 

12 multiple-choice questions.

1. What is a Python module?

2. Which statement imports the math module?

3. Which module is part of Python's standard library?

4. What is NumPy mainly used for?

5. What is the common alias for NumPy?

6. Which package is especially associated with DataFrames?

7. Which expression selects rows where Mark is at least 80 in a DataFrame df?

8. SciPy is commonly used for…

9. What does model.fit(X, y) generally do in Scikit-learn?

10. Why split data into training and testing sets?

11. What is a main benefit of user-defined modules?

12. Which is a valid way to import a function from a module named helpers?

Track your study

Celebrate each step ๐Ÿ†

Topic completion0 / 6
0% complete
Revision checklist

Exam quick notes ๐Ÿ“š

  • Module: reusable Python code, usually in a .py file.
  • Package: a way to organize related modules; third-party packages may need installation.
  • NumPy: numerical arrays, vectorization and array mathematics.
  • SciPy: scientific routines such as integration, optimization and statistics.
  • Pandas: Series and DataFrames for structured data handling and analysis.
  • Scikit-learn: preprocessing, model fitting, prediction and evaluation.
  • Good practice: import only what you need, check package availability, use meaningful names and test results.
For exams, practise writing import statements and explain one practical use case, one key feature and one example for each package.

Comments

Popular posts from this blog

index.html

Python #1 Fundamentals

#Python YT Videos for Jamal Engineering Students