---
title: "Class 12 IP Practical File 2026-27: pandas, Charts, SQL"
description: "Class 12 IP practical file 2026-27 for CBSE 065: 18 pandas programs, 5 Matplotlib charts and 19 SQL entries with real output, index and certificate."
canonical: https://learn.modernagecoders.com/cbse-class-12-informatics-practices-practical-file
source: src/pages/cbse-class-12-informatics-practices-practical-file.html
---
> Class 12 IP practical file 2026-27 for CBSE 065: 18 pandas programs, 5 Matplotlib charts and 19 SQL entries with real output, index and certificate.

Start here

## Courses that build the skills in this file

The IP course covers Class 11 and 12 in syllabus order. The other two go deeper into one half of the file each: data handling in pandas, or SQL.

[![Informatics Practices Class 11 and 12 course thumbnail](/images/ip-cs-class-11-12.webp)  This subject / 065 Informatics Practices Class 11 and 12 Series, DataFrames, Matplotlib, SQL, networks and society in board order, with practical file and viva preparation. Open the course →](/courses/cbse-informatics-practices-ip-class-11-12-python-pandas-sql-complete-course)[![Data Science for Teens course thumbnail](/images/data-science-teens.webp)  Beyond the file / Data Data Science for Teens For a student who enjoys the pandas half: cleaning real data, honest charts, statistics and first machine learning models. Open the course →](/courses/data-science-course-for-teens-python-data)[![MySQL for Teens course thumbnail](/images/mysql-teens.webp)  SQL half / Queries MySQL for Teens From the first SELECT to joins and small database apps, useful if the 25 SQL marks of the theory paper worry you. Open the course →](/courses/mysql-mastery-for-teens)

Ans. The short version

A Class 12 IP practical file for CBSE 065 must include at least 15 programs on pandas, 4 on Matplotlib and 15 SQL queries in 2026-27, and it earns 5 of the 30 practical marks. The other 25 are for pandas and Matplotlib programs (8), SQL queries (7), project (5) and viva (5). This page is a complete file: 18 pandas programs, 5 charts and 19 SQL entries, each with its real output, plus index and certificate wording. Modern Age Coders teaches students to write their own file in live one to one classes, and a priority demo lets you try a full class first.

Q1. How much goes in?

## How many programs are required in the Class 12 IP practical file 2026-27?

Thirty-four entries at the least: 15 pandas programs, 4 Matplotlib programs and 15 SQL queries. The CBSE Class XII Informatics Practices syllabus for 2026-27 states all three numbers.

| Practical head | Marks | How the file helps you score it |
| --- | --- | --- |
| Programs using pandas and Matplotlib | 8 | Marked apart from the file. Entries 1 to 23 are your practice for it |
| SQL queries | 7 | Also marked apart. Queries 1 to 19 use every function the syllabus names (or its listed twin) except NOW(), whose answer changes each second |
| **Practical file** | **5** | Complete, in order, signed, with outputs that match the code |
| Project work | 5 | A separate submission, using Class XI and XII ideas |
| Viva voce | 5 | Any page of your file can start a question |
| **Total** | **30** | Theory carries the remaining 70 |

So the file itself is 5 marks, but it trains you for 20 more: the programs, the queries and the viva. The project is the only head it does not prepare, and that has its own page: [a Class 12 IP project with source code](/cbse-class-12-informatics-practices-project).

**When it is due.** CBSE has scheduled the 2026-27 practical, project and internal assessment from 1 January 2027; winter-bound schools have 9 November to 19 December 2026. Your school names the day, and often wants the file signed earlier. Ask for both dates.

Q2. How is it arranged?

## Class 12 Informatics Practices practical file format: certificate and index

Keep the three groups in three sections, pandas, Matplotlib, SQL, so an examiner can count each one in seconds. The syllabus fixes the numbers, not the design, so your school’s layout comes first.

### Title page

Informatics Practices (065)
 **Practical File: pandas, Matplotlib and MySQL**
 Session 2026-27

Name, class and section
 Board roll number
 School name and city

### Certificate wording

This file is the work of [name], Class XII [section], board roll number [number]. The programs and queries in it were written and run by the student in the IP laboratory of [school] in the session 2026-27 under my supervision.

Internal examiner: [signature]
 External examiner: [signature]
 Principal: [signature and seal]

### Software used (one line)

Python with pandas and Matplotlib; MySQL. Write the versions on your own computer.

Ours: pandas 2.3.3, Matplotlib 3.11, MySQL 26.10. If your pandas is version 3, text columns show `dtype: str` where this page shows `object`.

### Index of the IP practical file

The last column shows where an entry comes from: a line of the CBSE suggested practical list, or a topic named in the syllabus units.

| No. | Entry | Source in the 065 document |
| --- | --- | --- |
| 1, 2 | Series from a dictionary; from an ndarray | Suggested list 5.1, item 1 |
| 3 to 5 | Scalar Series; arithmetic; indexing, slicing, head and tail | Unit 1, Series |
| 6 | Elements above the 75th percentile | 5.1, item 2 |
| 7, 8 | DataFrame from Series; from a list of dictionaries | Unit 1, DataFrames |
| 9 | Quarterly sales grouped by category | 5.1, item 3 |
| 10 | Labels, data types and dimensions of a result | 5.1, item 4 |
| 11 to 14 | Add; rename and delete; select; Boolean indexing | Unit 1, DataFrames |
| 15 | Duplicate rows | 5.1, item 5 |
| 16 | Iteration over rows and columns | Unit 1, DataFrames |
| 17, 18 | CSV export and import; a text file with another separator | 5.1, item 6 |
| 19, 20 | Line plots, one and two lines | 5.2, items 2 and 3 |
| 21, 22 | Bar graphs, subject-wise and class-wise | 5.2, items 1 and 2 |
| 23 | Histogram of marks | 5.2, items 1 and 2 |
| Q1 to Q5 | Create, insert, update, delete | 5.3, items 1 to 3 |
| Q6 to Q9 | Conditions, sorting, aggregates, counting | 5.3, items 4, 5 and 7 |
| Q10 to Q12 | GROUP BY and HAVING | 5.3, item 6 and Unit 2 |
| Q13 to Q16 | Math, text and date functions | Unit 2, functions |
| Q17 to Q19 | Equi-join, join with groups, ALTER and DROP | Unit 2 |

Q3. Where does the file begin?

## Class 12 IP practical file, Python pandas: Series programs 1 to 6

It begins with a Series, the one-dimensional structure: three ways to create it, then arithmetic, slicing and a filter. Each program imports pandas again, because each is a separate file in your folder.

### Program 1: Series from a dictionary

**Aim:** To create a Series from a dictionary of library visitors and display its index, values and size.

***Program 1**pandas*

```
# Program 1: Series from a dictionary
import pandas as pd

visitors = {"Mon": 42, "Tue": 35, "Wed": 58,
            "Thu": 35, "Fri": 61}
footfall = pd.Series(visitors)        # keys become the index
footfall.name = "Library visitors"

print(footfall)
print("Index :", list(footfall.index))
print("Values:", footfall.values)
print("Size  :", footfall.size)
```

***Output**as printed*

```
Mon    42
Tue    35
Wed    58
Thu    35
Fri    61
Name: Library visitors, dtype: int64
Index : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
Values: [42 35 58 35 61]
Size  : 5
```

**Why it works:** the dictionary keys turn into index labels and the values become the data. Tue and Thu share the value 35, which is fine; a label such as Tue appears only once because a dictionary key cannot repeat.

### Program 2: Series from a NumPy ndarray

**Aim:** To create a Series from an ndarray, with the default index and with labels of your own.

***Program 2**pandas*

```
# Program 2: Series from a NumPy ndarray
import numpy as np
import pandas as pd

temps = np.array([24.5, 27.0, 31.5, 30.0])     # an ndarray
plain = pd.Series(temps)          # index 0, 1, 2, 3
named = pd.Series(temps,
                  index=["8 am", "10 am", "12 pm", "2 pm"])

print(plain)
print(named)
print("At 12 pm:", named["12 pm"])
```

***Output**as printed*

```
0    24.5
1    27.0
2    31.5
3    30.0
dtype: float64
8 am     24.5
10 am    27.0
12 pm    31.5
2 pm     30.0
dtype: float64
At 12 pm: 31.5
```

**Why it works:** when no index is passed, pandas numbers the values 0, 1, 2, 3. A list of labels must have exactly one label per value, four here, or a ValueError is raised.

