0% found this document useful (0 votes)
7 views30 pages

Python Programming Exercises Guide

The document outlines a program file for a Computer Science course, detailing various Python programming tasks and exercises for students. It includes code examples for string manipulation, file handling, data storage, and database connectivity. Each task is numbered and provides a brief description along with sample code and expected results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views30 pages

Python Programming Exercises Guide

The document outlines a program file for a Computer Science course, detailing various Python programming tasks and exercises for students. It includes code examples for string manipulation, file handling, data storage, and database connectivity. Each task is numbered and provides a brief description along with sample code and expected results.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

E-3, Sector-61, Noida

Session: 2024-2025

COMPUTER SCIENCE - 083


Program File
STD:-_____________________
Roll No. __________________

Submitted To: Submitted By:


Mrs. Meera Gupta __________________

Page 1 of 30
[Link] Codes Page No.
1 Write a Python program to remove the nth index character from a 4
nonempty string.

2 Write a program to reverse a string. 4

3 Write a Python program to perform the following operations on a string: a) 5


Prompt the user to input a string. b) Extract all digits from the string, if
present. c) Calculate and display the sum of the digits. i) Display the digits.
ii) Display the original string. iii) Display the sum of the digits. d) If no digits
are present, display the original string along with the message "No Digits
are present."

4 Write a Python program to compute the total salary of the employee and 6
also calculate the size of the binary file named "[Link]", the file
consists of the following fields: employee number, employee name, basic
salary, allowance. (Hint: Total salary = basic + allowance)

5 Write a Python program to display all the records in a file along with 7
line/record numbers.

6 Write a menu-driven program to perform read and write operations using 8-10
a text file called "[Link]", containing student roll-no, name, and
address using two separate functions as given below:

7 A binary file "[Link]" has a structure [Book No, Book Name, Author, 11
Price]. Write a user-defined function Createfile() to input data for a record
and add it to '[Link]'. Also, write a function Countrec(Author) in Python
which accepts the Author name as a parameter and counts and returns
the number of books by the given Author stored in the binary file
"[Link]".

8 Write a Python program to implement a stock that contains two types of 12-13
information: a book number and its name. Just implement PUSH and
DISPLAY operations.

9 Write a program to save student information like admission number, roll 14-15
number, name, and marks in a dictionary, and display the information
based on the admission number.

10 Write a Python program to create a text file and print the lines starting 16
with 'T' or 'p'.

Page 2 of 30
11 Write a menu-based program to add, delete, and display the record of a 17-19
hostel using a list as a stack data structure in Python. The record of a
hostel contains the fields: Hostel number, Total students, and Total rooms.

12 Write a function LShift(arr, n) in Python which accepts a list arr of numbers 20


and a numeric value n by which all elements of the list are shifted to the
left.

13 Write a function countH() in Python to display the number of lines starting 21


with 'H' in the file "[Link]".

14 Write a menu-driven program implementing user-defined functions to 22-24


perform different operations on a CSV file "student" such as: a) Write a
single record to the CSV. b) Write all records in one go to the CSV. c)
Display the contents of the CSV file.

15 Write a function countmy() in Python to read the text file "[Link]" and 25
count the number of times 'my' occurs in the file.

16 What are the benefits of using the "with open()" method over "open()" 26
while opening a file? Write a Python program that defines and calls the
following user-defined functions: i) Add_item to accept and add data of
stationary items to a CSV file "[Link]". The record consists of a list
with field elements as Item_Id, Item_name, and Item_price. ii) Count() to
count the total number of stationary items in the CSV file.

17 SS Public School is managing student data in the 'student' table in the 27


'school' database. Write Python code that connects to the database
'school' and retrieves all records, displaying the total number of students.

18 Write code to connect to a MySQL database 'school' and retrieve all 28


records from the 'student' table where grade is 'A'.

19 Write a Python connectivity program to retrieve data, one record at a 29


time, from the 'EMP' table for employees with ID < 10.

20 Consider a database 'company' that has a table 'emp' that stores details of 30
many employees. Write a MySQL Python connectivity program to retrieve
data one record at a time for employees with ID < 10.

