0% found this document useful (0 votes)
2 views22 pages

Python Practical File

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views22 pages

Python Practical File

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Programming - Practical File

PYTHON PROGRAMMING
PRACTICAL FILE
Session 2026 - 2027

Submitted by:
Name: ____________________________
Class / Section: ___________________
Roll Number: ______________________

Submitted to:
Subject Teacher: __________________

Page 1 of 22
Python Programming - Practical File

INDEX

[Link]. Program Title Page

1 Words separated by #

2 Vowels / Consonants / Uppercase / Lowercase count

3 Remove lines containing 'a'

4 Binary file: Name & Roll Number search

5 Binary file: Update Marks

6 Dice Simulator

7 Stack using List

8 CSV: User-ID & Password search

9 SQL via Python: Create table & Insert data

10 SQL: ALTER TABLE (add / drop attribute)

11 SQL: UPDATE table

12 SQL: ORDER BY

13 SQL: DELETE tuple(s)

14 SQL: GROUP BY (MIN, MAX, SUM, COUNT, AVG)

15 Similar exercise: Employee table (full SQL-Python integration)

Page 2 of 22
Python Programming - Practical File

Program 1
Aim: Read a text file line by line and display each word separated by '#'.

Source Code:
# Program 1: Read a text file line by line and display each word separated by '#'
def display_words_with_hash(filename):
with open(filename, 'r') as f:
for line in f:
words = [Link]()
print("#".join(words))

display_words_with_hash("[Link]")

Output:
Python#is#a#powerful#programming#language.
It#is#widely#used#for#data#science#and#automation.
Students#enjoy#learning#Python#because#it#is#simple.

Page 3 of 22
Python Programming - Practical File

Program 2
Aim: Read a text file and display the number of vowels, consonants, uppercase and lowercase characters in the file.

Source Code:
# Program 2: Read a text file and display the number of vowels, consonants,
# uppercase and lowercase characters in the file.
def analyze_file(filename):
vowels = consonants = uppercase = lowercase = 0
vowel_set = "aeiouAEIOU"
with open(filename, 'r') as f:
content = [Link]()
for ch in content:
if [Link]():
if ch in vowel_set:
vowels += 1
else:
consonants += 1
if [Link]():
uppercase += 1
elif [Link]():
lowercase += 1
print("Vowels :", vowels)
print("Consonants :", consonants)
print("Uppercase :", uppercase)
print("Lowercase :", lowercase)

analyze_file("[Link]")

Output:
Vowels : 48
Consonants : 73
Uppercase : 4
Lowercase : 117

Page 4 of 22
Python Programming - Practical File

Program 3
Aim: Remove all the lines that contain the character 'a' in a file and write the remaining lines to another file.

Source Code:
# Program 3: Remove all the lines that contain the character 'a' in a file
# and write the remaining lines to another file.
def remove_lines_with_a(infile, outfile):
with open(infile, 'r') as fin, open(outfile, 'w') as fout:
for line in fin:
if 'a' not in line:
[Link](line)

remove_lines_with_a("[Link]", "output_no_a.txt")

print("Original file ([Link]):")


print(open("[Link]").read())
print("New file (output_no_a.txt) - lines without letter 'a':")
print(open("output_no_a.txt").read())

Output:
Original file ([Link]):
Python is a powerful programming language.
It is widely used for scripting.
Students enjoy coding.
Data science relies heavily on Python.

New file (output_no_a.txt) - lines without letter 'a':


It is widely used for scripting.
Students enjoy coding.

Page 5 of 22
Python Programming - Practical File

Program 4
Aim: Create a binary file with name and roll number. Search for a given roll number and display the name; if not
found, display an appropriate message.

Source Code:
# Program 4: Create a binary file with name and roll number.
# Search for a given roll number and display the name; if not found,
# display an appropriate message.
import pickle