### Program 3: Series from a scalar value

**Aim:** To create a Series from one value repeated for every roll number, then change two of them.

***Program 3**pandas*

```
# Program 3: Series from a scalar value
import pandas as pd

rolls = [1201, 1202, 1203, 1204]
lab_marks = pd.Series(0, index=rolls)     # 0 for every roll
print("Before the test:")
print(lab_marks)

lab_marks[1202] = 8                       # change by label
lab_marks[1204] = 7
print("After two students are marked:")
print(lab_marks)
```

***Output**as printed*

```
Before the test:
1201    0
1202    0
1203    0
1204    0
dtype: int64
After two students are marked:
1201    0
1202    8
1203    0
1204    7
dtype: int64
```

**Why it works:** a single value has no length of its own, so the index decides how long the Series is. Assigning with a label changes that element in place.

### Program 4: arithmetic on two Series

**Aim:** To add two Series whose labels only partly match, and to multiply a Series by a number.

***Program 4**pandas*

```
# Program 4: arithmetic on two Series
import pandas as pd

shelf_a = pd.Series([30, 12, 8],
                    index=["pens", "files", "scales"])
shelf_b = pd.Series([15, 20, 6],
                    index=["pens", "scales", "maps"])

print("shelf_a + shelf_b")
print(shelf_a + shelf_b)                      # matched by label
print("add() with fill_value=0")
print(shelf_a.add(shelf_b, fill_value=0))     # missing means 0
print("Twice shelf_a")
print(shelf_a * 2)
```

***Output**as printed*

```
shelf_a + shelf_b
files      NaN
maps       NaN
pens      45.0
scales    28.0
dtype: float64
add() with fill_value=0
files     12.0
maps       6.0
pens      45.0
scales    28.0
dtype: float64
Twice shelf_a
pens      60
files     24
scales    16
dtype: int64
```

**Why it works:** pandas lines the two up by label, not by position. A label found on one side alone gives NaN, and NaN is a float, which is why 45 prints as 45.0. `fill_value=0` says what to use for the absent side.

### Program 5: indexing, slicing, head() and tail()

**Aim:** To select elements of a Series by label, by position, by slice and from either end.

***Program 5**pandas*

```
# Program 5: indexing, slicing, head() and tail()
import pandas as pd

steps = pd.Series([6200, 8100, 4500, 9700, 7300, 11200],
                  index=["d1", "d2", "d3", "d4", "d5", "d6"])

print("By label   d4 :", steps["d4"])
print("By position 3 :", steps.iloc[3])
print("Label slice d2 to d4:")
print(steps["d2":"d4"])            # d4 is included
print("Position slice 1 to 3:")
print(steps.iloc[1:3])             # position 3 is left out
print("First two:", list(steps.head(2)))
print("Last two :", list(steps.tail(2)))
```

***Output**as printed*

```
By label   d4 : 9700
By position 3 : 9700
Label slice d2 to d4:
d2    8100
d3    4500
d4    9700
dtype: int64
Position slice 1 to 3:
d2    8100
d3    4500
dtype: int64
First two: [6200, 8100]
Last two : [7300, 11200]
```

**Why it works:** a label slice keeps its last label and a position slice drops its last position. So `"d2":"d4"` gives three values and `1:3` gives two.

### Program 6: values above the 75th percentile

**Aim:** Given a Series of reading times, to print all the elements above the 75th percentile.

***Program 6**pandas*

```
# Program 6: elements above the 75th percentile
import pandas as pd

minutes = pd.Series([35, 50, 20, 65, 45, 80, 30, 55],
                    index=list("ABCDEFGH"))      # reading time

limit = minutes.quantile(0.75)
print("75th percentile:", limit)
print("Above it:")
print(minutes[minutes > limit])
```

***Output**as printed*

```
75th percentile: 57.5
Above it:
D    65
F    80
dtype: int64
```

**Why it works:** in sorted order the 75th percentile falls between 55 and 65, at 57.5. `minutes > limit` is a Series of True and False, and the square brackets keep only the True rows.

For output-type questions on the same ideas, use [pandas Series for Class 12](/cbse-class-12-informatics-practices-pandas-series).

Q4. Which DataFrame programs are needed?

## pandas DataFrame programs 7 to 18 for the practical file

Twelve programs cover what the syllabus lists for DataFrames: creating, displaying, adding, selecting, deleting, renaming, filtering, iterating, and moving data to and from files.

### Program 7: DataFrame from a dictionary of Series

**Aim:** To create a DataFrame from two Series of term marks with different subjects.

***Program 7**pandas*

```
# Program 7: DataFrame from a dictionary of Series
import pandas as pd

term1 = pd.Series({"Accounts": 64, "IP": 78, "English": 71})
term2 = pd.Series({"IP": 85, "English": 69, "Economics": 74})

result = pd.DataFrame({"Term 1": term1, "Term 2": term2})
print(result)
print("Marks present in each term:")
print(result.count())
```

***Output**as printed*

```
           Term 1  Term 2
Accounts     64.0     NaN
Economics     NaN    74.0
English      71.0    69.0
IP           78.0    85.0
Marks present in each term:
Term 1    3
Term 2    3
dtype: int64
```

**Why it works:** the row labels are all the subjects found in either Series. A subject missing from one term becomes NaN, and `count()` counts only the values that are present.

### Program 8: DataFrame from a list of dictionaries

**Aim:** To create a DataFrame from a list of dictionaries, one of which has a key missing.

***Program 8**pandas*

```
# Program 8: DataFrame from a list of dictionaries
import pandas as pd

buses = [
    {"Route": "R1", "Stops": 9, "Students": 38},
    {"Route": "R2", "Stops": 12, "Students": 41},
    {"Route": "R3", "Students": 27},       # Stops not known
]
table = pd.DataFrame(buses)
print(table)

labelled = pd.DataFrame(buses, index=["b1", "b2", "b3"])
print("Only two columns, own row labels:")
print(labelled[["Route", "Students"]])
```

***Output**as printed*

```
  Route  Stops  Students
0    R1    9.0        38
1    R2   12.0        41
2    R3    NaN        27
Only two columns, own row labels:
   Route  Students
b1    R1        38
b2    R2        41
b3    R3        27
```

**Why it works:** each dictionary is a row and each key a column. Route R3 has no Stops key, so its cell is NaN and the whole Stops column becomes float.

### Program 9: quarterly sales by category

**Aim:** To create a DataFrame of quarterly sales with category, item and expenditure, and print the total expenditure of each category.

***Program 9**pandas*

```
# Program 9: quarterly sales, total spending per category
import pandas as pd

sales = pd.DataFrame({
    "Category": ["Stationery", "Sports", "Stationery",
                 "Cleaning", "Sports", "Cleaning"],
    "Item": ["Chart paper", "Football", "Marker set",
             "Mop", "Net", "Dustbin"],
    "Expenditure": [1450, 2600, 980, 720, 1900, 1350]})

print(sales)
totals = sales.groupby("Category")["Expenditure"].sum()
print("Total expenditure per category:")
print(totals)
print("Grand total:", totals.sum())
```

***Output**as printed*

```
     Category         Item  Expenditure
0  Stationery  Chart paper         1450
1      Sports     Football         2600
2  Stationery   Marker set          980
3    Cleaning          Mop          720
4      Sports          Net         1900
5    Cleaning      Dustbin         1350
Total expenditure per category:
Category
Cleaning      2070
Sports        4500
Stationery    2430
Name: Expenditure, dtype: int64
Grand total: 9000
```

**Why it works:** `groupby()` collects the rows of each category and `sum()` adds one column inside every group. The categories come out in alphabetical order.

### Program 10: labels, data types and dimensions

**Aim:** To create a DataFrame of an examination result and display its row labels, column labels, data types and dimensions.

***Program 10**pandas*

```
# Program 10: labels, data types and dimensions
import pandas as pd

result = pd.DataFrame(
    {"Name": ["Ishita", "Rehan", "Tanvi", "Yusuf"],
     "IP": [88, 73, 91, 65],
     "Eco": [79.5, 82.0, 68.5, 74.0]},
    index=["X1", "X2", "X3", "X4"])

print("Row labels   :", list(result.index))
print("Column labels:", list(result.columns))
print("Data types:")
print(result.dtypes)
print("Dimensions:", result.ndim, " Shape:", result.shape,
      " Size:", result.size)
```

***Output**as printed*