Page 3 of 30
Python
Program 1
Remove the nth index character from a non-empty string.

Code:
def remove_char(str, n):
first_part = str[:n]
last_part = str[n + 1:]
return first_part + last_part

print(remove_char('computer', 0))
print(remove_char('computer', 3))
print(remove_char('computer', 5))

Result:
omputer
comuter
compuer

Program 2
Code:
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[index - 1]
index = index - 1
return rstr1
print(string_reverse("helloworld"))

Result:
Output:
dlrowolleh

Page 4 of 30
Program 3
Code:
str1 = input("enter the string")
sum = 0
num = 0
if [Link]() == False:
for i in str1:
if [Link]() == True:
num = num * 10 + int(i)
sum += int(i)
print("original string:", str1)
print("digits:", num)
print("sum of digits is:", sum)
else:
print("original string:", str1, "has no digit")

Result:
enter the string: ab123cd45
original string: ab123cd45
digits: 12345
sum of digits is: 15

Page 5 of 30
Program 4
Code:
import pickle
print("working with binary files")
bfile = open("[Link]", "ab")
recno = 1
print("enter records of employees")
print()
while True:
print("RECORD No.", recno)
eno = int(input("\tEmployee number :"))
ename = input("\tEmployee name :")
ebasic = int(input("\tbasic salary : "))
allow = int(input("\tAllowances :"))
totsal = ebasic + allow
print("\tTotal salary : ", totsal)
edata = [eno, ename, ebasic, allow, totsal]
[Link](edata, bfile)
ans = input("Do you wish to enter more records (y/n) ?")
recno = recno + 1
if [Link]() == 'n':
print("Record entry over")
break
[Link]()
Result:
working with binary files
enter records of employees
RECORD No. 1
Employee number : 101
Employee name : John
basic salary : 5000
Allowances : 2000
Total salary : 7000
Do you wish to enter more records (y/n) ?n

Page 6 of 30
Program 5
Code:
import pickle

f = open("[Link]", "rb")
count = 0

while True:
try:
rec = [Link](f)
count += 1
print(f"Record {count}: {rec}")
except EOFError:
break
[Link]()

Result:

Record 1: [101, 'John', 25000, 5000, 30000]

Record 2: [102, 'Jane', 27000, 5500, 32500]

Record 3: [103, 'Alex', 22000, 4500, 26500]

Page 7 of 30
Program 6
Code:
import os
filename = "[Link]"

def student_record(filename):
if not [Link](filename):
print("File not created")
else:
ch = 'y'
print("Enter student details:")
with open(filename, 'a') as file:
while ch == 'y' or ch == 'Y':
roll_no = input("Enter roll no.: ")
name = input("Enter name: ")
address = input("Enter address: ")
[Link](str(roll_no) + "," + [Link]() + "," + address + "\n")
[Link]()
ch = input("Want to add more records? (y/n): ")
if ch == 'n':
break

def student_readdata(filename):
if [Link](filename):
with open(filename, 'r') as file:
print("Student information")
print("--------------------------")
for student in file:
print(student, end=" ")
else:
print("File does not exist")

def student_search(filename):
if [Link](filename):
with open(filename, 'r') as file:

Page 8 of 30
roll_no = int(input("Enter roll no. to be searched:"))
flag = False
for student in file:
i=0
str_roll_no = ""
while True:
if student[i] == ",":
break
if student[i] >= '0' and student[i] <= '9':
str_roll_no += student[i]
i += 1
s_roll_no = int(str_roll_no)
if roll_no == s_roll_no:
print("Student found:", student, end="")
flag = True
break
if not flag:
print("Record not found")
else:
print("File does not exist")

Page 9 of 30
Result:
Select a choice (1-4): 1
Enter student details:
Enter roll no.: 101
Enter name: John
Enter address: New York
Want to add more records? (y/n): y
Enter roll no.: 102
Enter name: Jane
Enter address: Los Angeles
Want to add more records? (y/n): n

