Vasu Nagar CS Report File
Vasu Nagar CS Report File
Practical File
Class -XII
Python Programming
After Execution:
Q2. Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
Code:-
def cnt():
f=open("D:\\test2.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g',
'h','j','k','l','m',
'n','p','q','r','s',
't','v','w','x','y','z']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",l_c_l)
print("Upper case letters are : ",u_c_l)
#main program
cnt()
Output:-
Input File:-
Output File:-
Q3. Remove all the lines that contain the character 'a' in a file and write it to another file.
Program Logic:
Open input file say ‘assignment.txt’ in read mode and store in temporary file object say
‘input_file’
Open output file say ‘dataoutput.txt’ in write mode and store in temporary file object say
‘output_file’
Read the contents of input file using readlines()
Iterate through input file using for loop
Within for loop, if statement is used to check input file contains the character ‘a’ or not
Write only those lines that does not contain character ‘a’ in output file using write()
Close all input and output file
Code:
# open input file in read mode
inputFile = open(r"D:\inputFile.txt","r")
# open output file in write mode
outputFile = open(r"D:\outputFile.txt","w")
# read all contents of input file using readlines()
lines = inputFile.readlines()
for i in lines:
if 'a' not in i:
outputFile.write(i)
outputFile.close()
inputFile.close()
Output:-
Before Executing
After Executing
Q4. Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
Code:-
import pickle
import sys
dict={}
def write_in_file():
file=open("D:\\stud2.dat","ab") #a-append, b-binary
no=int(input("ENTER NO OF STUDENTS: "))
for i in range(no):
print("Enter details of student ", i+1)
dict["roll"]=int(input("Enter roll number: "))
dict["name"]=input("enter the name: ")
pickle.dump(dict,file) #dump-to write in student file
file.close()
def display():
#read from file and display
file=open("D:\\stud2.dat","rb") #r-read,b-binary
try:
while True:
stud=pickle.load(file) #write to the file
print(stud)
except EOFError:
pass
file.close()
def search():
file=open("D:\\stud2.dat","rb") #r-read,b-binary
r=int(input("enter the rollno to search: "))
found=0
try:
while True:
data=pickle.load(file) #read from file
if data["roll"]==r:
print("The rollno =",r," record found")
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("The rollno =",r," record is not found")
file.close()
#main program
while True:
print("MENU \n 1-Write in a file \n 2-display ")
print(" 3-search\n 4-exit \n")
ch=int(input("Enter your choice = "))
if ch==1:
write_in_file()
if ch==2:
display()
if ch==3:
search()
if ch==4:
print(" Thank you ")
sys.exit()
Output:-
Q5. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
Code:
import pickle
#creating the file and writing the data
f=open("records.dat", "wb")
#list index 0 = roll number
#list index 1 = name
#list index 2 = marks
pickle.dump([1, "Wakil", 90], f)
pickle.dump([2, "Tanish", 80], f)
pickle.dump([3, "Priyashi", 90], f)
pickle.dump([4, "Kanupriya", 80], f)
pickle.dump([5, "Ashutosh", 85], f)
f.close()
#opeining the file to read contents
f=open("records.dat", "rb")
roll=int(input("Enter the Roll Number: "))
marks=float(input("Enter the updated marks: "))
List = [ ] #empty list
flag = False #turns to True if record is found
while True:
try:
record=pickle.load(f)
List.append(record)
except EOFError:
break
f.close()
#reopening the file to update the marks
f=open("records.dat", "wb")
for rec in List:
if rec[0]==roll:
rec[2] = marks
pickle.dump(rec, f)
print("Record updated successfully")
flag = True
else:
pickle.dump(rec,f)
f.close()
if flag==False:
print("This roll number does not exist")
Output:
Q6. Write a random number generator that generates random numbers between 1 and 6
(simulates a dice)
Code:
Q7. Write a python program to implement a stack using list
Here, we are going to write a python program to implement a stack using list. Before
implementing stack using list, first we will see what is stack. A stack is a data structure that
stores items in an Last-In/First-Out manner. This is frequently referred to as LIFO. There are
many ways to implement stack in python. I will tell you some of them. We can implement stack
using linear list or queue or dequeue. There are two inbuilt function to add and remove data
element from stack .
Pop : we can use pop() inbuilt function to remove element from stack in LIFO order.
Push : We can use push () inbuilt function to add element into stack. We can use append
function to add element at the top of the stack. Here we are using append () function to insert
new element to the top of the stack.
Code:-
mystack = []
# append() function to push
# element in the stack
mystack.append('p')
mystack.append('y')
mystack.append('t')
mystack.append('h')
mystack.append('o')
mystack.append('n')
print('After inserting element into stack :')
print(mystack)
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print(mystack.pop())
print('\nStack after elements are popped:')
print(mystack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
Output:-
Q8. Create a CSV file by entering user-id and password, read and search the password for
given user id.
Code:
import csv
with open("user_info.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("user_info.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
# print(i,given)
if i[0] == given:
print(i[1])
break
Output:-
13.Program to store multiple integers in a binary file and
Input:
Output:
18
Demo File (file2)
Input:
19
Original file:
20
16.A menu driven program to perform read and write
operation using a text file containing student information
using function DATA HANDLING FILE
Input:
21
22
17.Program to print a record from table in a database at run
time—PYTHON-MYSQL CONNECTION
Input:
23
Output:
24
18.Program to print a record from table up to a certain limit
PYTHON-MYSQL CONNECTION
Input:
Output:
25
19.Program to insert record in a table —PYTHON -
MYSQL CONNECTION
Input:
Output:
MYSQL TABLE:
26
20.A menu driven program to perform all function on a table
‘student’--- PYTHON-MYSQL CONNECTION
Input:
27
-
28
BIBLIOGRAPHY
● Computer science with python - Class XII By: Sumita Arora
● google.co.in
● www.learnpython.org
29
Database Management System
Q. Create a student table and insert data. Implement the following SQL commands on the
student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data o ORDER By to display data in ascending /
descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
GROUP BY CLAUSE
The GROUP BY Clause combines all those records that have identical values in particular field.
It is used in SELECT statement to divide the table into groups. Grouping can be done by
column name or with aggregate function. Aggregate function work with multiple rows at a time
and return aggregated values. Example of aggregate function : sum(), count(), min(),max(),
avg() etc.
Syntax of SELECT with GROUP BY clause
SELECT <COLUMN1>,<COLUMN2>,……. FROM TABLENAME GROUP BY
COLUMNNAME;
To find minimum,maximum,total,average marks of students (section wise) only
Q. Integrate SQL with Python by importing suitable module.
import mysql.connector
After that we need to establish connection to MySQL database using connect() function of
mysql.connector package. Then we need to create cursor instance which is control structure of
database connectivity. Database cursor help to get s the access of all the record of database and
allow you traverse the result-set that is your set of retrieved records row by row.
So once we have created a cursor,we can execute SQL queries using execute () function with
cursor object. In this way, we can integrate MySQL with python by importing mysql.connector
library.
Steps to create a database connectivity python application are :
Step 1 : Start python
Step 2 : Import package required for database programming ( ex : import
mysql.connector)
Step 3 : Open a connection
Step 4 : Create a cursor instance (ex: cursor = connectionobject.cursor() )
Step 5 : Execute a Query ( ex. cursor.execute( query ) )
Step 6 : Extract data from result set
Step 7 : Clean up environment
Let us now see following code examples how these functions work. For the following code
example, we shall be connecting to database student_dbl,table student that has following data in
it
1] Write a python program that display first 8 rows fetched from student table of MySQl
database student_dbl
integrate
mysql with python using mysql.connector
Output
2] Write a python database connectivity program that deletes record from student table of
database that have name = Meena
import pandas as pd
import mysql.connector as sqltor
conn=sqltor.connect(host="localhost",user="root",passwd="123456",data
base="student_dbl")
if conn.is_connected():
print("Successfully connected")
cursor = conn.cursor()
cursor.execute("delete from student where name = 'Meena'")
data = cursor.fetchmany(10)
count = cursor.rowcount
print("Total no of records deleted from database :",count)
conn.commit()
conn.close()
else:
print("MYSqL connection problem")
Output