```
Row labels   : ['X1', 'X2', 'X3', 'X4']
Column labels: ['Name', 'IP', 'Eco']
Data types:
Name     object
IP        int64
Eco     float64
dtype: object
Dimensions: 2  Shape: (4, 3)  Size: 12
```

**Why it works:** `dtypes`, `shape`, `size` and `ndim` are attributes, so they take no brackets. Size is 4 rows times 3 columns, and text is stored as object.

### Program 11: adding columns and a row

**Aim:** To add a calculated column, a column at a chosen place and a new row to a DataFrame.

***Program 11**pandas*

```
# Program 11: add columns and a row
import pandas as pd

team = pd.DataFrame({"Player": ["Anvi", "Dev", "Meher"],
                     "Match1": [14, 22, 9],
                     "Match2": [18, 11, 25]})

team["Total"] = team["Match1"] + team["Match2"]  # new column
team.insert(1, "House", ["Red", "Blue", "Red"])  # 2nd place
team.loc[3] = ["Om", "Blue", 20, 16, 36]         # new row
print(team)
```

***Output**as printed*

```
  Player House  Match1  Match2  Total
0   Anvi   Red      14      18     32
1    Dev  Blue      22      11     33
2  Meher   Red       9      25     34
3     Om  Blue      20      16     36
```

**Why it works:** assigning to a new column name puts it at the end; `insert()` takes the position first. `loc[3]` creates a row because label 3 did not exist. If it had, that row would be overwritten.

### Program 12: renaming and deleting

**Aim:** To rename columns and a row label, and to delete one column and one row.

***Program 12**pandas*

```
# Program 12: rename and delete rows and columns
import pandas as pd

stock = pd.DataFrame(
    {"itm": ["Chalk", "Duster", "Globe", "Map"],
     "qty": [40, 12, 3, 7],
     "rack": ["A", "A", "B", "C"]},
    index=[101, 102, 103, 104])

stock = stock.rename(columns={"itm": "Item", "qty": "Quantity"})
stock = stock.rename(index={104: 110})
print(stock)

stock = stock.drop("rack", axis=1)        # axis 1: a column
stock = stock.drop(102, axis=0)           # axis 0: a row
print("After deleting column rack and row 102:")
print(stock)
```

***Output**as printed*

```
       Item  Quantity rack
101   Chalk        40    A
102  Duster        12    A
103   Globe         3    B
110     Map         7    C
After deleting column rack and row 102:
      Item  Quantity
101  Chalk        40
103  Globe         3
110    Map         7
```

**Why it works:** `rename()` and `drop()` return a changed copy, so the result is assigned back. `axis=1` means the label is a column, `axis=0` a row.

### Program 13: selecting with loc and iloc

**Aim:** To select a column, a row, a block and a single cell of a DataFrame.

***Program 13**pandas*

```
# Program 13: select with loc, iloc and column names
import pandas as pd

hostel = pd.DataFrame({"Wing": ["N", "N", "S", "S"],
                       "Beds": [2, 3, 2, 4],
                       "Filled": [2, 1, 2, 3]},
                      index=["R1", "R2", "R3", "R4"])

print("One column:", list(hostel["Beds"]))
print("One row as a Series:")
print(hostel.loc["R4"])
print("Rows R2 to R3, two columns:")
print(hostel.loc["R2":"R3", ["Wing", "Filled"]])
print("First two rows, last two columns:")
print(hostel.iloc[0:2, 1:3])
print("One cell:", hostel.loc["R2", "Filled"])
```

***Output**as printed*

```
One column: [2, 3, 2, 4]
One row as a Series:
Wing      S
Beds      4
Filled    3
Name: R4, dtype: object
Rows R2 to R3, two columns:
   Wing  Filled
R2    N       1
R3    S       2
First two rows, last two columns:
    Beds  Filled
R1     2       2
R2     3       1
One cell: 1
```

**Why it works:** `loc` uses labels and includes both ends; `iloc` uses positions and leaves the end out. One row comes back as a Series whose index is the column names.

### Program 14: Boolean indexing

**Aim:** To filter the rows of a DataFrame with one condition, with AND and with OR.

***Program 14**pandas*

```
# Program 14: Boolean indexing with one and two conditions
import pandas as pd

fest = pd.DataFrame({
    "Stall": ["Dosa", "Juice", "Books", "Plants", "Games"],
    "Type": ["Food", "Food", "Shop", "Shop", "Fun"],
    "Sold": [120, 95, 34, 58, 140]})

print("Sold more than 90:")
print(fest[fest["Sold"] > 90])
print("Food AND more than 100:")
print(fest[(fest["Type"] == "Food") & (fest["Sold"] > 100)])
print("Shop OR more than 130:")
print(fest[(fest["Type"] == "Shop") | (fest["Sold"] > 130)])
```

***Output**as printed*

```
Sold more than 90:
   Stall  Type  Sold
0   Dosa  Food   120
1  Juice  Food    95
4  Games   Fun   140
Food AND more than 100:
  Stall  Type  Sold
0  Dosa  Food   120
Shop OR more than 130:
    Stall  Type  Sold
2   Books  Shop    34
3  Plants  Shop    58
4   Games   Fun   140
```

**Why it works:** each condition stands in its own brackets and the pair is joined with `&` or `|`. Writing the word `and` raises a ValueError. The row labels 2, 3 and 4 are kept from the original.

### Program 15: duplicate rows

**Aim:** To find duplicate rows in a DataFrame of event entries and display the data without them.

***Program 15**pandas*

```
# Program 15: find and remove duplicate rows
import pandas as pd

entries = pd.DataFrame({
    "Adm_No": [5011, 5014, 5011, 5020, 5014],
    "Event": ["Chess", "Quiz", "Chess", "Quiz", "Debate"]})

print("Is this row a repeat?")
print(entries.duplicated())
print("The repeated rows:")
print(entries[entries.duplicated()])
print("After removing them:")
print(entries.drop_duplicates())
print("First entry of each student:")
print(entries.drop_duplicates(subset="Adm_No"))
```

***Output**as printed*

```
Is this row a repeat?
0    False
1    False
2     True
3    False
4    False
dtype: bool
The repeated rows:
   Adm_No  Event
2    5011  Chess
After removing them:
   Adm_No   Event
0    5011   Chess
1    5014    Quiz
3    5020    Quiz
4    5014  Debate
First entry of each student:
   Adm_No  Event
0    5011  Chess
1    5014   Quiz
3    5020   Quiz
```

**Why it works:** `duplicated()` marks a row only if every column repeats an earlier row. Student 5014 entered two different events, so that row is a repeat only when `subset` limits the check to Adm_No.

### Program 16: iterating over a DataFrame

**Aim:** To display the data of a DataFrame row by row and column by column.

***Program 16**pandas*

```
# Program 16: iterate over rows and over columns
import pandas as pd

tanks = pd.DataFrame({"Place": ["Roof", "Garden", "Canteen"],
                      "Litres": [900, 260, 510]})

print("Row by row with iterrows():")
for label, row in tanks.iterrows():
    if row["Litres"] < 300:
        remark = "refill"
    else:
        remark = "enough"
    print(label, row["Place"], row["Litres"], remark)

print("Column by column with items():")
for name, column in tanks.items():
    print(name, "->", list(column))
```

***Output**as printed*

```
Row by row with iterrows():
0 Roof 900 enough
1 Garden 260 refill
2 Canteen 510 enough
Column by column with items():
Place -> ['Roof', 'Garden', 'Canteen']
Litres -> [900, 260, 510]
```

**Why it works:** `iterrows()` gives the row label and the row as a Series. `items()` gives the column name and the column as a Series.

### Program 17: DataFrame to CSV and back

**Aim:** To export a DataFrame to a CSV file and import it with one column as the index.

***Program 17**pandas*

```
# Program 17: export a DataFrame to CSV and import it again
import pandas as pd

marks = pd.DataFrame({"Roll": [1, 2, 3],
                      "Name": ["Ira", "Neel", "Sana"],
                      "Marks": [82, None, 90]})
marks.to_csv("marks.csv", index=False)      # no row labels

with open("marks.csv") as f:        # look inside the file
    print(f.read())

back = pd.read_csv("marks.csv", index_col="Roll")
print(back)
print("Average of those present:", back["Marks"].mean())
```

***Output**as printed*

```
Roll,Name,Marks
1,Ira,82.0
2,Neel,
3,Sana,90.0

      Name  Marks
Roll
1      Ira   82.0
2     Neel    NaN
3     Sana   90.0
Average of those present: 86.0
```