Select a choice (1-4): 2


Student information
--------------------------
101, JOHN, New York
102, JANE, Los Angeles

Select a choice (1-4): 3


Enter roll no. to be searched: 101
Student found: 101, JOHN, New York

Page 10 of 30
Program 7
Code:
import pickle

def createfile():
fobj = open("[Link]", "ab")
BookNo = int(input("Book Number:"))
Book_name = input("Name:")
Author = input("Author:")
Price = int(input("Price:"))
rec = [BookNo, Book_name, Author, Price]
[Link](rec, fobj)
[Link]()

def CountRec():
fobj = open("[Link]", "ab")
num = 0
try:
while True:
rec = [Link](fobj)
if Author == rec[2]:
num = num + 1
except:
[Link]()
return num

Result:
Book Number: 101
Name: Python Programming
Author: John
Price: 500
Book Number: 102
Name: Data Science
Author: Jane
Price: 600

Page 11 of 30
Program 8
Code:
def isEmpty(stk):
if stk == []:
return True
else:
return False
def Push(stk, item):
[Link](item)
top = len(stk) - 1
def Display(stk):
if isEmpty(stk):
print('Stack empty')
else:
top = len(stk) - 1
print(stk[top], 'top')
for a in range(top - 1, -1, -1):
print(stk[a])
Stack = []
while True:
print('STACK OPERATION')
print('1. Push')
print('2. Display stack')
print('3. Exit')
ch = int(input('Enter your choice (1-3): '))
if ch == 1:
bno = int(input('Enter book no. to be inserted: '))
bname = input('Enter book name to be inserted: ')
Item = [bno, bname]
Push(Stack, Item)
elif ch == 2:
Display(Stack)
elif ch == 3:

Page 12 of 30
break
else:
print("Invalid choice!")

Result:
STACK OPERATION
1. Push
2. Display stack
3. Exit
Enter your choice (1-3): 1
Enter book no. to be inserted: 101
Enter book name to be inserted: Python

STACK OPERATION
1. Push
2. Display stack
3. Exit
Enter your choice (1-3): 1
Enter book no. to be inserted: 102
Enter book name to be inserted: Java

STACK OPERATION
1. Push
2. Display stack
3. Exit
Enter your choice (1-3): 2
102 Java top
101 Python

STACK OPERATION
1. Push
2. Display stack
3. Exit
Enter your choice (1-3): 3

Page 13 of 30
Program 9
Code:
scl = {}
i=1
n = int(input("Enter number of entries: "))
while i <= n:
adm = input("\nEnter admission number of student: ")
section = input("Enter class and section: ")
nm = input("Enter name of the student: ")
per = float(input("Enter percentage of the student: "))
b = (nm, section, per)
scl[adm] = b
i += 1
print("\nStudent Records:")
for adm_no, details in [Link]():
print(f"\nAdm No: {adm_no}:")
print("Name\t\tClass\t\tPercentage")
print(f"{details[0]}\t{details[1]}\t{details[2]}")

Page 14 of 30
Result:
Enter number of entries: 2

Enter admission number of student: 101


Enter class and section: 12A
Enter name of the student: Razz
Enter percentage of the student: 85

Enter admission number of student: 102


Enter class and section: 12B
Enter name of the student: Sita Kumari
Enter percentage of the student: 90

Student Records:

Adm No: 101:


Name Class Percentage
Razz 12A 85.0

Adm No: 102:


Name Class Percentage
Sita Kumari 12B 90.0

Page 15 of 30
Program 10
Code:
def display():
file = open('[Link]', 'r')
line = [Link]()
while line:
if line[0] == 'P':
print(line)
line = [Link]()
[Link]()

display()

Result:
Penny is a great person.
Today is a wonderful day.
The sky is blue.
Peter loves coding.

Output:
Penny is a great person.
Peter loves coding.

Page 16 of 30
Program 11
Code:
def push(host):
hn = int(input("Enter hostel number:"))
ts = int(input("Enter total students:"))
tr = int(input("Enter total rooms:"))
temp = [hn, ts, tr]
[Link](temp)