def create_binary_file(filename):
students = [
{"roll": 101, "name": "Aarav Sharma"},
{"roll": 102, "name": "Priya Singh"},
{"roll": 103, "name": "Rohan Gupta"},
]
with open(filename, 'wb') as f:
[Link](students, f)

def search_roll(filename, roll_no):


with open(filename, 'rb') as f:
students = [Link](f)
for s in students:
if s["roll"] == roll_no:
return s["name"]
return None

create_binary_file("[Link]")

for roll in (102, 105):


name = search_roll("[Link]", roll)
if name:
print(f"Roll No {roll} -> Name: {name}")
else:
print(f"Roll No {roll} not found in the file.")

Output:
Roll No 102 -> Name: Priya Singh
Roll No 105 not found in the file.

Page 6 of 22
Python Programming - Practical File

Program 5
Aim: Create a binary file with roll number, name and marks. Input a roll number and update the marks.

Source Code:
# Program 5: Create a binary file with roll number, name and marks.
# Input a roll number and update the marks.
import pickle

def create_file(filename):
students = [
{"roll": 201, "name": "Ananya Verma", "marks": 78},
{"roll": 202, "name": "Kabir Mehta", "marks": 85},
{"roll": 203, "name": "Ishita Rao", "marks": 91},
]
with open(filename, 'wb') as f:
[Link](students, f)

def update_marks(filename, roll_no, new_marks):


with open(filename, 'rb') as f:
students = [Link](f)

updated = False
for s in students:
if s["roll"] == roll_no:
s["marks"] = new_marks
updated = True
break

with open(filename, 'wb') as f:


[Link](students, f)
return updated

create_file("[Link]")

print("Before update:")
for s in [Link](open("[Link]", 'rb')):
print(s)

roll_to_update = 202
new_marks = 96
result = update_marks("[Link]", roll_to_update, new_marks)
print(f"\nUpdate for Roll No {roll_to_update}: {'Success' if result else 'Roll
number not found'}")

print("\nAfter update:")
for s in [Link](open("[Link]", 'rb')):
print(s)

Output:
Before update:
{'roll': 201, 'name': 'Ananya Verma', 'marks': 78}
{'roll': 202, 'name': 'Kabir Mehta', 'marks': 85}
{'roll': 203, 'name': 'Ishita Rao', 'marks': 91}

Page 7 of 22
Python Programming - Practical File

Update for Roll No 202: Success

After update:
{'roll': 201, 'name': 'Ananya Verma', 'marks': 78}
{'roll': 202, 'name': 'Kabir Mehta', 'marks': 96}
{'roll': 203, 'name': 'Ishita Rao', 'marks': 91}

Page 8 of 22
Python Programming - Practical File

Program 6
Aim: Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).

Source Code:
# Program 6: Random number generator that generates random numbers
# between 1 and 6 (simulates a dice).
import random

def roll_dice():
return [Link](1, 6)

[Link](42) # seed fixed only so the printed output is reproducible


print("Simulating 10 dice rolls:")
for i in range(1, 11):
print(f"Roll {i}: {roll_dice()}")

Output:
Simulating 10 dice rolls:
Roll 1: 6
Roll 2: 1
Roll 3: 1
Roll 4: 6
Roll 5: 3
Roll 6: 2
Roll 7: 2
Roll 8: 2
Roll 9: 6
Roll 10: 1

Page 9 of 22
Python Programming - Practical File

Program 7
Aim: Write a Python program to implement a stack using a list.

Source Code:
# Program 7: Python program to implement a stack using a list.
class Stack:
def __init__(self):
[Link] = []

def is_empty(self):
return len([Link]) == 0

def push(self, item):


[Link](item)
print(f"Pushed: {item}")

def pop(self):
if self.is_empty():
print("Stack Underflow! Cannot pop.")
return None
item = [Link]()
print(f"Popped: {item}")
return item

def peek(self):
if self.is_empty():
print("Stack is empty.")
return None
return [Link][-1]