**Why it works:** without `index=False` the row numbers are written too and return as a column named Unnamed: 0. Neel was absent, so his field in the file is empty, and `mean()` divides by 2, not 3.

### Program 18: text file with another separator

**Aim:** To read a text file separated by semicolons, display its first and last rows, and save selected rows to a new file.

***Program 18**pandas*

```
# Program 18: read a text file that is not comma separated
import pandas as pd

with open("plants.txt", "w") as f:          # make the test file
    f.write("Tulsi;32;Yes\n")
    f.write("Neem;140;No\n")
    f.write("Aloe;25;Yes\n")
    f.write("Mint;18;Yes\n")

plants = pd.read_csv("plants.txt", sep=";", header=None,
                     names=["Plant", "Height", "Potted"])
print(plants.head(3))
print("Last row:")
print(plants.tail(1))
tall = plants[plants["Height"] > 30]
tall.to_csv("tall.txt", sep="|", index=False)
print("Rows written to tall.txt:", len(tall))
```

***Output**as printed*

```
   Plant  Height Potted
0  Tulsi      32    Yes
1   Neem     140     No
2   Aloe      25    Yes
Last row:
  Plant  Height Potted
3  Mint      18    Yes
Rows written to tall.txt: 2
```

**Why it works:** `sep` names the separator. This file has no heading line, so `names` supplies the column names; leave out both names and `header=None` and Tulsi would be taken as a heading.

More practice on selection and filtering is on [DataFrame for Class 12 IP](/cbse-class-12-informatics-practices-dataframe).

Q5. What about the charts?

## Matplotlib programs 19 to 23: line plot, bar graph and histogram

The syllabus names three plots, line, bar and histogram, and at least four programs. Every chart below was saved by the program beside it, with `savefig()` before `show()`, so the picture in your file and the one on disk are the same.

### Program 19: line plot

**Aim:** To plot the water used in a school on the six days of a week.

***Program 19**Matplotlib*

```
# Program 19: line plot of one week
import matplotlib.pyplot as plt

days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
kilolitres = [5.2, 4.8, 5.5, 6.9, 5.1, 2.4]

plt.figure(figsize=(8, 5))
plt.plot(days, kilolitres, color="darkgreen", marker="o")
plt.title("Water used in the school, one week")
plt.xlabel("Day")
plt.ylabel("Water used (kilolitres)")
plt.ylim(0, 8)
plt.savefig("19-line-water-used.png", dpi=150)
plt.show()
```

**Saved chart**19-line-water-used.png![Line plot of water used from Monday to Saturday, highest on Thursday at 6.9 kilolitres and lowest on Saturday at 2.4](/images/board-prep/cbse-class-12-informatics-practices-practical-file/19-line-water-used.png)

Line plot of water used from Monday to Saturday, highest on Thursday at 6.9 kilolitres and lowest on Saturday at 2.4.

**Why it works:** a line suits values that follow one another in time. `ylim(0, 8)` starts the scale at zero, so Thursday does not look more extreme than it is.

### Program 20: two lines with a legend

**Aim:** To compare the electricity used by labs and by classrooms over six months from a DataFrame.

***Program 20**Matplotlib*

```
# Program 20: two lines and a legend, from a DataFrame
import pandas as pd
import matplotlib.pyplot as plt

power = pd.DataFrame({
    "Month": ["Apr", "May", "Jun", "Jul", "Aug", "Sep"],
    "Labs": [410, 465, 180, 440, 455, 430],
    "Classrooms": [620, 540, 150, 590, 605, 615]})

plt.figure(figsize=(8, 5))
plt.plot(power["Month"], power["Labs"], color="navy",
         marker="s", label="Labs")
plt.plot(power["Month"], power["Classrooms"], color="crimson",
         linestyle="--", marker="o", label="Classrooms")
plt.title("Electricity used, April to September")
plt.xlabel("Month")
plt.ylabel("Units")
plt.ylim(0, 700)
plt.legend()
plt.savefig("20-two-lines-electricity.png", dpi=150)
plt.show()
```

**Saved chart**20-two-lines-electricity.png![Two line plots of electricity units from April to September: labs solid navy and classrooms dashed red, both falling sharply in June](/images/board-prep/cbse-class-12-informatics-practices-practical-file/20-two-lines-electricity.png)

Two line plots of electricity units from April to September: labs solid navy and classrooms dashed red, both falling sharply in June.

**Why it works:** `label` gives each line a name and `legend()` displays the names. Different markers and line styles keep the two apart even in a black and white print.

### Program 21: bar graph, subject-wise

**Aim:** To find the average marks in each subject of a result and plot them as a bar graph.

***Program 21**Matplotlib*

```
# Program 21: subject-wise bar graph of a result
import pandas as pd
import matplotlib.pyplot as plt

result = pd.DataFrame({
    "Section": ["A", "A", "A", "B", "B", "B"],
    "IP": [88, 73, 91, 65, 84, 79],
    "Accounts": [62, 58, 81, 77, 69, 73],
    "Economics": [71, 80, 66, 74, 85, 68]})
result.to_csv("result.csv", index=False)   # for Program 22

subjects = ["IP", "Accounts", "Economics"]
averages = result[subjects].mean()
print(averages)

plt.figure(figsize=(8, 5))
plt.bar(subjects, averages, width=0.5, color="teal")
plt.title("Average marks in each subject")
plt.xlabel("Subject")
plt.ylabel("Average marks out of 100")
plt.ylim(0, 100)
plt.savefig("21-bar-subject-average.png", dpi=150)
plt.show()
```

**Saved chart**21-bar-subject-average.png![Bar graph of average marks: IP 80, Accounts 70, Economics 74](/images/board-prep/cbse-class-12-informatics-practices-practical-file/21-bar-subject-average.png)

Bar graph of average marks: IP 80, Accounts 70, Economics 74.

***Also printed**text output*

```
IP           80.0
Accounts     70.0
Economics    74.0
dtype: float64
```

**Why it works:** `mean()` on three columns returns a Series with one average per subject, and its values become the bar heights. The same data is saved for the next program.

### Program 22: bar graph, class-wise

**Aim:** To compare two sections in three subjects with bars placed side by side.

***Program 22**Matplotlib*

```
# Program 22: class-wise comparison, two bars per subject
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

result = pd.read_csv("result.csv")
subjects = ["IP", "Accounts", "Economics"]
sec_a = result[result["Section"] == "A"][subjects].mean()
sec_b = result[result["Section"] == "B"][subjects].mean()

x = np.arange(len(subjects))               # 0, 1, 2
plt.figure(figsize=(8, 5))
plt.bar(x - 0.2, sec_a, width=0.4, color="orange",
        label="Section A")
plt.bar(x + 0.2, sec_b, width=0.4, color="purple",
        label="Section B")
plt.xticks(x, subjects)
plt.title("Section A and Section B compared")
plt.xlabel("Subject")
plt.ylabel("Average marks")
plt.ylim(0, 100)
plt.legend()
plt.savefig("22-bar-two-sections.png", dpi=150)
plt.show()
```

**Saved chart**22-bar-two-sections.png![Side by side bars of section A and section B in IP, Accounts and Economics; section A is higher only in IP](/images/board-prep/cbse-class-12-informatics-practices-practical-file/22-bar-two-sections.png)

Side by side bars of section A and section B in IP, Accounts and Economics; section A is higher only in IP.

**Why it works:** the bars of one section are moved 0.2 to the left and those of the other 0.2 to the right. With a width of 0.4 they touch but never overlap. `xticks()` puts subject names back on the axis.

### Program 23: histogram

**Aim:** To show the distribution of the marks of 28 students in bins of ten marks.

***Program 23**Matplotlib*

```
# Program 23: histogram of marks
import pandas as pd
import matplotlib.pyplot as plt

marks = pd.Series([38, 45, 47, 52, 55, 56, 58, 61, 62, 63,
                   64, 66, 67, 68, 71, 72, 73, 75, 76, 78,
                   79, 81, 84, 85, 88, 91, 93, 97])
edges = [30, 40, 50, 60, 70, 80, 90, 100]

plt.figure(figsize=(8, 5))
counts, used, bars = plt.hist(marks, bins=edges, color="gold",
                              edgecolor="black")
print("Students in each bin:", counts)
plt.title("Marks of 28 students")
plt.xlabel("Marks")
plt.ylabel("Number of students")
plt.xticks(edges)
plt.savefig("23-histogram-marks.png", dpi=150)
plt.show()
```

