ADVANCED PYTHON
Complete Exam Preparation Notes
Q&A Format · Theory + Code · All Topics Covered
■ NumPy ■ Pandas ■ Matplotlib
■ Seaborn ■ OOP & Classes ■ MySQL + Python
Paper Pattern
Q1: Compulsory — 20 Marks
Q2–Q7: Attempt Any 4 — 10 Marks Each
Total: 60 Marks
These notes are written in simple, easy-to-understand language with clear definitions, Q&A format, and
practical code examples. Covers every topic from your practicals and syllabus.
SECTION 1 — NumPy (Numerical Python)
What is NumPy?
NumPy (Numerical Python) is a Python library used for working with numbers and arrays. It makes
mathematical calculations fast and easy. Think of it as a powerful calculator that can handle large sets of
numbers at once.
Key Definition: An Array is a collection of numbers stored together in a single variable — like a list, but
much faster for calculations.
Q. How do you import NumPy?
Ans: We import NumPy using the following line at the top of our program:
import numpy as np
Ans: Here, np is a short nickname (alias) for numpy so we don't have to type 'numpy' every time.
Q. What is a 1D Array and how do you create one?
Ans: A 1D array is a simple list of numbers in a single row — like a row in a table.
arr = [Link]([12, 45, 7, 89, 34])
print(arr) # Output: [12 45 7 89 34]
Q. What is a 2D Array (Matrix)?
Ans: A 2D array has rows and columns — like a table or a grid of numbers. It is also called a Matrix.
a = [Link]([[1, 2],
[3, 4]])
print(a)
# Output:
# [[1 2]
# [3 4]]
Q. What are special arrays in NumPy?
Ans: NumPy has built-in functions to create common arrays:
Function What it creates Example
[Link]((3,3)) Array of all 0s 3×3 grid of zeros
[Link]((2,4)) Array of all 1s 2×4 grid of ones
[Link](0,10,2) Numbers in a range [0,2,4,6,8]
[Link](m,s,n) Random numbers (bell curve) [Link](170,10,2
50)
Q. What are the basic statistical operations in NumPy?
Ans: After creating an array, we can find useful statistics with simple commands:
arr = [Link]([12, 45, 7, 89, 34])
print('Maximum:', [Link]()) # 89 — largest number
print('Minimum:', [Link]()) # 7 — smallest number
print('Sum:', [Link]()) # 187 — total of all numbers
print('Average:', [Link]()) # 37.4 — mean value
Q. What is Matrix Addition and Multiplication?
Ans: Matrix Addition adds each matching element together (element-wise). Matrix Multiplication uses
[Link]() and follows the dot-product rule.
a = [Link]([[1,2],[3,4]])
b = [Link]([[5,6],[7,8]])
# Addition (element by element)
print(a + b) # [[6,8],[10,12]]
# Matrix Multiplication (dot product)
print([Link](a, b)) # [[19,22],[43,50]]
■ NOTE: [Link](a,b) = Matrix Multiplication. Using a*b only multiplies element by element — that is NOT matrix
multiplication!
NumPy Quick Reference Table
Function What it does
[Link]() Returns the maximum (largest) value
[Link]() Returns the minimum (smallest) value
[Link]() Returns the total sum of all elements
[Link]() Returns the average (mean) of all elements
[Link] Returns dimensions — e.g. (2,2) means 2 rows, 2 cols
[Link] Returns data type — e.g. int64, float64
[Link](a,b) Matrix multiplication of two 2D arrays
SECTION 2 — Pandas (Data Analysis Library)
What is Pandas?
Pandas is a Python library used to work with data in table form — like an Excel spreadsheet inside Python.
It is used for loading, cleaning, filtering, and analysing structured data. The name comes from 'Panel Data'.
Two Main Data Structures in Pandas:
• Series — A single column of data (1D). Like one column of an Excel sheet.
• DataFrame — A full table with rows and columns (2D). Like a complete Excel sheet.
Q. How do you import Pandas?
import pandas as pd
Ans: 'pd' is the standard short nickname for pandas.
Q. How do you create a Series?
Ans: A Series is created from a simple Python list. Each item gets an automatic index number (0,1,2...).
data = [10, 20, 30, 40]
s = [Link](data)
print(s)
# Output:
# 0 10
# 1 20
# 2 30
# 3 40
Q. How do you create a DataFrame?
Ans: A DataFrame is created from a dictionary where keys become column names and values become
rows.
data = {'Name': ['Aman','Rohit','Neha'],
'Age': [24, 26, 23],
'City': ['Delhi','Mumbai','Pune']}
df = [Link](data)
print(df)
# Output:
# Name Age City
# 0 Aman 24 Delhi
# 1 Rohit 26 Mumbai
# 2 Neha 23 Pune
Q. How do you load data from a CSV file?
Ans: CSV (Comma Separated Values) files contain data in table format. We use pd.read_csv() to load
them.
df = pd.read_csv('/content/HR_Analytics.csv')
[Link](10) # Shows first 10 rows
[Link](5) # Shows last 5 rows
Q. What are the 6 most important Pandas commands for data exploration?
Ans: These 6 commands are called the 'Big 6' — always run them when you get a new dataset:
Command What it shows Example Output
[Link]() Column names, data types, non-null count 38 columns, 1480 entries
[Link]() Statistics: mean, min, max, std deviation Numeric summary
[Link]().sum() Count of missing (empty) values per YearsWithCurrManager:
column 57
[Link] Number of rows × columns (1480, 38)
df['Col'].unique() All unique/distinct values in a column ['R&D;','Sales','HR']
df['Col'].nunique() Count of unique values 3
Q. How do you select data from a DataFrame?
# Single column
print(df['Name'])
# Multiple columns
print(df[['Name', 'Age']])
# First row
print([Link][0])
# Filter rows where Age > 30
print(df[df['Age'] > 30])
Q. What did you find in the HR Analytics Dataset?
Ans: Key findings from analysing the HR_Analytics.csv file:
• Total employees: 1,480 rows, Total columns: 38
• Only YearsWithCurrManager had missing values — 57 null values out of 1480
• All other 37 columns had zero missing values
• 3 Departments: Research & Development, Sales, Human Resources
• 5 Age Groups: 18-25, 26-35, 36-45, 46-55, 55+
Q. How do you handle missing values (null values)?
Ans: Best practice: fill missing values with the mean (average) of that column.
# Fill missing values with the mean of that column
df['YearsWithCurrManager'].fillna(
df['YearsWithCurrManager'].mean(), inplace=True
)
■ NOTE: Always run [Link]().sum() FIRST before starting any analysis to check for missing data!
NumPy vs Pandas — Comparison Table
Feature NumPy Pandas
Data Structure Array (ndarray) Series & DataFrame
Type of Data Numerical data only Structured (table-like) data
Example Data [1, 2, 3, 4] Name, Age, Salary table
Code Example import numpy as np a = import pandas as pd df =
[Link]([1,2,3]) [Link]({'A':[1,2,3]})
Operation a + 2 → [3,4,5] df['A'] + 2 → column updated
Speed Faster Slightly slower
Labels No row/column labels Has row & column labels
Use Case Math, calculations Data analysis, Excel/CSV
SECTION 3 — Matplotlib (Data Visualisation Library)
What is Matplotlib?
Matplotlib is Python's main library for creating charts and graphs. It can draw line plots, bar charts, pie
charts, histograms, and more. It helps us see patterns in data visually instead of just reading numbers.
Q. How do you import Matplotlib?
import [Link] as plt
Ans: 'plt' is the standard short nickname. pyplot is the module inside matplotlib that we use for plotting.
Q. What is the basic structure for making any Matplotlib chart?
Ans: Every Matplotlib chart follows the same 4-step structure:
# Step 1: Prepare your data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 30, 25]
# Step 2: Create the plot
[Link](x, y)
# Step 3: Add labels and title
[Link]('X-axis Label')
[Link]('Y-axis Label')
[Link]('My Chart Title')
# Step 4: Show the chart
[Link]()
Q. What are all the chart types in Matplotlib? When do we use each one?
Chart Type Function When to Use
Line Plot [Link](x, y) Show trends over time
Scatter Plot [Link](x, y) Show relationship between two variables
Bar Chart (V) [Link](x, y) Compare categories
Bar Chart (H) [Link](x, y) Horizontal category comparison
Histogram [Link](data, bins=5) Show distribution / frequency
Pie Chart [Link](values, labels=labels) Show parts of a whole (percentages)
Stack Plot [Link](x, y1, y2, y3) Show cumulative data over time
Q. How do you create a Histogram? Explain with code.
Ans: A Histogram shows how frequently values fall in different ranges (called 'bins'). It is used to
understand the distribution of data — for example, student marks.
marks = [45,55,60,62,65,70,72,75,78,80,82,85,88,90,92]
[Link](marks, bins=5, color='skyblue', edgecolor='black')
[Link]('Distribution of Student Marks')
[Link]('Marks Scored')
[Link]('Number of Students')
[Link](axis='y', linestyle='--', alpha=0.7)
[Link]()
Ans: bins=5 divides the marks range into 5 equal groups. alpha=0.7 makes grid lines semi-transparent.
edgecolor='black' adds a border around each bar.
Q. How do you create a Pie Chart with a highlighted slice? Explain explode.
Ans: A Pie Chart shows percentages of a whole. The explode parameter pulls one slice outward to
highlight it. autopct displays percentage values on the chart.
data = {'Rent':40,'Food':25,'Transport':10,'Entertainment':15,'Savings':10}
labels = list([Link]())
values = list([Link]())
# Pull out the largest slice automatically
max_value = max(values) # 40 = Rent
explode = [0.1 if v == max_value else 0 for v in values]
# Result: [0.1, 0, 0, 0, 0] — only Rent is pulled out
[Link](values, labels=labels, autopct='%1.1f%%',
explode=explode, startangle=140, shadow=True)
[Link]('Monthly Expenses Breakdown')
[Link]('equal') # IMPORTANT! Makes pie a circle, not oval
[Link]()
■ NOTE: Always add [Link]('equal') for pie charts. Without it, the pie becomes oval/egg-shaped!
Q. How do you create a Grouped Bar Chart (like BMW vs Audi)?
Ans: In a grouped bar chart, we place two sets of bars side-by-side by shifting their X positions slightly.
# BMW bars start at 0.25, Audi bars start at 0.75 (offset by 0.5)
[Link]([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20], label='BMW', color='0.5',
width=0.5)
[Link]([0.75,1.75,2.75,3.75,4.75],[80,20,20,50,60], label='Audi', color='r',
width=0.5)
[Link]()
[Link]('Days')
[Link]('Distance (kms)')
[Link]('BMW vs Audi Distance Comparison')
[Link]()
Q. How do you create a Stack Plot?
Ans: A Stack Plot stacks multiple data series on top of each other to show how each part contributes to the
total over time.
days = [1, 2, 3, 4, 5]
sleeping= [7, 8, 6,11, 7]
eating = [2, 3, 4, 2, 3]
working = [7, 8, 7, 2, 7]
playing = [8, 5, 8, 7,13]
[Link](days, sleeping, eating, working, playing, colors=['m','c','r','k'])
[Link]('Day')
[Link]('Hours')
[Link]('Daily Activity Stack Plot')
[Link](['Sleeping','Eating','Working','Playing'], loc='upper left')
[Link]()
Q. What are the important Matplotlib customisation options?
Parameter Purpose Example Values
color Colour of the chart element 'red', '#ff9999', '0.5' (grey)
marker Shape of data points 'x', 'o', 's' (square), '^'
linestyle Style of line '--', '-', ':', '-.'
figsize Size of the figure [Link](figsize=(8,6))
bins Number of buckets in histogram bins=5, bins=20
alpha Transparency (0=invisible, 1=solid) alpha=0.7
edgecolor Border colour of bars edgecolor='black'
autopct Percentage format in pie chart autopct='%1.1f%%'
explode Pull out a pie slice [0.1, 0, 0, 0]
■ NOTE: 'olivegreen' is NOT a valid Matplotlib colour. Use 'olive', 'green', or a hex code like '#556B2F'
SECTION 4 — Seaborn (Statistical Visualisation)
What is Seaborn?
Seaborn is a Python library built on top of Matplotlib. It creates beautiful statistical charts with less code. It
works directly with Pandas DataFrames. It is especially used for heatmaps, distribution plots, and boxplots.
Q. How do you import Seaborn?
import seaborn as sns
import [Link] as plt
Q. What is a Heatmap and how do you create one?
Ans: Definition: A Heatmap is a colour-coded grid that shows the correlation (relationship strength)
between different numeric columns in a dataset. Dark blue = strong positive correlation. Red = negative
correlation.
import seaborn as sns
import [Link] as plt
[Link](figsize=(25, 20))
corr = [Link](numeric_only=True) # Calculate correlation between all columns
[Link](corr, cmap='RdBu', annot=True)
[Link]('Correlation Heatmap')
[Link]()
• cmap='RdBu' — Red-Blue colour map. Blue = positive, Red = negative correlation.
• annot=True — Shows the actual correlation numbers inside each cell.
Key HR Data Findings:
• MonthlyIncome vs JobLevel = 0.95 — Very strong positive correlation (almost perfect)
• YearsAtCompany vs YearsWithCurrManager = 0.76 — Strong positive correlation
Q. How do you create a Histogram with a smooth density curve (KDE)?
Ans: [Link]() with kde=True adds a smooth curve over the histogram showing the distribution shape.
[Link](df['Age'], kde=True, bins=20)
[Link]('Age Distribution of Employees')
[Link]()
Q. What are all the important Seaborn functions?
Function What it creates
[Link]() Correlation heatmap with colour coding
[Link](kde=True) Histogram with smooth density curve (KDE)
[Link]() Box-whisker plot to find outliers
[Link]() Bar chart for count of categories
SECTION 5 — Object-Oriented Programming (OOP)
What is OOP?
Object-Oriented Programming (OOP) is a way of writing programs by organising code into Classes
(blueprints) and Objects (real things made from that blueprint). It makes code reusable, clean, and easy to
manage.
Key Definitions:
Term Simple Definition Real Life Example
Class A blueprint or template Blueprint of a house
Object A real thing created from the class An actual house built from blueprint
Attribute Data/information stored in the object House colour, number of rooms
Method An action/function the object can do Open door, switch lights
self Refers to the current object itself 'this' house (not some other house)
__init__() Constructor — runs automatically on Setting up a new house when built
creation
Q. How do you define a basic Class in Python?
Ans: A class is defined using the 'class' keyword. Variables inside it are called Class Variables.
class Student:
name = 'Aman' # Class variable
age = 22 # Class variable
s1 = Student() # Create an object
print([Link]) # Output: Aman
print([Link]) # Output: 22
Q. What is the difference between Class Variable and Instance Variable?
Ans: Class Variable: Defined inside the class, outside any method. It is SHARED by all objects of that
class. All objects get the same value.
Instance Variable: Defined on a specific object (e.g., [Link] = 'Amit'). It belongs ONLY to that object.
Each object can have a different value.
class Employee:
company = 'TCS' # Class variable — same for all employees
e1 = Employee()
[Link] = 'Amit' # Instance variable — only for e1
[Link] = 40000
e2 = Employee()
[Link] = 'Neha' # Instance variable — only for e2
[Link] = 50000
print([Link], [Link], [Link]) # Amit 40000 TCS
print([Link], [Link], [Link]) # Neha 50000 TCS
Q. What is a Method in a class? How is it different from a regular function?
Ans: A Method is a function defined inside a class. The key difference is that a method always has self as
its first parameter. 'self' allows the method to access the object's data.
class Add:
def add_numbers(self, a, b, c): # 'self' is always first!
return a + b + c
a1 = Add()
print('Addition:', a1.add_numbers(77636635, 109877997, 766))
# Output: Addition: 187515398
Q. Explain the __init__ Constructor with an example.
Ans: The __init__ method is called a Constructor. It runs AUTOMATICALLY when an object is created. It
is used to set up initial values for the object.
class Car:
def __init__(self, brand, colour):
[Link] = brand # Set when object is created
[Link] = colour
def show_details(self):
print('Brand:', [Link], '| Colour:', [Link])
c1 = Car('BMW', 'Black') # __init__ runs automatically here
c1.show_details() # Output: Brand: BMW | Colour: Black
Q. Write a class to check if a number is Even or Odd.
class Numbers:
def evenodd(self, n):
if n % 2 == 0:
return 'Even'
else:
return 'Odd'
n1 = Numbers()
print([Link](9)) # Output: Odd
print([Link](68)) # Output: Even
Q. Write a class to calculate Simple Interest.
Ans: Formula: Simple Interest (SI) = (Principal × Rate × Time) / 100
class Interest:
def calc(self, p, r, t):
return (p * r * t) / 100
si = Interest()
print('Simple Interest:', [Link](7, 8, 6))
# Calculation: (7 × 8 × 6) / 100 = 3.36
Q. Write a class to find the Largest and Smallest of two numbers.
class Largest:
def find_largest(self, a, b):
if a > b:
return a
else:
return b
class Smallest:
def find_smallest(self, a, b):
if a < b:
return a
else:
return b
n1 = Largest()
print('Largest:', n1.find_largest(92, 67)) # 92
n2 = Smallest()
print('Smallest:', n2.find_smallest(92, 67)) # 67
Q. Write a Vendor Management class for a fruit market.
Ans: This example shows class variable (product category shared by all vendors) and instance variables
(each vendor's own product details).
class Vendor:
product = 'Fruits' # Class variable — same for ALL vendors
v1 = Vendor()
[Link] = 'Apple'
[Link] = 40
[Link] = 120
v2 = Vendor()
[Link] = 'Banana'
[Link] = 20
[Link] = 100
print([Link], 'Qty:', [Link], '| Price:', [Link], '| Category:',
[Link])
# Output: Apple Qty: 40 | Price: 120 | Category: Fruits
OOP Summary Table
Concept Syntax Purpose
Class Definition class ClassName: Create a blueprint
Object Creation obj = ClassName() Make a real instance from blueprint
Class Variable Inside class, outside method Shared by ALL objects
Instance Variable [Link] = value Unique to each object
Method def method(self, ...): Function belonging to the class
self First param of every method Refers to current object
Constructor def __init__(self, ...): Runs automatically on object creation
SECTION 6 — Connecting Python to MySQL Database
What is MySQL Connector?
Python can be connected to a MySQL database using a library called mysql-connector-python. This library
acts as an interface (bridge) that allows Python programs to communicate with the MySQL server and
perform database operations.
Q. What are the steps to connect Python to MySQL?
Ans: There are 7 steps involved in connecting Python to a MySQL database:
1. Installing the Connector
A MySQL connector library must be installed to enable communication between Python and the database.
pip install mysql-connector-python
2. Importing the Module
The connector module is imported into the Python program to use its functions.
import [Link]
3. Establishing a Connection
A connection is created using the server's host name, username, password, and database name. This step
allows Python to access the MySQL database.
conn = [Link](
host='localhost',
user='root',
password='yourpassword',
database='school'
)
4. Creating a Cursor Object
A cursor is an object used to execute SQL queries and retrieve results from the database. Think of it as a
'pointer' that runs commands inside the database.
cursor = [Link]()
5. Executing SQL Queries
SQL commands such as SELECT, INSERT, UPDATE, and DELETE are executed using the cursor object.
[Link]('SELECT * FROM students')
results = [Link]()
for row in results:
print(row)
6. Committing Changes
For operations that modify data (INSERT, UPDATE, DELETE), changes must be committed to save them
permanently in the database.
[Link]() # Save changes permanently
7. Closing the Connection
Finally, the cursor and connection are closed to free system resources.
[Link]()
[Link]()
Q. Write a complete Python program to connect to MySQL and retrieve data.
import [Link]
# Step 3: Establish Connection
conn = [Link](
host='localhost',
user='root',
password='password123',
database='school'
)
# Step 4: Create Cursor
cursor = [Link]()
# Step 5: Execute SQL Query
[Link]('SELECT * FROM students')
results = [Link]()
for row in results:
print(row)
# Step 7: Close Connection
[Link]()
[Link]()
print('Connection closed.')
Q. What is the difference between fetchone(), fetchall(), and fetchmany()?
Method What it Returns
fetchone() Returns only the NEXT single row of result
fetchall() Returns ALL remaining rows as a list
fetchmany(n) Returns the next N rows as a list
Q. How do you INSERT data into a MySQL table using Python?
[Link](
'INSERT INTO students (name, age) VALUES (%s, %s)',
('Rahul', 21)
)
[Link]() # Must commit to save the INSERT
■ NOTE: Always call [Link]() after INSERT, UPDATE, or DELETE — otherwise changes are NOT saved!
SECTION 7 — Important Case Studies (Exam Q&A;)
Case Study 1: HR Analytics — Employee Attrition
Scenario: A company with 1,480 employees wants to analyse their HR dataset (HR_Analytics.csv) to
understand employee patterns and missing data.
Q. How would you load and initially inspect the HR dataset?
import pandas as pd
df = pd.read_csv('/content/HR_Analytics.csv')
print([Link](10)) # First 10 rows
print([Link]) # (1480, 38)
print([Link]()) # Column names, types, null counts
print([Link]()) # Statistical summary
Q. How do you check for missing values and what was found?
print([Link]().sum())
# Result: Only 'YearsWithCurrManager' had 57 null values
# All other 37 columns had 0 nulls
# Fix: Fill with mean
df['YearsWithCurrManager'].fillna(
df['YearsWithCurrManager'].mean(), inplace=True)
Q. How do you draw a Correlation Heatmap?
import seaborn as sns, [Link] as plt
[Link](figsize=(25, 20))
corr = [Link](numeric_only=True)
[Link](corr, cmap='RdBu', annot=True)
[Link]('Correlation')
[Link]()
# Key finding: MonthlyIncome vs JobLevel = 0.95 (very strong!)
Case Study 2: Vendor Management Using OOP
Scenario: A fruit market wants to manage multiple vendors. All vendors sell 'Fruits' but each has their own
product name, quantity, and price.
Q. Design a Vendor class with class and instance variables.
class Vendor:
product = 'Fruits' # Class variable (same for all vendors)
v1 = Vendor()
[Link] = 'Apple'
[Link] = 40
[Link] = 120
v2 = Vendor()
[Link] = 'Banana'
[Link] = 20
[Link] = 100
Q. Add a method to calculate total revenue for each vendor.
class Vendor:
product = 'Fruits'
def total_revenue(self):
return [Link] * [Link]
v1 = Vendor()
[Link] = 'Apple'
[Link] = 40
[Link] = 120
print('Revenue:', v1.total_revenue()) # 40 × 120 = 4800
Case Study 3: Monthly Expense Dashboard
Expenses: Rent 40%, Food 25%, Transport 10%, Entertainment 15%, Savings 10%
Q. Create a pie chart that highlights the largest expense.
import [Link] as plt
data = {'Rent':40, 'Food':25, 'Transport':10, 'Entertainment':15, 'Savings':10}
labels = list([Link]())
values = list([Link]())
max_value = max(values) # 40 = Rent
explode = [0.1 if v == max_value else 0 for v in values]
[Link](figsize=(8, 6))
[Link](values, labels=labels, autopct='%1.1f%%',
explode=explode, startangle=140, shadow=True,
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99','#c2c2f0'])
[Link]('Monthly Expenses Breakdown')
[Link]('equal')
[Link]()
SECTION 8 — Quick Revision Cheat Sheet
Imports — Always Write These First
import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
Most Important Points to Remember
Topic Key Point
Matrix Multiply Use [Link](a,b) — NOT a*b (that's element-wise only)
Pie Chart Always add [Link]('equal') — makes it a circle, not oval
Missing Values HR Data: YearsWithCurrManager had 57 null values
Correlation MonthlyIncome vs JobLevel = 0.95 (very strong in HR data)
Valid Colour 'olivegreen' is INVALID. Use 'olive', 'green', or '#556B2F'
Commit SQL Always call [Link]() after INSERT/UPDATE/DELETE
Class Variable Defined inside class, outside method. Shared by all objects.
Instance Variable [Link] = value — unique to each object
Constructor def __init__(self): — auto-called when object is created
DataFrame Check [Link]().sum() — ALWAYS check before analysis
Histogram Bins bins= divides data range into N equal groups
Explode Pie explode=[0.1, 0, 0, 0] — pulls first slice outward
autopct autopct='%1.1f%%' — shows percentages on pie chart
Heatmap annot annot=True — shows number values inside heatmap cells
Best of Luck on Your Exam!
Read each question carefully. Show your code with comments.
Always import libraries first. You've got this!