def display(self):
print("Current Stack:", [Link])

s = Stack()
[Link](10)
[Link](20)
[Link](30)
[Link]()
[Link]()
[Link]()
print("Top element:", [Link]())

Output:
Pushed: 10
Pushed: 20
Pushed: 30
Current Stack: [10, 20, 30]
Popped: 30
Current Stack: [10, 20]
Top element: 20

Page 10 of 22
Python Programming - Practical File

Program 8
Aim: Create a CSV file by entering user-id and password, read and search the password for a given user-id.

Source Code:
# Program 8: Create a CSV file by entering user-id and password,
# read and search the password for a given user-id.
import csv

def create_csv(filename):
users = [
("user1", "pass@123"),
("user2", "secure#456"),
("user3", "hello$789"),
]
with open(filename, 'w', newline='') as f:
writer = [Link](f)
[Link](["UserID", "Password"])
[Link](users)

def search_password(filename, user_id):


with open(filename, 'r', newline='') as f:
reader = [Link](f)
for row in reader:
if row["UserID"] == user_id:
return row["Password"]
return None

create_csv("[Link]")

for uid in ("user2", "user9"):


pwd = search_password("[Link]", uid)
if pwd:
print(f"UserID: {uid} -> Password: {pwd}")
else:
print(f"UserID: {uid} not found.")

Output:
UserID: user2 -> Password: secure#456
UserID: user9 not found.

Page 11 of 22
Python Programming - Practical File

Program 9
Aim: Integrate SQL with Python (sqlite3 module). Create a Student table and insert data into it.

Source Code:
# Program 9: Integrate SQL with Python (sqlite3 module).
# Create a Student table and insert data into it.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

[Link]("DROP TABLE IF EXISTS Student")


[Link]("""
CREATE TABLE Student (
RollNo INTEGER PRIMARY KEY,
Name TEXT,
Age INTEGER,
Marks REAL
)
""")

students = [
(1, "Aarav Sharma", 16, 78.5),
(2, "Priya Singh", 17, 88.0),
(3, "Rohan Gupta", 16, 65.0),
(4, "Ishita Rao", 17, 91.5),
(5, "Kabir Mehta", 16, 55.0),
]
[Link]("INSERT INTO Student VALUES (?, ?, ?, ?)", students)
[Link]()

print("Student table created and data inserted successfully.\n")


print("Current data in Student table:")
for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]()

Output:
Student table created and data inserted successfully.

Current data in Student table:


(1, 'Aarav Sharma', 16, 78.5)
(2, 'Priya Singh', 17, 88.0)
(3, 'Rohan Gupta', 16, 65.0)
(4, 'Ishita Rao', 17, 91.5)
(5, 'Kabir Mehta', 16, 55.0)

Page 12 of 22
Python Programming - Practical File

Program 10
Aim: ALTER the Student table to add a new attribute and drop an attribute.

Source Code:
# Program 10: ALTER the Student table - add a new attribute,
# modify data (via new column), and drop an attribute.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

# (a) Add a new column 'Grade'


[Link]("ALTER TABLE Student ADD COLUMN Grade TEXT")
print("Column 'Grade' added.")

# Populate the new column based on marks


[Link]("UPDATE Student SET Grade = CASE WHEN Marks >= 85 THEN 'A' WHEN Marks
>= 70 THEN 'B' ELSE 'C' END")
[Link]()

print("\nTable after adding 'Grade' column:")


for row in [Link]("SELECT * FROM Student"):
print(row)

# (b) Drop an attribute - SQLite (3.35+) supports DROP COLUMN directly


[Link]("ALTER TABLE Student DROP COLUMN Age")
[Link]()
print("\nColumn 'Age' dropped.")

print("\nTable after dropping 'Age' column:")


[Link]("SELECT * FROM Student")
print([d[0] for d in [Link]])
for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]()

Output:
Column 'Grade' added.