**Saved chart**23-histogram-marks.png![Histogram of the marks of 28 students in bins of ten, tallest for 60 to 70 and 70 to 80 with seven students each](/images/board-prep/cbse-class-12-informatics-practices-practical-file/23-histogram-marks.png)

Histogram of the marks of 28 students in bins of ten, tallest for 60 to 70 and 70 to 80 with seven students each.

***Also printed**text output*

```
Students in each bin: [1. 2. 4. 7. 7. 4. 3.]
```

**Why it works:** a histogram counts how many values fall in each interval. A mark equal to an inner edge, such as 60, is counted in the bin to its right, while the last bin includes 100. The seven counts add to 28.

The suggested list also asks you to take data of your own interest from an open source such as data.gov.in and plot it. Replace the lists in Program 20 with the columns of the file you download, name the source under the chart, and you have that entry too. Colours, legends and axis limits are explained one at a time on [Matplotlib charts for Class 12 IP](/cbse-class-12-informatics-practices-matplotlib-charts).

Q6. And the database half?

## Class 12 IP practical file, MySQL: 19 SQL entries with results

Run them in this order, since each entry works on the table left by the one before. Nineteen entries hold far more than 15 single queries, so a school that counts every statement is covered too.

### Query 1: create a database and a table

**Aim:** To create a database and a STUDENT table with the student id as primary key, and display its structure.

***Query 1**SQL*

```
CREATE DATABASE ip_file;
USE ip_file;
CREATE TABLE STUDENT (
  sid    INT PRIMARY KEY,
  sname  VARCHAR(20) NOT NULL,
  hcode  CHAR(2),
  marks  INT,
  dob    DATE);
DESC STUDENT;
```

***Result**MySQL*

```
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int         | NO   | PRI | NULL    |       |
| sname | varchar(20) | NO   |     | NULL    |       |
| hcode | char(2)     | YES  |     | NULL    |       |
| marks | int         | YES  |     | NULL    |       |
| dob   | date        | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
```

**Why it works:** the primary key column shows NO under Null even though NOT NULL was not typed for it. Some older versions print `int(11)` in place of `int`.

### Query 2: insert rows and display them

**Aim:** To insert six students and display the whole table.

***Query 2**SQL*

```
INSERT INTO STUDENT VALUES
 (1, 'Aarohi', 'H1', 86, '2009-03-14'),
 (2, 'Bilal',  'H2', 72, '2009-11-02'),
 (3, 'Charu',  'H1', 93, '2008-12-25'),
 (4, 'Denzil', 'H3', NULL, '2009-07-30'),
 (5, 'Esha',   'H2', 81, '2009-03-03'),
 (6, 'Faiz',   'H3', 58, '2009-01-19');
SELECT * FROM STUDENT;
```

***Result**MySQL*

```
+-----+--------+-------+-------+------------+
| sid | sname  | hcode | marks | dob        |
+-----+--------+-------+-------+------------+
|   1 | Aarohi | H1    |    86 | 2009-03-14 |
|   2 | Bilal  | H2    |    72 | 2009-11-02 |
|   3 | Charu  | H1    |    93 | 2008-12-25 |
|   4 | Denzil | H3    |  NULL | 2009-07-30 |
|   5 | Esha   | H2    |    81 | 2009-03-03 |
|   6 | Faiz   | H3    |    58 | 2009-01-19 |
+-----+--------+-------+-------+------------+
```

**Why it works:** one INSERT can carry several rows separated by commas. Text and dates need quotes; NULL must not have any, or it would be a four-letter word.

### Query 3: a new student with some columns only

**Aim:** To insert the details of a new student whose house and marks are not yet known.

***Query 3**SQL*

```
INSERT INTO STUDENT (sid, sname, dob)
VALUES (7, 'Gunjan', '2009-09-05');
SELECT * FROM STUDENT WHERE sid = 7;
```

***Result**MySQL*

```
+-----+--------+-------+-------+------------+
| sid | sname  | hcode | marks | dob        |
+-----+--------+-------+-------+------------+
|   7 | Gunjan | NULL  |  NULL | 2009-09-05 |
+-----+--------+-------+-------+------------+
```

**Why it works:** columns left out of the list become NULL, which is allowed here because only sid and sname refuse it.

### Query 4: update a row

**Aim:** To fill in the house and marks of the new student.

***Query 4**SQL*

```
UPDATE STUDENT SET hcode = 'H1', marks = 64
WHERE sid = 7;
SELECT sid, sname, hcode, marks FROM STUDENT
WHERE hcode = 'H1';
```

***Result**MySQL*

```
+-----+--------+-------+-------+
| sid | sname  | hcode | marks |
+-----+--------+-------+-------+
|   1 | Aarohi | H1    |    86 |
|   3 | Charu  | H1    |    93 |
|   7 | Gunjan | H1    |    64 |
+-----+--------+-------+-------+
```

**Why it works:** WHERE picks the one row. Without it, all seven students would move to house H1 with 64 marks.

### Query 5: delete a row

**Aim:** To delete the details of one student.

***Query 5**SQL*

```
DELETE FROM STUDENT WHERE sid = 6;
SELECT sid, sname FROM STUDENT;
```

***Result**MySQL*

```
+-----+--------+
| sid | sname  |
+-----+--------+
|   1 | Aarohi |
|   2 | Bilal  |
|   3 | Charu  |
|   4 | Denzil |
|   5 | Esha   |
|   7 | Gunjan |
+-----+--------+
```

**Why it works:** DELETE removes rows and leaves the table. The other sid values do not shift, so 7 stays 7.

### Query 6: WHERE with >, BETWEEN and IS NULL

**Aim:** To list students with more than 80 marks, with marks from 60 to 81, and with no marks entered.

***Query 6**SQL*

```
SELECT sid, sname, marks FROM STUDENT
WHERE marks > 80;
SELECT sname, marks FROM STUDENT
WHERE marks BETWEEN 60 AND 81;
SELECT sname FROM STUDENT WHERE marks IS NULL;
```

***Result**MySQL*

```
+-----+--------+-------+
| sid | sname  | marks |
+-----+--------+-------+
|   1 | Aarohi |    86 |
|   3 | Charu  |    93 |
|   5 | Esha   |    81 |
+-----+--------+-------+

+--------+-------+
| sname  | marks |
+--------+-------+
| Bilal  |    72 |
| Esha   |    81 |
| Gunjan |    64 |
+--------+-------+

+--------+
| sname  |
+--------+
| Denzil |
+--------+
```

**Why it works:** BETWEEN includes both ends, so Esha with 81 is in. A test for NULL must use IS NULL: `marks = NULL` returns no row.

### Query 7: ORDER BY on one and two columns

**Aim:** To list marks in descending order, and names sorted inside each house.

***Query 7**SQL*

```
SELECT sid, marks FROM STUDENT
ORDER BY marks DESC;
SELECT hcode, sname FROM STUDENT
ORDER BY hcode, sname DESC;
```

***Result**MySQL*

```
+-----+-------+
| sid | marks |
+-----+-------+
|   3 |    93 |
|   1 |    86 |
|   5 |    81 |
|   2 |    72 |
|   7 |    64 |
|   4 |  NULL |
+-----+-------+

+-------+--------+
| hcode | sname  |
+-------+--------+
| H1    | Gunjan |
| H1    | Charu  |
| H1    | Aarohi |
| H2    | Esha   |
| H2    | Bilal  |
| H3    | Denzil |
+-------+--------+
```

**Why it works:** DESC belongs only to the column it follows, so houses rise while names fall. MySQL places NULL last in descending order.

### Query 8: minimum, maximum, sum and average

**Aim:** To find the minimum, maximum, sum and average of the marks.

***Query 8**SQL*

```
SELECT MIN(marks), MAX(marks), SUM(marks), AVG(marks)
FROM STUDENT;
```

***Result**MySQL*

```
+------------+------------+------------+------------+
| MIN(marks) | MAX(marks) | SUM(marks) | AVG(marks) |
+------------+------------+------------+------------+
|         64 |         93 |        396 |    79.2000 |
+------------+------------+------------+------------+
```

**Why it works:** aggregate functions skip NULL. The average is 396 divided by 5 students, not by 6.

### Query 9: three kinds of COUNT

**Aim:** To count all rows, the students who have marks, and the different houses.

***Query 9**SQL*

