Professional Documents
Culture Documents
CS Files Practical
CS Files Practical
COMPUTER SCIENCE
PRACTICAL FILE
NAME : HRISHANT TRIPATHI
CLASS : 12-C
ROLL NO. : 23
S.N ACTIVITY
O
1 RANDOM NUMBERS
2 KEYWORD ARGUMENTS
3 ODD-EVEN
4 USING TEXT FILES
5 USING BINARY FILES
6 CALCULATIONS
7 CSV FILES
8 FIBONACCI SERIES
9 FACTORIAL OF A NUMBER
10 COUNTING NUMBER OF CONSONANTS
11 COUNTING NUMBER OF VOWELS
def student(firstname,lastname):
print(firstname,lastname)
# Keyword arguments
student(firstname ='Geeks',lastname ='Practice')
student(lastname ='Practice',firstname ='Geeks')
Q) Write a python program to check whether a given Enter your number:31
number x is even or odd. Odd
Enter your number:22
def evenOdd( x ): Even
if (x % 2 == 0):
print("even")
else:
print("odd")
x=int(input("Enter your number:",))
evenOdd(x)
Q) Write a program to use write function on text files. My first line of code
to enter data into a text file
f=open("one.txt","w") we will do binary files later
f.write("My first line of code \n")
f.write("to enter data into a text file \n")
f.write("we will do binary files later \n")
print("File Created Successfully!!!")
f.close()
Q) Write a program to perform simple mathematics enter no1 42
calculations. enter no2 39
Result 7
def add(x,y): Result 81
r=x+y 1638
print("Result ",r) 1.0769230769230769
return(r) Result= 3
def sub(x,y):
r=x-y
return(r)
def pro(x,y):
r=x*y
print(r)
return(x*y)
def div(x,y):
if y==0:
print("Zero Division ERROR!!")
else:
r=x/y
print(r)
return(x/y)
#End of Module
no1=int(input("enter no1 "))
no2=int(input("enter no2 "))
add(4,3)
add(no1,no2)
pro(no1,no2)
div(no1,no2)
#print("Result of addition ",r)
Res=sub(no1,no2)
print ("Result= ",Res)
Q) Write a python program to us writelines in text file. enter list values11 Hrishant Tripathi 96 A+
f=open("two.txt","w") File Created Successfully!!!
l=[]
f.writelines(["10\n","Aditya Pratp\n","98","A+"]) 10
l=input("enter list values") Aditya Pratp
f.writelines(l) 98A+11 Hrishant Tripathi 96 A+
print("File Created Successfully!!!")
f.close()
Q) Write a python program to use an existing file. enter list valuesHRISHANT1 20
do you want to continue?y
f=open("two.txt","w") enter list valuesHRISHANT2 21
l=[] do you want to continue?y
ch='y' enter list valuesHRISHANT3 22
x=0 do you want to continue?y
while ch=='y': enter list valuesHRISHANT4 23
l=input("enter list values") do you want to continue?n
f.writelines(l) File Created Successfully!!! with 4 records
ch=input("do you want to continue?") entered
x+=1
print("File Created Successfully!!! with ",x,"records HRISHANT1 20HRISHANT2 21HRISHANT3
entered") 22HRISHANT4 23
f.close()
Q) Write a python program to display writing more than Enter list values --> rishu1
one data into a Text file using writeline. Do you want to continue --> y
Enter list values --> rishu2
with open ("two.txt",'w') as f: Do you want to continue --> y
l=[] Enter list values --> rishu3
ch='y' Do you want to continue --> y
x=0 Enter list values --> rishu4
while ch=='y': Do you want to continue --> y
l=input("Enter list values --> ") Enter list values --> rishu5
f.writelines(l) Do you want to continue --> n
ch=input("Do you want to continue --> ") Files created with 5 records entered!!!
x+=1
print("Files created with", x, "records entered!!!")
except EOFError:
print("Match found and displayed successfully!")
fr.close()
BF_dict()
Q) Write a python program for creating a Enter admission number:123
dictionary and writing contents into a binary file. Enter name:Saumya
Enter phone number:93768392
defBF_dict(): Enter address:Lodi colony
import pickle Do you want to continue?(y/n)y
fw=open("dict.dat","ab") Enter admission number:234
fr=open("dict.dat","rb") Enter name:Shruti
d1={} Enter phone number:89374663
ch="y" Enter address:AnandVihar
ctr=count=0 Do you want to continue?(y/n)n
while ch=="y" or ch=="Y": Written 2 Records
ctr+=1 Reading from the file
ad=input("Enter admission number:") Record 1 : {123: ['Saumya', 93768392,
name=input("Enter name:") 'Lodi colony']}
pn=int(input("Enter phone number:")) Record 2 : {234: ['Shruti', 89374663,
add=input("Enter address:") 'AnandVihar']}
d1={admno:[name,pn,add]} 2 Records read and displayed
pickle.dump(d1,fw) successfully!
ch=input("Do you want to continue?(y/n)")
fw.close()
print("Written",ctr,"Records")
print("Reading from the file")
try:
while True:
count+=1
dl=pickle.load(fr)
print("Record",count,":",dl)
except EOFError:
print(count-1,"Records read and displayed
successfully!")
fr.close()
BF_dict()
Q) Write a python program for writing into csv Enter st record :
file. Roll Number --> 23
Enter name --> Hrishant Tripathi
import csv Enter marks --> 98
f=open("St.csv",'a+') Enter st record :
sw=csv.writer(f) Roll Number --> 31
sw.writerow(["Rn","Name","Marks"]) Enter name --> Naman
for i in range(2): Enter marks --> 98
print("Enter st record :")
r=int(input("Roll Number --> "))
n=input("Enter name --> ")
m=float(input("Enter marks --> "))
sr=[r,n,m]
sw.writerow(sr)
f.close()
Q) Write a python program for reading and Contents of the CSV file St.csv
displaying the contents from a csv file. ['Rn', 'Name', 'Marks']
['23', 'Hrishant Tripathi', '98.0']
#import C-write ['31', 'Naman', '98.0']
import csv
with open("St.csv",'r',newline='\r\n') as f:
cr=csv.reader(f)
print("Contents of the CSV file St.csv")
for rec in cr:
print(rec)
Q) Write a python code to demonstrate ['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Implementing stack using list.
s=[]
for letter in w:
if letter in v:
if letter not in s:
s.append(letter)
print(s)
Q) Write a python program for reversing a word in Reversing each word in a string using -->
a string. STRING CONCATANATION
METHOD
# The word is "nohtyP gnimmargorP" 1. Reversed String -->
str1="Python Programming" REVERSE EACH WORD USING
l1=str1.split() STACK IMPLEMENTATION
str2=' ' Original String --> Python Programming
print("Reversing each word in a string using --> Reversed String --> nohtyP
STRING CONCATANATION METHOD") gnimmargorP
for i in l1:
for j in range(len(i)-1,-1,-1):
str2+=i[j]
str2=' '
print("1. Reversed String --> ", str2)
print("REVERSE EACH WORD USING STACK
IMPLEMENTATION")
revs=[]
for w in l1:
for j in range(len(w)-1,-1,-1):
revs.append(w[j])
revs.append(' ')
frevs=''.join(revs)
print("Original String --> ",str1)
print("Reversed String --> ",frevs)
Q) WAP to implement a stack with Book Detail 1. Enter Details
2. Delete Details
def isempty(a): 3. Display Details
Enter Choice...1
if a==[]: Enter Book number --> 10
Enter book name --> HG WELLS
return True Continue...?Y
Enter Choice...1
else: Enter Book number --> 11
Enter book name --> MARK TWAIN
return False Continue...?y
Enter Choice...1
def s_push(a,item): Enter Book number --> 12
Enter book name --> CHARLES
a.append(item) DICKEN
Continue...?y
def s_pop(a): Enter Choice...2
Remove item is --> (12, 'CHARLES
if isempty(a): DICKEN')
Continue...?y
print("Underflow") Enter Choice...3
(11, 'MARK TWAIN')
ele=None (10, 'HG WELLS')
Continue...?n
else:
ele=a.pop()
return ele
def isdisplay(a):
if isempty(a):
print('No element')
else:
for i in a[::-1]:
print(i)
def main():
stack=[]
ch='y'
c=int(input("Enter Choice..."))
if c==1:
bo=(bno,bname)
s_push(stack,bo)
elif c==2:
item=s_pop(stack)
elif c==3:
isdisplay(stack)
else:
ch=input("Continue...?")
main()
Q) Write a python program to generate 5 no. and Enter the number of items in list5
enter them in a list. Enter the lower limit10
Enter the upper limit20
import random [18, 19, 17, 15, 12]
def Rand(start,end,num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
num=int(input("Enter the number of items in list"))
start=int(input("Enter the lower limit"))
end=int(input("Enter the upper limit"))
print(Rand(start,end,num))
Q) Write a python program to enter a Fibonacci How many terms? 10
Series of n terms. Fibonacci sequence:
0
nterms = int(input("How many terms? ")) 1
n1, n2 = 0, 1 1
count = 0 2
if nterms <= 0: 3
print("Please enter a positive integer") 5
8
elif nterms == 1:
13
print("Fibonacci sequence upto",nterms,":")
21
print(n1)
34
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Q) Write a python program to enter a number and Enter a number whose factorial you want
find its factorial. to find5
The factorial of 5 is 120
num=int(input("Enter a number whose factorial you
want to find"))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Q) Write a python program to read a text file and cut
display the words shorter than 4 letters. the
is
def DISPLAYWORDS():
c=0
file=open("STORY.TXT",'R')
line=file.read()
word=line.split()
for w in word:
if len(w)<4:
print(w)
file.close()
# Global Scope
s = "Python is great!"
f()
print(s)
import mysql.connector
mydb=mysql.connector.connect(host="localhost",use
r="root",password="tiger",database="12 C")
mycursor.execute("show tables")
print("TABLES IN DATABASE 12C")
for c in mycursor:
print(c)
print("STRUCTURE OF TABLE STUDENTS")
mycursor.execute("DESC student")
for c in mycursor:
print(c)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE
customers (name VARCHAR(255),
address VARCHAR(255))"
import mysql.connector
mydb=mysql.connector.connect(host="localhost",use
r="root",password="tiger",database="12C")
mycursor=mydb.cursor()
ch='y'
while ch=='y' or ch=='Y':
v1=int(input("Add Rno.-->"))
v2=input("Name-->")
v3=input("Cl_S-->")
v4=float(input("TotM-->"))
sql1="INSERT INTO student values(%s,%s,%s,%s)"
info=(v1,v2,v3,v4)
mycursor.execute(sql1, info)
ch=input("Do you want to continue?(y/n)-->")
mydb.commit()
print(mycursor.rowcount,"Row Inserted")
print("DISPLAY THE CONTENTS OF THE TABLE")
mycursor.execute("select * from students")
myrec=mycursor.fetchall()
for r in myrec:
print(r)
def facto(num):
if num<0:
print("Sorry, factorial don't exist for negative
integers!")
elif num==0:
return 1
else:
for i in (1,num+1):
return(num * facto(num-1))
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE
mydatabase")
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers
(id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), address VARCHAR(255))")
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name,
address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record
inserted.")
Q1. Write a method /function countlines_et () Q2. Write a function that counts the number of
in python to read lines from a text file report.txt, “Me” or “My” words present in a text file”
and COUNT those lines which are starting either story1.txt.
with ‘E’ and starting with ‘T’ respectively. And If the “story1.txt” content are as follows:
display the Total count separately. My first book was Me and My Family. It gave me
For example: if REPORT.TXT consists of chance to be known to the world.
“ENTRY LEVEL OF PROGRAMMING CAN BE The output of the function should be:
LEARNED FROM USEFUL FOR VARIETY OF Count of Me/My in file: 4
USERS.” Solution:
Then, Output will be: No. of Lines with E: 1 def displayMeMy():
No. of Lines with T: 1 num=0
Solution: f=open("story1.txt","rt")
def countlines_et(): N=f.read()
f=open("report.txt",'r') M=N.split()
lines=f.readlines() for x in M:
linee=0 if x=="Me" or x== "My":
linet=0 print(x)
for i in lines: num=num+1
if i[0]=='E': f.close()
linee+=1 print("Count of Me/My in file:",num)
elif i[0]=='T': displayMeMy()
linet+=1 OR
print("No.of Lines with E:",linee) Write a function count_A_M(), which should read
print("No.of Lines with T:",linet) each character of a text file STORY.TXT, should
countlines_et() count and display the occurrence of alphabets A
OR and M (including small cases a and m too).
Write a method/function show_todo():in python Example: If the file content is as follow: Updated
to read contents from a text file abc.txt and display information As simplified by official websites.
those lines which have occurrence of the word “ The count_A_M():function should display the
TO” or “DO” output as:
For example: If the content of the file is A or a:4 M or m:2
“THIS IS IMPORTANT TO NOTE THAT SUCCESS IS Solution:
THE RESULT OF HARD WORK WE ALL ARE def count_A_M():
EXPECTED TO DO HARD WORK. AFTER ALL f=open("story1.txt","r")
EXPERIENCE COMES FROM HARDWORK.” A,M=0,0
The method/function should display” r=f.read()
THIS IS IMPORTANT TO NOTE THAT SUCCESS IS for x in r:
THE RESULT OF HARD WORK. if x[0]=="A" or x[0]=="a" :
WE ALL ARE EXPECTED TO DO HARD WORK. A=A+1
Solutions: elif x[0]=="M" or x[0]=="m":
def show_todo(): M=M+1
f=open("abc.txt",'r') f.close()
lines=f.readlines() print("A or a: ",A,"\t M or m: ",M)
for i in lines:
if "TO" in i or "DO" in i:
print(i)
show_todo()
Consider a binary file stock.dat that has the Q4. A binary file “Book.dat” has structure [BookNo,
following data: OrderId, MedicineName,Qty and Book_Name, Author, Price].
Price of all the medicines of wellness medicos, a.Write a user defined function CreateFile() to
write the following functions: input data for a record and add to Book.dat.
a)AddOrder() that can input all the medicine b. Write a function CountRec(Author) in Python
orders. which accepts the Author name as parameter and
b)DisplayPrice() to display the details of all the count and retum number of books by the given
medicine that have Price. Author are stored in the binary file “Book.dat”.
Solution: import pickle
import pickle def CreateFile():
def AddOrder(): fobj=open("Book.dat","ab")
f=open("Stock.dat",'ab') BookNo=int(input("Book Number : "))
OrderId=input("Enter Order Id") Book_name=input("Name :")
MedicineName=input("Enter Medicine Name") Author = input("Author: ")
Qty=int(input("Enter Quantity:")) Price = int(input("Price : "))
Price=int(input("Enter Price:")) rec=[BookNo,Book_Name,Author,Price]
data=[OrderId,MedicineName,Qty,Price] pickle.dump(rec,fobj)
pickle.dump(data,f) fobj.close()
f.close() def CountRec(Author):
AddOrder() fobj=open("Book.dat","rb")
def DisplayPrice(): num = 0
f=open("Stock.dat",'rb') try:
try: while True:
while True: rec=pickle.load(fobj)
data=pickle.load(f) if Author==rec[2]:
if data[3]>500: num = num + 1
print(data[0],data[1],data[2],data[3],sep="\t") except:
except: fobj.close()
f.close() return num
DisplayPrice() Q6. A binary file named “TEST.dat” has some
Q5. Create a binary file funandfood.dat that can records of the structure [TestId, Subject,
store details of rides such as Ticketno, Ridename, MaxMarks, ScoredMarks]
No_ofpersons, and price with the help of Write a function in Python named
AddRides() function and write another python DisplayAvgMarks(Sub) that will accept a subject
function display Total to display total amount of as an argument and read the contents of TEST.dat.
each ticket. Also count total number of tickets sold. The function will calculate & display the Average
Solution: of the ScoredMarks of the passed Subject on
import pickle # to use binary file screen.
def AddRides(): Solution:
f=open("funandfood.dat",'ab') def DisplayAvgMarks(sub):
Ticketno=input("Enter Ticket Number") f=open("TEST.dat","rb")
RideName=input("Enter The Name of Ride") count=0
No_ofperson=int(input("Enter no of Persons")) sum=0
Price=int(input("Enter Price:")) try:
data=[Ticketno,RideName,No_ofperson,Price]
pickle.dump(data,f)
f.close()
AddRides()
def Display Total():
f=open("funandfood.dat",'rb')
total=0
count=0
maxsize=5
top=-1
#-------------
def pop(stack):
global top
if (isEmpty(stack)):
print("\n Stack is UnderFlow \n")
else:
n=stack[top]
stack.pop()
print("Removed Element ",n)
top=top-1
def push(stack):
global top
if (isFull(stack)):
print("\n Stack is OverFlow \n ")
else:
n=int(input("\nEnter an element to push :"))
top=top+1
stack.append(n)
def traverse(stack):
if (isEmpty(stack)):
print("Stack is Empty ")
else:
for i in stack:
print(i,end=" ")
def peak(stack):
global top
return stack[top]
def isFull(stack):
global maxsize
if (top==maxsize-1):
return True
else:
return False
def isEmpty(stack):
if (top==-1):
return True
else:
return False
#********** Main Program ************
stack=[]
a=True
while a:
print("\n1. Stack Push Operation ")
print("2. Stack Pop Operation ")
print("3. Show Peak / Top Position ")
print("4. Traverse / Show Stack ")
print("5. Exit ")
ch=int(input("Enter Choice :"))
if ch == 1:
push(stack)
elif ch == 2:
pop(stack)
elif ch == 3:
print("\n Peak Position ",peak(stack))
print('Top is ', top)
elif ch == 4:
traverse(stack)
elif ch == 5:
a=False
else:
print('Please enter a valid choice ‘)