Table after adding 'Grade' column:


(1, 'Aarav Sharma', 16, 78.5, 'B')
(2, 'Priya Singh', 17, 88.0, 'A')
(3, 'Rohan Gupta', 16, 65.0, 'C')
(4, 'Ishita Rao', 17, 91.5, 'A')
(5, 'Kabir Mehta', 16, 55.0, 'C')

Column 'Age' dropped.

Table after dropping 'Age' column:


['RollNo', 'Name', 'Marks', 'Grade']
(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(3, 'Rohan Gupta', 65.0, 'C')

Page 13 of 22
Python Programming - Practical File

(4, 'Ishita Rao', 91.5, 'A')


(5, 'Kabir Mehta', 55.0, 'C')

Page 14 of 22
Python Programming - Practical File

Program 11
Aim: UPDATE the Student table to modify data.

Source Code:
# Program 11: UPDATE the Student table to modify data.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

print("Before UPDATE:")
for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]("UPDATE Student SET Marks = Marks + 5 WHERE Grade = 'C'")


[Link]()

print("\nAfter UPDATE (+5 marks bonus for Grade 'C' students):")


for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]()

Output:
Before UPDATE:
(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(3, 'Rohan Gupta', 65.0, 'C')
(4, 'Ishita Rao', 91.5, 'A')
(5, 'Kabir Mehta', 55.0, 'C')

After UPDATE (+5 marks bonus for Grade 'C' students):


(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(3, 'Rohan Gupta', 70.0, 'C')
(4, 'Ishita Rao', 91.5, 'A')
(5, 'Kabir Mehta', 60.0, 'C')

Page 15 of 22
Python Programming - Practical File

Program 12
Aim: Use ORDER BY to display data in ascending and descending order.

Source Code:
# Program 12: ORDER BY to display data in ascending / descending order.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

print("Data ordered by Marks - ASCENDING:")


for row in [Link]("SELECT * FROM Student ORDER BY Marks ASC"):
print(row)

print("\nData ordered by Marks - DESCENDING:")


for row in [Link]("SELECT * FROM Student ORDER BY Marks DESC"):
print(row)

[Link]()

Output:
Data ordered by Marks - ASCENDING:
(5, 'Kabir Mehta', 60.0, 'C')
(3, 'Rohan Gupta', 70.0, 'C')
(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(4, 'Ishita Rao', 91.5, 'A')

Data ordered by Marks - DESCENDING:


(4, 'Ishita Rao', 91.5, 'A')
(2, 'Priya Singh', 88.0, 'A')
(1, 'Aarav Sharma', 78.5, 'B')
(3, 'Rohan Gupta', 70.0, 'C')
(5, 'Kabir Mehta', 60.0, 'C')

Page 16 of 22
Python Programming - Practical File

Program 13
Aim: Use DELETE to remove tuple(s) from the Student table.

Source Code:
# Program 13: DELETE to remove tuple(s) from the Student table.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

print("Before DELETE:")
for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]("DELETE FROM Student WHERE Grade = 'C'")


[Link]()

print("\nAfter DELETE (removed students with Grade 'C'):")


for row in [Link]("SELECT * FROM Student"):
print(row)

[Link]()

Output:
Before DELETE:
(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(3, 'Rohan Gupta', 70.0, 'C')
(4, 'Ishita Rao', 91.5, 'A')
(5, 'Kabir Mehta', 60.0, 'C')

After DELETE (removed students with Grade 'C'):


(1, 'Aarav Sharma', 78.5, 'B')
(2, 'Priya Singh', 88.0, 'A')
(4, 'Ishita Rao', 91.5, 'A')

Page 17 of 22
Python Programming - Practical File

Program 14
Aim: Use GROUP BY and find the MIN, MAX, SUM, COUNT and AVERAGE.

Source Code:
# Program 14: GROUP BY and find MIN, MAX, SUM, COUNT and AVERAGE.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

# Re-create table with fresh data so grouping is meaningful


[Link]("DROP TABLE IF EXISTS Student")
[Link]("""
CREATE TABLE Student (
RollNo INTEGER PRIMARY KEY,
Name TEXT,
Marks REAL,
Grade TEXT
)
""")
students = [
(1, "Aarav Sharma", 78.5, "B"),
(2, "Priya Singh", 88.0, "A"),
(3, "Rohan Gupta", 70.0, "C"),
(4, "Ishita Rao", 91.5, "A"),
(5, "Kabir Mehta", 60.0, "C"),
(6, "Meera Nair", 82.0, "B"),
]
[Link]("INSERT INTO Student VALUES (?, ?, ?, ?)", students)
[Link]()

print("Grade-wise statistics (MIN, MAX, SUM, COUNT, AVG of Marks):\n")


query = """
SELECT Grade,
MIN(Marks) AS Min_Marks,
MAX(Marks) AS Max_Marks,
SUM(Marks) AS Total_Marks,
COUNT(*) AS Num_Students,
AVG(Marks) AS Avg_Marks
FROM Student
GROUP BY Grade
"""
print(f"{'Grade':<8}{'Min':<8}{'Max':<8}{'Sum':<10}{'Count':<8}{'Avg':<8}")
for row in [Link](query):
grade, mn, mx, sm, cnt, avg = row
print(f"{grade:<8}{mn:<8}{mx:<8}{sm:<10}{cnt:<8}{avg:<8.2f}")

[Link]()

Output:
Grade-wise statistics (MIN, MAX, SUM, COUNT, AVG of Marks):

Grade Min Max Sum Count Avg


A 88.0 91.5 179.5 2 89.75

Page 18 of 22
Python Programming - Practical File

B 78.5 82.0 160.5 2 80.25


C 60.0 70.0 130.0 2 65.00

Page 19 of 22
Python Programming - Practical File

Program 15
Aim: A similar exercise framed for another case (Employee table), demonstrating CREATE, INSERT, ALTER,
UPDATE, ORDER BY, DELETE and GROUP BY together, integrating SQL with Python using the sqlite3 module.

Source Code:
# Program 15: Similar exercise framed for another case - an Employee table.
# Full integration of SQL with Python (sqlite3): CREATE, INSERT, ALTER,
# UPDATE, ORDER BY, DELETE and GROUP BY all demonstrated together.
import sqlite3

conn = [Link]("[Link]")
cur = [Link]()

[Link]("DROP TABLE IF EXISTS Employee")


[Link]("""
CREATE TABLE Employee (
EmpID INTEGER PRIMARY KEY,
Name TEXT,
Dept TEXT,
Salary REAL
)
""")

employees = [
(1, "Neha Kapoor", "IT", 55000),
(2, "Arjun Malhotra", "HR", 42000),
(3, "Simran Kaur", "IT", 61000),
(4, "Vikram Joshi", "Sales", 48000),
(5, "Divya Menon", "HR", 39000),
(6, "Karan Chawla", "Sales", 52000),
]
[Link]("INSERT INTO Employee VALUES (?, ?, ?, ?)", employees)
[Link]()
print("1) Employee table created and populated:")
for row in [Link]("SELECT * FROM Employee"):
print(row)

# ALTER - add a Bonus column


[Link]("ALTER TABLE Employee ADD COLUMN Bonus REAL")
[Link]("UPDATE Employee SET Bonus = Salary * 0.10")
[Link]()
print("\n2) After ALTER (added 'Bonus' column, set as 10% of Salary):")
for row in [Link]("SELECT * FROM Employee"):
print(row)

# UPDATE - give a raise to IT department


[Link]("UPDATE Employee SET Salary = Salary + 5000 WHERE Dept = 'IT'")
[Link]()
print("\n3) After UPDATE (IT department gets a 5000 raise):")
for row in [Link]("SELECT * FROM Employee"):
print(row)

# ORDER BY
print("\n4) Employees ordered by Salary DESCENDING:")
for row in [Link]("SELECT * FROM Employee ORDER BY Salary DESC"):
print(row)

Page 20 of 22
Python Programming - Practical File

# GROUP BY
print("\n5) Department-wise Salary statistics:")
query = """
SELECT Dept, MIN(Salary), MAX(Salary), SUM(Salary), COUNT(*), AVG(Salary)
FROM Employee GROUP BY Dept
"""
print(f"{'Dept':<8}{'Min':<10}{'Max':<10}{'Sum':<10}{'Count':<8}{'Avg':<10}")
for dept, mn, mx, sm, cnt, avg in [Link](query):
print(f"{dept:<8}{mn:<10}{mx:<10}{sm:<10}{cnt:<8}{avg:<10.2f}")

# DELETE
[Link]("DELETE FROM Employee WHERE Dept = 'HR'")
[Link]()
print("\n6) After DELETE (HR department records removed):")
for row in [Link]("SELECT * FROM Employee"):
print(row)

[Link]()

Output:
1) Employee table created and populated:
(1, 'Neha Kapoor', 'IT', 55000.0)
(2, 'Arjun Malhotra', 'HR', 42000.0)
(3, 'Simran Kaur', 'IT', 61000.0)
(4, 'Vikram Joshi', 'Sales', 48000.0)
(5, 'Divya Menon', 'HR', 39000.0)
(6, 'Karan Chawla', 'Sales', 52000.0)

2) After ALTER (added 'Bonus' column, set as 10% of Salary):


(1, 'Neha Kapoor', 'IT', 55000.0, 5500.0)
(2, 'Arjun Malhotra', 'HR', 42000.0, 4200.0)
(3, 'Simran Kaur', 'IT', 61000.0, 6100.0)
(4, 'Vikram Joshi', 'Sales', 48000.0, 4800.0)
(5, 'Divya Menon', 'HR', 39000.0, 3900.0)
(6, 'Karan Chawla', 'Sales', 52000.0, 5200.0)

3) After UPDATE (IT department gets a 5000 raise):