```
SELECT COUNT(*), COUNT(marks), COUNT(DISTINCT hcode)
FROM STUDENT;
```

***Result**MySQL*

```
+----------+--------------+-----------------------+
| COUNT(*) | COUNT(marks) | COUNT(DISTINCT hcode) |
+----------+--------------+-----------------------+
|        6 |            5 |                     3 |
+----------+--------------+-----------------------+
```

**Why it works:** `COUNT(*)` counts rows, `COUNT(marks)` counts values that are not NULL, and DISTINCT counts each house once.

### Query 10: customers from each country

**Aim:** To create a CUSTOMER table and find the number of customers from each country.

***Query 10**SQL*

```
CREATE TABLE CUSTOMER (
  cid INT PRIMARY KEY, cname VARCHAR(20),
  country VARCHAR(15));
INSERT INTO CUSTOMER VALUES
 (101, 'Lakshmi', 'India'), (102, 'Omar', 'Oman'),
 (103, 'Pranav', 'India'),  (104, 'Sita', 'Nepal'),
 (105, 'Rashid', 'Oman'),   (106, 'Uma', 'India');
SELECT country, COUNT(*) FROM CUSTOMER
GROUP BY country;
```

***Result**MySQL*

```
+---------+----------+
| country | COUNT(*) |
+---------+----------+
| India   |        3 |
| Oman    |        2 |
| Nepal   |        1 |
+---------+----------+
```

**Why it works:** GROUP BY makes one group per country and `COUNT(*)` runs once for every group, so three countries give three rows.

### Query 11: HAVING and an alias

**Aim:** To display only the countries with more than one customer, largest first.

***Query 11**SQL*

```
SELECT country, COUNT(*) AS total FROM CUSTOMER
GROUP BY country HAVING COUNT(*) > 1
ORDER BY total DESC;
```

***Result**MySQL*

```
+---------+-------+
| country | total |
+---------+-------+
| India   |     3 |
| Oman    |     2 |
+---------+-------+
```

**Why it works:** HAVING tests a finished group, and Nepal has just one customer, so it goes. The alias total can be used in ORDER BY.

### Query 12: WHERE, GROUP BY, HAVING and ORDER BY together

**Aim:** To find houses whose average is above 75, with the number of students marked.

***Query 12**SQL*

```
SELECT hcode, AVG(marks), COUNT(*) FROM STUDENT
WHERE marks IS NOT NULL
GROUP BY hcode HAVING AVG(marks) > 75
ORDER BY AVG(marks) DESC;
```

***Result**MySQL*

```
+-------+------------+----------+
| hcode | AVG(marks) | COUNT(*) |
+-------+------------+----------+
| H1    |    81.0000 |        3 |
| H2    |    76.5000 |        2 |
+-------+------------+----------+
```

**Why it works:** WHERE removes single rows first, so Denzil is not counted. Groups are then formed, HAVING filters them and ORDER BY comes last.

### Query 13: POWER, MOD and ROUND

**Aim:** To use the three math functions on numbers and on a column.

***Query 13**SQL*

```
SELECT POWER(3, 4), MOD(86, 7);
SELECT ROUND(153.478, 2), ROUND(153.478, 0),
       ROUND(153.478, -2);
SELECT sname, ROUND(marks / 3, 1) FROM STUDENT
WHERE hcode = 'H1';
```

***Result**MySQL*

```
+-------------+------------+
| POWER(3, 4) | MOD(86, 7) |
+-------------+------------+
|          81 |          2 |
+-------------+------------+

+-------------------+-------------------+--------------------+
| ROUND(153.478, 2) | ROUND(153.478, 0) | ROUND(153.478, -2) |
+-------------------+-------------------+--------------------+
|            153.48 |               153 |                200 |
+-------------------+-------------------+--------------------+

+--------+---------------------+
| sname  | ROUND(marks / 3, 1) |
+--------+---------------------+
| Aarohi |                28.7 |
| Charu  |                31.0 |
| Gunjan |                21.3 |
+--------+---------------------+
```

**Why it works:** 86 divided by 7 leaves 2. A negative second argument rounds to the left of the point, so 153.478 becomes 200 with -2.

### Query 14: case, length, left and right

**Aim:** To change the case of names, find their lengths and take letters from either end.

***Query 14**SQL*

```
SELECT UCASE(sname), LCASE(sname), LENGTH(sname)
FROM STUDENT WHERE sid <= 3;
SELECT sname, LEFT(sname, 3), RIGHT(sname, 2)
FROM STUDENT WHERE hcode = 'H2';
```

***Result**MySQL*

```
+--------------+--------------+---------------+
| UCASE(sname) | LCASE(sname) | LENGTH(sname) |
+--------------+--------------+---------------+
| AAROHI       | aarohi       |             6 |
| BILAL        | bilal        |             5 |
| CHARU        | charu        |             5 |
+--------------+--------------+---------------+

+-------+----------------+-----------------+
| sname | LEFT(sname, 3) | RIGHT(sname, 2) |
+-------+----------------+-----------------+
| Bilal | Bil            | al              |
| Esha  | Esh            | ha              |
+-------+----------------+-----------------+
```

**Why it works:** these functions change only what is displayed; the stored names are untouched.

### Query 15: MID, SUBSTR, INSTR and the TRIM family

**Aim:** To take out a part of a string, find a letter in it and remove spaces.

***Query 15**SQL*

```
SELECT MID('Practices', 4, 3), SUBSTR('Practices', -4, 2);
SELECT sname, INSTR(sname, 'a') FROM STUDENT;
SELECT LENGTH('  ip  ') AS plain,
 LENGTH(LTRIM('  ip  ')) AS lt,
 LENGTH(RTRIM('  ip  ')) AS rt,
 LENGTH(TRIM('  ip  ')) AS both_sides;
```

***Result**MySQL*

```
+------------------------+----------------------------+
| MID('Practices', 4, 3) | SUBSTR('Practices', -4, 2) |
+------------------------+----------------------------+
| cti                    | ic                         |
+------------------------+----------------------------+

+--------+-------------------+
| sname  | INSTR(sname, 'a') |
+--------+-------------------+
| Aarohi |                 1 |
| Bilal  |                 4 |
| Charu  |                 3 |
| Denzil |                 0 |
| Esha   |                 4 |
| Gunjan |                 5 |
+--------+-------------------+

+-------+------+------+------------+
| plain | lt   | rt   | both_sides |
+-------+------+------+------------+
|     6 |    4 |    4 |          2 |
+-------+------+------+------------+
```

**Why it works:** SQL counts characters from 1, unlike Python. A negative start counts from the right end. INSTR gives 0 when the letter is absent, as for Denzil, and it ignores case here, so Aarohi gives 1.

### Query 16: date functions

**Aim:** To display parts of the dates of birth, and the month and day names of those born in March.

***Query 16**SQL*

```
SELECT sname, DAY(dob), MONTH(dob), YEAR(dob)
FROM STUDENT WHERE sid < 4;
SELECT sname, MONTHNAME(dob), DAYNAME(dob)
FROM STUDENT WHERE MONTH(dob) = 3;
SELECT DATE('2027-01-18 09:40:00');
```

***Result**MySQL*

```
+--------+----------+------------+-----------+
| sname  | DAY(dob) | MONTH(dob) | YEAR(dob) |
+--------+----------+------------+-----------+
| Aarohi |       14 |          3 |      2009 |
| Bilal  |        2 |         11 |      2009 |
| Charu  |       25 |         12 |      2008 |
+--------+----------+------------+-----------+

+--------+----------------+--------------+
| sname  | MONTHNAME(dob) | DAYNAME(dob) |
+--------+----------------+--------------+
| Aarohi | March          | Saturday     |
| Esha   | March          | Tuesday      |
+--------+----------------+--------------+

+-----------------------------+
| DATE('2027-01-18 09:40:00') |
+-----------------------------+
| 2027-01-18                  |
+-----------------------------+
```

**Why it works:** DAYNAME works out the weekday from the date itself. `DATE()` keeps the date part of a date and time. For `NOW()` paste the result from your own screen, with its time.

### Query 17: equi-join of two tables

**Aim:** To create a HOUSE table and display each student with the house name.

***Query 17**SQL*

```
CREATE TABLE HOUSE (
  hcode CHAR(2) PRIMARY KEY, hname VARCHAR(10));
INSERT INTO HOUSE VALUES
 ('H1', 'Ganga'), ('H2', 'Kaveri'), ('H3', 'Narmada');
SELECT sname, hname FROM STUDENT, HOUSE
WHERE STUDENT.hcode = HOUSE.hcode;
```