def pop(host):
if (host == []):
print("No record")
else:
print("Deleted record is:", [Link]())

def display(host):
I = len(host)
print("Hostel number\t Total students\t Total rooms")
for i in range(I - 1, -1, -1):
print(host[i][0], '\t', host[i][1], '\t', host[i][2])

host = []
while True:
print('1. Add record')
print('2. Delete record')
print('3. Display records')
print('4. Exit')
ch = input('Do you want to enter more (y/n): ')
if [Link]() == 'y':
choice = int(input('Enter your choice: '))
if choice == 1:
push(host)

Page 17 of 30
elif choice == 2:
pop(host)
elif choice == 3:
display(host)
elif choice == 4:
break
else:
print("Invalid choice, try again!")

Page 18 of 30
Result:
1. Add record
2. Delete record
3. Display records
4. Exit
Do you want to enter more? (y/n): y
Enter your choice: 1
Enter hostel number: 101
Enter total students: 200
Enter total rooms: 50

1. Add record
2. Delete record
3. Display records
4. Exit
Do you want to enter more? (y/n): y
Enter your choice: 1
Enter hostel number: 102
Enter total students: 150
Enter total rooms: 40

1. Add record
2. Delete record
3. Display records
4. Exit
Do you want to enter more? (y/n): y
Enter your choice: 3
Hostel Number Total Students Total Rooms
102 150 40
101 200 50

Page 19 of 30
Program 12
Code:
def LShift(arr, n):
I = len(arr)
for x in range(0, n):
y = arr[0]
for i in range(0, I - 1):
arr[i] = arr[i + 1]
arr[I - 1] = y
print(arr)

arr = [10, 20, 30, 40, 12, 11]


LShift(arr, 2)

Result:

Shifted array: [30, 40, 12, 11, 10, 20]

Page 20 of 30
Program 13
Code:
f = open("[Link]", "w")
[Link]("""whose woods there are i think i know
His house is in the village though He will not
see me stopping here to watch his woods fill up with snow""")
[Link]()

def countH():
f = open("[Link]", "r")
C=0
L = [Link]()
for i in L:
if i[0] == 'H':
C += 1
print("NO. of lines starting with H are: ", C)
[Link]()

countH()

Result:
NO. of lines starting with H are: 2

Page 21 of 30
Program 14
Code:
import csv

def write_record(single=True):
"""Write records to the CSV file."""
with open("[Link]", mode="a", newline="") as file:
writer = [Link](file)
if single:
[Link]([
input("Enter Roll Number: "),
input("Enter Name: "),
input("Enter Marks: ")
])
else:
for _ in range(int(input("Enter the number of records to add: "))):
[Link]([
input("Enter Roll Number: "),
input("Enter Name: "),
input("Enter Marks: ")
])

def display_csv_contents():
"""Display the contents of the CSV file."""
try:
with open("[Link]", mode="r") as file:
print("\nContents of '[Link]':")
for row in [Link](file):
print(row)
except FileNotFoundError:
print("The file '[Link]' does not exist. Please add records first.")

def main():

