7.1 Python Recap — Essentials from Class IX
Before diving into Advance Python, quick refresher of the essentials you learnt last year:
# single line comment""" multi-line
comment """int (whole numbers) · float (decimals) · str (text) · bool (True/False)x = 10 · name = "Ravi" · No need to declare type — Python figures it out.+ − * / // % **Comparison:
== != < > <= >=Logical:
and · or · notprint() — displays outputinput() — takes user input (always returns str).if · elif · else — use 4-space indentation.for (fixed times) · while (until condition false). range(start, stop, step) generates sequences.[ ]. Indexing starts at 0. Methods: append · insert · remove · pop · extend · sort · reverse · len.7.2 Jupyter Notebook
🔹 Why Use Jupyter Notebook?
🔹 Installing Jupyter Notebook
Option 1 — Anaconda Distribution (recommended):
- Download Anaconda from anaconda.com/download.
- Install it following the on-screen instructions.
- Open Anaconda Navigator → click Launch under Jupyter Notebook.
Option 2 — Using pip:
# Install Jupyter pip install jupyter # Launch Jupyter Notebook jupyter notebook
🔹 Parts of Jupyter Notebook
| Component | Purpose |
|---|---|
| Code Cell | Write and execute Python code. Press Shift + Enter to run. |
| Markdown Cell | Write formatted text, headings, lists, equations. |
| Kernel | The engine that runs your Python code. Can be restarted. |
| Toolbar | Save · Add cell · Cut/Copy/Paste · Run · Restart Kernel. |
| Menu Bar | File · Edit · View · Insert · Cell · Kernel · Help. |
🔹 Common Keyboard Shortcuts
| Shortcut | Action | Shortcut | Action |
|---|---|---|---|
| Shift + Enter | Run cell + move to next | A | Insert cell above |
| Ctrl + Enter | Run cell, stay put | B | Insert cell below |
| Alt + Enter | Run cell + insert new below | DD | Delete cell (press D twice) |
| M | Change to Markdown | Y | Change to Code |
7.3 Virtual Environments
🔹 Why Virtual Environments?
- Isolation — keep project dependencies separate.
- Version control — Project A can use NumPy 1.20, Project B can use NumPy 1.24 — no conflict.
- Clean global — don't clutter your global Python install.
- Reproducibility — share exact package versions with teammates via
requirements.txt. - Safe experimentation — test new packages without breaking existing projects.
🔹 Creating a Virtual Environment
# Create a virtual environment named 'myenv' python -m venv myenv # Activate it — Windows myenv\Scripts\activate # Activate it — Mac / Linux source myenv/bin/activate # Your prompt will now show (myenv) — indicating activation # Install packages inside this env pip install numpy pandas matplotlib # Save installed packages to a file pip freeze > requirements.txt # Deactivate when done deactivate
🔹 Using Conda Environments (Anaconda)
# Create conda environment conda create -n myenv python=3.11 # Activate conda activate myenv # Install package conda install numpy pandas # List environments conda env list # Deactivate conda deactivate
7.4 Installing Python Packages (pip)
🔹 Common pip Commands
| Command | Purpose |
|---|---|
pip install package_name | Install a package (e.g., pip install numpy) |
pip install package==version | Install a specific version (e.g., numpy==1.24.0) |
pip install --upgrade package | Upgrade to the latest version |
pip uninstall package | Remove a package |
pip list | List all installed packages |
pip freeze | List installed packages with exact versions (for requirements.txt) |
pip install -r requirements.txt | Install all packages from a requirements file |
pip show package | Show details about an installed package |
7.5 Essential Python Libraries for AI
Numerical Python — high-performance arrays and mathematical operations. Foundation of all data science in Python.
Data analysis library — handles CSV, Excel, SQL data in DataFrames. Reading, cleaning, transforming, summarising.
Plotting library — create line charts, scatter plots, bar charts, histograms and more.
Computer Vision library — read, edit, transform images and videos. Face detection, object tracking.
Machine Learning library — classification, regression, clustering ready to use.
Deep-Learning libraries — build and train neural networks and CNNs.
7.6 Suggested Programs — CBSE Practical Examination
The CBSE Class X practical exam requires you to write and execute these 8 programs. Each is covered below with full code and expected output.
📋 Program 1 — Add Elements of Two Lists
Program 1: Add Elements of Two Lists
list1 = [10, 20, 30, 40, 50] list2 = [1, 2, 3, 4, 5] # Add element-wise using list comprehension result = [list1[i] + list2[i] for i in range(len(list1))] print("List 1:", list1) print("List 2:", list2) print("Sum of elements:", result)
Alternative — using NumPy (cleaner):
import numpy as np list1 = np.array([10, 20, 30, 40, 50]) list2 = np.array([1, 2, 3, 4, 5]) result = list1 + list2 print("Sum:", result)
🧮 Program 2 — Mean, Median and Mode using NumPy
Program 2: Calculate Mean, Median and Mode using NumPy
import numpy as np from scipy import stats data = np.array([5, 2, 9, 4, 7, 2, 8, 2, 3]) mean_value = np.mean(data) median_value = np.median(data) mode_value = stats.mode(data, keepdims=True).mode[0] print("Data :", data) print("Mean :", mean_value) print("Median:", median_value) print("Mode :", mode_value)
np.mean() and np.median() — for mode, use scipy.stats.mode() or use Python's built-in statistics.mode() from the statistics module.
📈 Program 3 — Line Chart from (2,5) to (9,10)
Program 3: Display a Line Chart
import matplotlib.pyplot as plt x = [2, 9] y = [5, 10] plt.plot(x, y, marker='o', color='blue', linewidth=2) plt.title("Line Chart from (2,5) to (9,10)") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.grid(True) plt.show()
⚫ Program 4 — Scatter Chart for 5 Points
Program 4: Display Scatter Chart for (2,5), (9,10), (8,3), (5,7), (6,18)
import matplotlib.pyplot as plt x = [2, 9, 8, 5, 6] y = [5, 10, 3, 7, 18] plt.scatter(x, y, color='red', s=100, marker='o') plt.title("Scatter Chart") plt.xlabel("X-axis") plt.ylabel("Y-axis") plt.grid(True) plt.show()
📑 Program 5 — Read CSV and Display 10 Rows
Program 5: Read CSV File and Display First 10 Rows
import pandas as pd # Read CSV file df = pd.read_csv('data.csv') # Display first 10 rows print("First 10 rows of the dataset:") print(df.head(10))
df.head() for first 5 rows, df.tail() for last 5, df.head(n) for first n rows.
ℹ️ Program 6 — Read CSV and Display Info
Program 6: Read CSV File and Display Information
import pandas as pd df = pd.read_csv('data.csv') print("Shape of dataset:", df.shape) print("\nColumn names:", df.columns.tolist()) print("\nData types:") print(df.dtypes) print("\nStatistical summary:") print(df.describe()) print("\nFull info:") df.info()
🖼️ Program 7 — Read and Display an Image
Program 7: Read and Display an Image using Python
import cv2 # Read the image img = cv2.imread('photo.jpg') # Display the image in a window cv2.imshow('My Image', img) # Wait for any key press cv2.waitKey(0) # Close the window cv2.destroyAllWindows()
Alternative — using Matplotlib:
import cv2 import matplotlib.pyplot as plt img = cv2.imread('photo.jpg') # OpenCV reads in BGR, convert to RGB for correct colours img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) plt.imshow(img_rgb) plt.axis('off') plt.show()
📐 Program 8 — Read an Image and Identify its Shape
Program 8: Read an Image and Identify its Shape
import cv2 img = cv2.imread('photo.jpg') print("Shape of image:", img.shape) print("Height (rows) :", img.shape[0]) print("Width (cols) :", img.shape[1]) print("Number of Channels :", img.shape[2]) print("Total pixels :", img.shape[0] * img.shape[1]) print("Image data type :", img.dtype)
- img.shape[0] = Height (number of rows of pixels)
- img.shape[1] = Width (number of columns of pixels)
- img.shape[2] = Channels: 3 for RGB (actually BGR in OpenCV), 1 for grayscale
- img.dtype = data type of pixel values — typically
uint8(0-255)
7.7 Combining Libraries — A Complete Example
Here's how libraries work together in a real AI workflow:
Example: Read CSV → Analyse → Visualise
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 1. Read data (Pandas) df = pd.read_csv('students.csv') print("Dataset Shape:", df.shape) # 2. Calculate statistics (NumPy) avg_marks = np.mean(df['Marks']) print("Average marks:", avg_marks) # 3. Visualise (Matplotlib) plt.bar(df['Name'], df['Marks'], color='skyblue') plt.title("Student Marks") plt.xlabel("Student Name") plt.ylabel("Marks") plt.xticks(rotation=45) plt.tight_layout() plt.show()
7.8 Best Practices for Advance Python
- Always use virtual environments — keep projects isolated.
- Use meaningful names —
student_marksis better thansm. - Comment your code — future you will thank present you.
- Use libraries instead of reinventing — NumPy is 100× faster than a Python loop.
- Handle errors gracefully — use
try / exceptaround file reads. - Save your work frequently in Jupyter.
- Keep a requirements.txt — so others can reproduce your setup.
- Read documentation — NumPy, Pandas, Matplotlib all have excellent docs.
- Practise on real datasets — Kaggle has thousands of free datasets.
7.9 Common Errors & How to Fix
| Error | Cause | Fix |
|---|---|---|
ModuleNotFoundError | Library not installed | pip install <name> |
FileNotFoundError | CSV or image not in current folder | Use full path or check spelling |
IndentationError | Mixed tabs and spaces | Use 4 spaces consistently |
NameError | Variable used before defined | Define variable above its use |
TypeError | Mixing types (string + int) | Convert with str() or int() |
KeyError | DataFrame column doesn't exist | Check column name with df.columns |
IndexError | Accessing list/array out of range | Check with len() first |
Quick Revision — Key Points to Remember
- Jupyter Notebook = web-based tool for interactive Python — code + output + notes in one file (.ipynb). Install via Anaconda or
pip install jupyter. - Jupyter shortcuts: Shift+Enter run, A/B insert above/below, DD delete, M markdown, Y code.
- Virtual Environment = isolated Python env. Create:
python -m venv myenv. Activate on Windows:myenv\Scripts\activate. - pip = Python package installer.
pip install package,pip freeze > requirements.txt. - 6 essential AI libraries: NumPy (arrays) · Pandas (DataFrames) · Matplotlib (charts) · OpenCV (images) · Scikit-learn (ML) · TensorFlow/Keras (DL).
- Program 1 — Add lists: loop or
np.array + np.array. - Program 2 — Mean/Median/Mode:
np.mean(),np.median(),stats.mode(). - Program 3 — Line chart:
plt.plot(x, y)+plt.show(). - Program 4 — Scatter chart:
plt.scatter(x, y). - Program 5 — Read CSV 10 rows:
pd.read_csv('file.csv').head(10). - Program 6 — CSV info:
df.shape,df.columns,df.dtypes,df.describe(),df.info(). - Program 7 — Read & display image:
cv2.imread + cv2.imshow + cv2.waitKey(0) + cv2.destroyAllWindows(). - Program 8 — Image shape:
img.shape→ (Height, Width, Channels). - Shape interpretation: shape[0]=Height, shape[1]=Width, shape[2]=3 for RGB or 1 for Grayscale.
- Common errors: ModuleNotFoundError · FileNotFoundError · IndentationError · TypeError · KeyError · IndexError.