***Result**MySQL*

```
+--------+---------+
| sname  | hname   |
+--------+---------+
| Aarohi | Ganga   |
| Bilal  | Kaveri  |
| Charu  | Ganga   |
| Denzil | Narmada |
| Esha   | Kaveri  |
| Gunjan | Ganga   |
+--------+---------+
```

**Why it works:** the WHERE line matches the common column. Remove it and every student pairs with every house: 6 times 3, which is 18 rows.

### Query 18: join with GROUP BY

**Aim:** To find the top marks and the number of members in each house, by name.

***Query 18**SQL*

```
SELECT hname, MAX(marks) AS top, COUNT(*) AS members
FROM STUDENT, HOUSE
WHERE STUDENT.hcode = HOUSE.hcode
GROUP BY hname ORDER BY members DESC, hname;
```

***Result**MySQL*

```
+---------+------+---------+
| hname   | top  | members |
+---------+------+---------+
| Ganga   |   93 |       3 |
| Kaveri  |   81 |       2 |
| Narmada | NULL |       1 |
+---------+------+---------+
```

**Why it works:** Narmada’s only member has NULL marks, so MAX returns NULL while `COUNT(*)` still returns 1. This one row can start a whole viva.

### Query 19: ALTER TABLE and DROP TABLE

**Aim:** To add a column to a table, check it, remove it, and then drop the table.

***Query 19**SQL*

```
ALTER TABLE CUSTOMER ADD phone VARCHAR(10);
DESC CUSTOMER;
ALTER TABLE CUSTOMER DROP phone;
DROP TABLE CUSTOMER;
```

***Result**MySQL*

```
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| cid     | int         | NO   | PRI | NULL    |       |
| cname   | varchar(20) | YES  |     | NULL    |       |
| country | varchar(15) | YES  |     | NULL    |       |
| phone   | varchar(10) | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
```

**Why it works:** ALTER changes the structure and DROP TABLE removes structure and data together. Keep this entry last: after it, queries 10 and 11 cannot run.

Want queries to solve before seeing a result? Try [Class 12 IP SQL questions with answers](/cbse-class-12-informatics-practices-sql-questions).

Q7. Can you defend the file?

## Questions an examiner can ask from this IP practical file

The hardest questions change one line and ask what happens. Rehearse with these. Every answer here that names a result or an error was tried on the computer.

### pandas and Matplotlib

1. **In Program 1, pass `index=["Fri", "Sat"]` as well.** Fri prints 61.0 and Sat prints NaN, since the dictionary has no key Sat.
2. **How would Program 6 show the lowest quarter?**`minutes[minutes < minutes.quantile(0.25)]`, which leaves C and G.
3. **In Program 8, what does `labelled.loc[0]` give?** A KeyError, because the row labels are now b1, b2 and b3. `labelled.iloc[0]` works.
4. **Remove `.sum()` in Program 9. What is totals?** A grouped object with nothing calculated yet, so printing it shows no totals.
5. **You call `stock.drop("rack", axis=1)` and do not assign it.** The original still has the rack column.
6. **What if the column to drop is not there?** A KeyError saying it is not found in axis.
7. **How do `result["IP"]` and `result[["IP"]]` differ?** The first is a Series with one dimension, the second a DataFrame with two.
8. **Could Program 23 be a bar graph?** Not with the raw marks. A bar graph compares separate categories; a histogram shows how numbers spread over intervals, which is why its bars touch.

### SQL

1. **Degree and cardinality of STUDENT after Query 5?** Degree 5 (columns), cardinality 6 (rows).
2. **Why can `HAVING` not be replaced by WHERE in Query 11?** WHERE runs before groups exist, so it cannot test COUNT(*).
3. **DELETE without WHERE, or DROP TABLE?** DELETE empties the table and keeps its structure. DROP removes both.
4. **What is the foreign key idea in Query 17?** hcode in STUDENT refers to the primary key hcode of HOUSE. We matched them in the query without declaring a constraint.
5. **Is `CHAR(2)` better than `VARCHAR(2)` for hcode?** It suits codes of a fixed length. Names vary, so they use VARCHAR.
6. **Which functions here act on one row and which on many?** UCASE, MID, ROUND and YEAR work row by row. SUM, AVG, MIN, MAX and COUNT work on a group.

A bigger bank, including networks and societal impacts, is on [Class 12 IP viva questions](/cbse-class-12-informatics-practices-viva-questions).

### Make the 42 entries your own

1. #### Swap the data before you type

  Keep the idea and change the subject: your own colony, sports team, bus route or kitchen shelf. New data means a new output, which nobody else in class can have.
2. #### Predict, then run

  Write what you expect in pencil before pressing run. Where you were wrong, add a comment explaining the result. Those comments are your viva notes.
3. #### Keep one folder per section

  Name files p01.py, c19.py and so on, and store the SQL in one script that can be run again from the top if a table is spoilt.
4. #### Then make the PDF

  Code, output and chart go on facing pages with the index in front. Printing this page to PDF from the browser gives you a copy to study from, not one to submit.

One to one, at your own timing

## Finish the IP file with a teacher, entry by entry

Try a class before you decide. In a priority demo the student gets a full paid live class at the slot your family chooses, a written skill report follows, and the fee is adjusted against the first month if you enrol. A free demo class is available as well. After that, classes are personalised one to one, billed by the month with no admission fee.

Before you enrol · Try a class

### Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

- One pandas entry and one SQL entry typed live, with your own data
- A chart drawn, labelled and saved as a PNG
- A check on how many of the 34 required entries are still missing
- The written report names the topics to repair first

[Book a priority demo](/book-demo)

The classes · Choose your own timing

### Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

- You choose the days and the hour, and can change them in exam weeks
- pandas, charts and SQL taught as the entries are written, not after
- Timed runs of the 8-mark Python part and the 7-mark SQL part
- File, project and viva prepared together before the practical date

Ask for a personalised plan

Stop at the end of any month. If only the SQL section is pending, tell us at the demo and the plan starts there. The monthly fee is displayed above in your currency.

IP students abroad

## Help with the 065 practical file outside India

CBSE schools in the Gulf, Nepal, Singapore and elsewhere follow the same 065 document, so the same 15, 4 and 15 apply. Pick an evening slot by your own clock.

| Where you live | Time difference | Usual class window, local time | Format |
| --- | --- | --- | --- |
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 1-on-1 |

Weekly subject tuition alongside the practical work is described on [CBSE Class 12 computer tuition](/computer-science-class-12-cbse).

What families say

## Rated 4.9 across 547 Google reviews

Real reviews from real families. We neither write nor commission them.

★★★★★

"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."

Ria Mukherjee

Parent

★★★★★

"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."

Samriddha Mondal

Student

★★★★★

"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."

Vansh Agarwal

Student

★★★★★

"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."

Sonam Oswal

Parent of Dhairya

★★★★★

"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."

Sonu Goyal

Parent

★★★★★

"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."

Ritu Kedia

Parent

The rest of the Class 12 series

## More for Class 12 Informatics Practices

Every page in the CBSE Class 12 Informatics Practices series, grouped by what you need.

### Practicals, project and viva

- [Class 12 IP project with source code](/cbse-class-12-informatics-practices-project)
- [Class 12 IP project topics](/cbse-class-12-informatics-practices-project-topics)
- [Class 12 IP viva questions](/cbse-class-12-informatics-practices-viva-questions)

### Exam, papers and marks

- [Class 12 IP sample paper practice](/cbse-class-12-informatics-practices-sample-paper-2026-27)
- [Class 12 IP syllabus and pattern](/cbse-class-12-informatics-practices-syllabus-and-paper-pattern)
- [Class 12 IP important questions](/cbse-class-12-informatics-practices-important-questions)

### Questions and practice

- [Class 12 IP MCQ test](/cbse-class-12-informatics-practices-mcq-test)
- [Class 12 IP SQL questions](/cbse-class-12-informatics-practices-sql-questions)

### Chapter by chapter

- [Pandas Series Class 12 IP](/cbse-class-12-informatics-practices-pandas-series)
- [DataFrame Class 12 IP](/cbse-class-12-informatics-practices-dataframe)
- [Matplotlib and charts Class 12 IP](/cbse-class-12-informatics-practices-matplotlib-charts)
- [Computer networks Class 12 IP](/cbse-class-12-informatics-practices-computer-networks)
- [Societal impacts Class 12 IP](/cbse-class-12-informatics-practices-societal-impacts)