Page 22 of 30
"""Main function to display the menu and handle user choices."""
while True:
choice = input("\n--- Menu ---\n1. Write a single record\n2. Write multiple
records\n3. Display CSV contents\n4. Exit\nEnter your choice (1-4): ")
if choice == '1':
write_record(single=True)
elif choice == '2':
write_record(single=False)
elif choice == '3':
display_csv_contents()
elif choice == '4':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

Result:
--- Menu ---
1. Write a single record
2. Write multiple records
3. Display CSV contents
4. Exit
Enter your choice (1-4): 1
Enter Roll Number: 101
Enter Name: Rahul Verma
Enter Marks: 85

--- Menu ---


1. Write a single record
2. Write multiple records
3. Display CSV contents
4. Exit

Page 23 of 30
Enter your choice (1-4): 2
Enter the number of records to add: 2
Enter Roll Number: 102
Enter Name: Priya Sharma
Enter Marks: 90
Enter Roll Number: 103
Enter Name: Aman Kumar
Enter Marks: 80

--- Menu ---


1. Write a single record
2. Write multiple records
3. Display CSV contents
4. Exit
Enter your choice (1-4): 3

Contents of '[Link]':
['101', 'Rahul Verma', '85']
['102', 'Priya Sharma', '90']
['103', 'Aman Kumar', '80']

--- Menu ---


1. Write a single record
2. Write multiple records
3. Display CSV contents
4. Exit
Enter your choice (1-4): 4
Exiting program. Goodbye!

Page 24 of 30
Program 15
Code:
def countmy():
f = open("[Link]", "r")
count = 0
x = [Link]()
word = [Link]()
for i in word:
if i == "my":
count += 1
print("my occurs", count, "times")
[Link]()

countmy()

Result:
my occurs 3 times

Page 25 of 30
Program 16
Code:
import csv

def Add_item():
f = open("[Link]", "a", newline="\n")
data = [Link](f)
Item_id = input("Enter Item Id::")
Item_Name = input("Enter Item Name::")
Item_Price = int(input("Enter Price::"))
Lst = [Item_id, Item_Name, Item_Price]
[Link](Lst)
[Link]()

def Count():
f = open("[Link]", "r", newline="\n")
data = [Link](f)
d = list(data)
print(len(d))
[Link]()

Add_item()
Count()
Result:
Enter Item Id:: 101
Enter Item Name:: Pen
Enter Price:: 10

Page 26 of 30
Program 17
Code:
import [Link]

mydb = [Link](
host="localhost",
user="root",
password="raj0911",
database="school"
)

cur = [Link]()

[Link]("SELECT * FROM student")

records = [Link]()

count = 0

for x in records:
count += 1
print(x)

print('Total number of records are:', count)

[Link]()

Result:
(1, 'John Doe', '10', 'A', 85)
(2, 'Jane Smith', '10', 'B', 90)
...
Total number of records are: 5

Page 27 of 30
Program 18
Code:
import [Link]

mydb = [Link](
host="localhost",
user="root",
password=" raj0911",
database="school"
)

cur = [Link]()

run = "SELECT * FROM student WHERE grade = 'A'"

[Link](run)

data = [Link]()

for i in data:
print(i)
[Link]()

Result:
(1, 'Milan', 'A', 95)
(2, 'Sahil', 'A', 92)
(3, 'Anisha', 'A', 98)

Page 28 of 30
Program 19
Code:
import [Link]

conn = [Link](host="localhost", user="root",


passwd=" raj0911",
database="school")
c = [Link]()
[Link]("SELECT * FROM emp WHERE id < 10")
r = [Link]()
count = 0
while r is not None and count < 5:
print(r)
r = [Link]()
count += 1
[Link]()

Result:
(1, 'Rajesh Kumar', 'Mumbai', 'Manager', 50000)
(2, 'Sonia Mehta', 'Delhi', 'Software Engineer', 60000)
(3, 'Amit Verma', 'Bangalore', 'HR Executive', 40000)
(4, 'Priya Sharma', 'Chennai', 'Sales Manager', 45000)
(5, 'Ravi Singh', 'Kolkata', 'Marketing Head', 70000)

Page 29 of 30
Program 20
Code:
import [Link]

db = [Link](host="localhost", user="root",
passwd=" raj0911",
database="company")
cursor = [Link]()

sql = "SELECT * FROM emp WHERE id < 10"


[Link](sql)

r = [Link]()
while r is not None:
print(r)
r = [Link]() # Fetch the next record

[Link]()

Result:
(1, 'Rajesh Kumar', 'Mumbai', 'Manager', 50000)
(2, 'Sonia Mehta', 'Delhi', 'Software Engineer', 60000)
(3, 'Amit Verma', 'Bangalore', 'HR Executive', 40000)
(4, 'Priya Sharma', 'Chennai', 'Sales Manager', 45000)
(5, 'Ravi Singh', 'Kolkata', 'Marketing Head', 70000)

Page 30 of 30

You might also like