Uploaded by divijsharma07

Report file

advertisement
Computer Science (083)
Practical File
Class -XII
Python Programming
Student’s Name:Board Roll Number:-
Q1. Read a text file line by line and display each word separated by a #.
Program Logic:
 Open text file say ‘book.txt’ in read mode using open function
 Pass file name and access mode to open function.Here,we want to read text file that’s
why access mode should be “r”.
 Read the whole content of text file using readlines() function and store it in another
variable say ‘lines’
 Apply for loop to iterate through text file
 Use split function on line object and store words in variable say ‘words’. it splits a string
into a list
 Iterate through word by word using for loop
 Specifies the separator “#”
 Display new modified contents of text file using print() function
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:
Original File:
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
read display it on screen DATA FILE HANDLING
Input:
Output:
14.Program to copy content of one file to another file Data
File Handling Input:
17
Output:
Test file (file1)
18
Demo File (file2)
15.Program to capitalize the first letter of sequence in a file
Data File Handling
Input:
19
Original file:
Output file after program execution:
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:
MYSQL ORIGINAL TABLE:
MYSQL TABLE AFTER PROGRAM EXECUTION:
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
Create a student table in MySQL and insert data
Solutions
CREATE TABLE command is used to create table in MySQL. When table is created,its
columns are named,data types and sizes are also supplied for each column. One point is to be
note that each table must have at least one column.
Syntax of CREATE TABLE command is :
CREATE TABLE <table-name>
(<column name1><data type1>[(size1)], <column name2><data type2>[(size2)],
<column name3><data type3>[(size3)]……………. <column namen><data typen>[(sizen)] );
To create student table whose schema is as follows :
CREATE TABLE STUDENT
(RNO INT PRIMARY KEY, NAME VARCHAR(60),CLASS INT,
SECTION VARCHAR(5),GENDER VARCHAR(10),MARKS INT);
In this way ,we can create student table with multiple columns. In this table, we declare RNO
column as the primary key of the table. The primary keys can not allow NULL values.
Create a student table
Inserting data into table
We can add rows into table using INSERT command of SQL.
Syntax of INSERT INTO command :
INSERT INTO <table name>[ <column list> ]
VALUES( <value1>,<value2>,……………………….);
The INSERT statement adds a new row to table giving value for every column in the row.
Note that the data values are in same order as the column names in table. We can insert number
of rows into student table . If we want to insert 10 rows into student table then we need to
specify 10 INSERT command to do it.
Insert 10 student record into student table
ALTER TABLE Command
We can add column using ALTER TABLE command .We can also redefine a column and we
can change the definition of existing tables. We can change the data type or size of column
using ALTER TABLE command.
To add column
Syntax of ALTER TABLE command is :
ALTER TABLE <TABLE NAME>ADD<COLUMN
NAME><DATATYPE><SIZE>[<CONSTRAINT NAME>];
To add a new column city in the above table with appropriate data type
UPDATE Command
Sometimes we need to change some or all of the values in an existing row. This can be done
using UPDATE command of SQL. WHERE Clause and SET keyword are used with UPDATE
command.
Syntax of UPDATE command
UPDATE <table name> SET <column name> <scalar expression> WHERE condition;
To update single column, one column assignment can be specified with SET clause.
To update multiple columns ,multiple columns assignments can be specified with SET clause.
Suppose ,if you want to increase the marks for the student who have less than 40 by 50%, you
could use the following code
To increase marks by 50% for those students who have marks less than 40
Sorting result—- ORDER BY CLAUSE
ORDER BY clause allows sorting of query results by one or more columns. The sorting can be
done either in ascending or descending order,default order is ascending. Note that, the data in
the table is not sorted;only results that appear on the screen are sorted.
SYNTAX OF ORDER BY CLAUSE
SELECT <COLUMN NAME>[, <COLUMN NAME>,……]
FROM <TABLE NAME>[WHERE <PREDICATE>] [ORDER BY <COLUMN NAME>
ASC/DESC];
To specify the sort order ,we may specify DESC for descending order or ASC for ascending
order. We can perform ordering on multiple attributes or columns
To display Rno, Name, Marks of those Female students in ascending order of their names
To display Rno, Gender, Name,Marks in descending order of their marks
ALTER TABLE Command with DROP Clause
We can remove specific columns from table using ALTER TABLE command with DROP
clause. This command is used to remove specific column from table.
Syntax of ALTER TABLE Command with DROP Clause
ALTER TABLE <TABLENAME> DROP COLUMN <COLUMNNAME>;
Drop column CITY from student table
DELETE command
The DELETE command removes the rows from table. This removes the entire rows,not
individual field values.
Syntax of DELETE Command
DELETE FROM <TABLENAME>[WHERE CONDITION];
To remove all the contents of specific rows, the following command is used.
Delete student details from above table
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
Download