### Revision and help

- [Class 12 IP crash course](/cbse-class-12-informatics-practices-crash-course)

**CBSE Class 12 Computer Science (083):** [Class 12 CS viva questions](/cbse-class-12-computer-science-viva-questions)  [Class 12 CS sample paper practice](/cbse-class-12-computer-science-sample-paper-2026-27)  [Class 12 CS project with source code](/cbse-class-12-computer-science-project-python-mysql)  [Class 12 CS important questions](/cbse-class-12-computer-science-important-questions)

**CBSE Class 12 Information Technology (802):** [IT 802 practical and project file](/cbse-class-12-it-802-practical-and-project-file)  [IT 802 Java notes and programs](/cbse-class-12-it-802-java-programs)  [IT 802 notes](/cbse-class-12-it-802-notes)

**CBSE Class 11 CS, IP and AI:** [Class 11 CS practical file](/cbse-class-11-computer-science-practical-file)  [Class 11 IP practical file](/cbse-class-11-informatics-practices-practical-file)  [CS or IP in Class 11](/computer-science-or-informatics-practices-class-11)

**ISC Computer Science (868):** [ISC Class 12 CS syllabus 2027](/isc-class-12-computer-science-syllabus-2027)  [ISC Class 12 CS practice paper](/isc-class-12-computer-science-specimen-paper-practice)  [ISC Class 12 practical questions solved](/isc-class-12-computer-science-practical-questions)  [ISC Boolean algebra and K-maps](/isc-class-12-computer-science-boolean-algebra)

**Program lists with output:** [Class 12 practical file programs](/blog/python-practical-file-class-12)  [Python programs for Class 11 CS and IP](/blog/python-programs-for-class-11)

IP file questions

## Class 12 IP practical file: questions students ask

### How many programs are there in the Class 12 IP practical file?

The CBSE 2026-27 syllabus asks for a minimum of 15 programs based on pandas, 4 based on Matplotlib and 15 SQL queries, so 34 entries in all. The file carries 5 marks. Adding two or three extra in each group protects you if an entry is rejected; this page has 18, 5 and 19.

### How can I get a Class 12 IP practical file PDF?

Use the Print option of your browser on this page and choose to save as PDF; the code, outputs, charts and SQL results are all included. Treat it as a study copy. The file you hand in should carry your own data and your own runs, because any page of it can come up in the viva.

### What is the format of the IP practical file for Class 12?

A title page, certificate, index and then three sections: pandas programs, Matplotlib programs and SQL queries. Give each entry a number, date, aim, code and output. CBSE fixes the minimum number of entries but not the layout, so follow any format your school provides.

### How are the 30 practical marks in Class 12 IP divided?

Programs using pandas and Matplotlib carry 8 marks, SQL queries 7, the practical file 5, project work 5 and the viva voce 5, as printed in the 2026-27 Informatics Practices syllabus. The theory paper of 70 marks is separate.

### Which graphs should be in the IP practical file?

Line plots, bar graphs and histograms are the three types named in the Class 12 IP syllabus. Include at least one of each and add titles, axis labels and a legend where there is more than one series. Pie charts and scatter plots are not listed, so they do not need to be there.

### Do I need Python and MySQL connectivity in the IP file?

The practical file line for Class 12 IP asks only for pandas programs, Matplotlib programs and SQL queries. Programs that connect Python to MySQL are a requirement of Computer Science 083. If your IP teacher wants one, add it as an extra entry.

### Can SQL results be handwritten in the practical file?

The syllabus does not say, so ask your school. Whichever way you present them, copy the result grid from MySQL exactly, including NULL and the column headings, so the page agrees with the screen if you are asked to run the query again.

### Why does my pandas output look different from the book?

Usually it is the version. In pandas 2 a text column shows dtype object, and in pandas 3 it shows str. Column spacing can also differ. Paste what your own computer prints and write the version on the software page.

### What happens if my practical file is incomplete?

The file is 5 of the 30 practical marks, and CBSE does not publish how marks are cut for missing entries; the examiners decide. What is certain is that the minimum of 15, 4 and 15 is printed in the syllabus, so complete the counts first and improve the pages afterwards.

### When is the Class 12 IP practical exam in 2027?

CBSE has scheduled 2026-27 practicals from 1 January 2027, while winter-bound schools have 9 November to 19 December 2026. Each school fixes its own day. The Informatics Practices theory paper is on 31 March 2027.

### Can I use the same programs as my friend?

The same aim is normal, since every file follows one syllabus. The same data and the same output are the problem, as neither of you can then show that the work is yours. Change the data set, the names and the comments, then run it yourself.

### Will you write my IP practical file for me?

No. In our live one to one classes the student types and runs each entry while the teacher explains and asks questions, so the file can be defended in the viva. Start with a priority demo at your chosen slot, or take the free demo class.

Start

## Bring one unfinished entry to the first class

Tell us how many of the 15, 4 and 15 are ready and which chapter feels shaky. The first class is spent on one real entry, from a blank editor to an output the student can explain.

Practicals close? A priority demo gives you a slot of your choice, a written report and a clear list of what is left. Its fee is adjusted in the first month if you continue.

[WhatsApp us](https://wa.me/919123366161?text=Hello%20Modern%20Age%20Coders.%20I%20need%20one%20to%20one%20help%20with%20the%20CBSE%20Class%2012%20Informatics%20Practices%20practical%20file.) · [+91 91233 66161](tel:+919123366161) · [connect@modernagecoders.com](mailto:connect@modernagecoders.com)

Every class is live video. The form requests a callback and reserves nothing.

### Want it sooner? Book a priority demo

A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.

[Book a priority demo](/book-demo)

## Keep exploring Modern Age Coders

### By class and age

- [Class 12 Computer Science Syllabus 2026-27 (083) Explained](/cbse-class-12-computer-science-syllabus-2026-27)
- [Stack Class 12 Computer Science: Push, Pop and Questions](/cbse-class-12-computer-science-stack)
- [Class 12 IT 802 Sample Paper with Solutions, 2026-27](/cbse-class-12-it-802-sample-paper)
- [Class 12 Computer Science SQL Questions with Output (083)](/cbse-class-12-computer-science-sql-queries)
- [Class 12 IT 802 Syllabus 2026-27: Units, Marks and Dates](/cbse-class-12-it-802-syllabus-2026-27)
- [CBSE Computational Thinking for Classes 3-5](/cbse-computational-thinking-classes-3-to-5)
- [Class 12 IP Syllabus 2026-27, Paper Pattern and Exam Date](/cbse-class-12-informatics-practices-syllabus-and-paper-pattern)
- [BC Grade 10 Numeracy Assessment Practice: Format, Questions](/bc-grade-10-numeracy-assessment-practice)
- [BC ADST Curriculum: Coding by Grade, Kindergarten to Grade 9](/bc-adst-curriculum-coding-by-grade)

### Learn more

- [Backend Development for Teens: Node, APIs and Databases](/courses/backend-coding-masterclass-for-teens)
- [Class 10 AI Tuition Delhi: Live CBSE 417 Classes Online](/class-10-ai-tuition-delhi)
- [Computer Science Class 11-12: CBSE Python & ICSE/ISC Java](/courses/cbse-icse-computer-science-class-11-12-python-java-complete-course)
- [Data Analysis Course: Excel, SQL, Python & BI](/courses/data-analysis-mastery-course-college)

### Free resources

- [SQL Tutorial: Databases, Basics to Advanced](/resources/sql)
- [Setting Up MySQL and Your First Query](/resources/sql/setting-up-mysql-and-first-query)
- [Subqueries (Nested Queries) and EXISTS](/resources/sql/subqueries-and-nested-queries)
- [Window Functions](/resources/sql/window-functions)

### From the blog

- [String Handling in Java: The ICSE and CBSE Guide](/blog/string-handling-in-java)
- [20 Python Programs for CBSE Class 12 Board Exam (083)](/blog/python-programs-for-cbse-class-12)
- [50 Important Java Programs for ICSE Class 10 Boards](/blog/50-java-programs-for-icse-class-10)

### Start here

- [Browse every live course at Modern Age Coders](/courses)
- [Try a free trial class with a Modern Age Coders mentor](/free-trial)

---

*Canonical: https://learn.modernagecoders.com/cbse-class-12-informatics-practices-practical-file*