(1, 'Neha Kapoor', 'IT', 60000.0, 5500.0)
(2, 'Arjun Malhotra', 'HR', 42000.0, 4200.0)
(3, 'Simran Kaur', 'IT', 66000.0, 6100.0)
(4, 'Vikram Joshi', 'Sales', 48000.0, 4800.0)
(5, 'Divya Menon', 'HR', 39000.0, 3900.0)
(6, 'Karan Chawla', 'Sales', 52000.0, 5200.0)

4) Employees ordered by Salary DESCENDING:


(3, 'Simran Kaur', 'IT', 66000.0, 6100.0)
(1, 'Neha Kapoor', 'IT', 60000.0, 5500.0)
(6, 'Karan Chawla', 'Sales', 52000.0, 5200.0)
(4, 'Vikram Joshi', 'Sales', 48000.0, 4800.0)
(2, 'Arjun Malhotra', 'HR', 42000.0, 4200.0)
(5, 'Divya Menon', 'HR', 39000.0, 3900.0)

5) Department-wise Salary statistics:


Dept Min Max Sum Count Avg
HR 39000.0 42000.0 81000.0 2 40500.00
IT 60000.0 66000.0 126000.0 2 63000.00
Sales 48000.0 52000.0 100000.0 2 50000.00

Page 21 of 22
Python Programming - Practical File

6) After DELETE (HR department records removed):


(1, 'Neha Kapoor', 'IT', 60000.0, 5500.0)
(3, 'Simran Kaur', 'IT', 66000.0, 6100.0)
(4, 'Vikram Joshi', 'Sales', 48000.0, 4800.0)
(6, 'Karan Chawla', 'Sales', 52000.0, 5200.0)

Page 22 of 22

You might also like