Python Programs Class-12
Python Programs Class-12
Korba
AISSCE 2020-21
COMPUTER SCIENCE
PRACTICALS
file = open("sample.txt",'r')
number_of_lines = 0
number_of_words = 0
for line in file:
line = line.strip('\n')
words = line.split()
number_of_lines += 1
number_of_words += len(words)
file.close
print('lines:', number_of_lines, 'words:',
number_of_words)
#Program 2
#program to read a text file and count number of
'the'
file = open('tea.txt','rt')
data = file.read()
words = data.count('the')
print('number of words in the text file is ', words)
file.close()
#Program 3
#Program to create a text file and store as many
lines as user wants
file = open('hello.txt','w')
edit = input('Enter the lines:')
file.writelines(edit)
file.close()
#Program 4
#Program to read a text file and count number of
vowels and consonants
file = open('lyrics.txt','r')
text = file.read().split()
countV = 0
for V in text:
if V in vowels:
countV += 1
countC = 0
for C in text:
if C in cons:
countC += 1
print('The number of vowels are:', countV, '\n The
number of consonants are:', countC)
#Program 5
#Program that receives two numbers and generate a
random number from that range
#Program 6
#Program to implement stack operation
class Stack:
def _init_(self):
self.items = []
def is_empty(self):
return self.items == []
def pop(self):
return self.items.pop()
s = Stack()
while True:
print('push ')
print('pop ')
print('exit ')
do = input('Enter Your Choice:').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'exit':
break
#Program 7
#Program to generate fibonacci numbers
def fibonacci(N):
if N < 0:
print('Incorrect input')
elif N == 0:
return 0
elif N == 1 or N == 2:
return 1
else:
return fibonacci(N-1) + fibonacci(N-2)
print(fibonacci(int(input('Enter the number: '))))
#Program 8
#Program to create a binary file and display all the
records
import pickle
import sys
dict ={}
def write_in_file():
file = open('D:\\stud2.dat','ab')
no = int(input('Enter no of students: '))
def display():
file = open('D:\\stud2.dat','rb')
try:
while True:
stud = pickle.load(file)
print(stud)
except EOFError:
pass
file.close()
while True:
print('Menue \n 1-Write in a file \n 2-display')
print('3-exit \n')
ch = int(input('Enter your choice = '))
if ch == 1:
write_in_file()
if ch == 2:
display()
if ch == 3:
print('Thank You')
sys.exit()
#Program 9
#Program to create binary file and display only those
records having Grade = 'A'
import pickle
import sys
dict ={}
def write_in_file():
file = open('D:\\stud2.dat','ab')
no = int(input('Enter no of students: '))
def display():
file = open('D:\\stud2.dat','rb')
try:
while True:
stud = pickle.load(file)
if dict['Grade'] == 'A':
print(stud)
break
except EOFError:
pass
file.close()
while True:
print('Menue \n 1-Write in a file \n 2-display')
print('3-exit \n')
ch = int(input('Enter your choice = '))
if ch == 1:
write_in_file()
if ch == 2:
display()
if ch == 3:
print('Thank You')
sys.exit()
#Program 10
#Program to create binary file and search & display
for givrn roll number
import pickle
import sys
dict ={}
def write_in_file():
file = open('D:\\stud2.dat','ab')
no = int(input('Enter no of students: '))
def display():
file = open('D:\\stud2.dat','rb')
try:
while True:
stud = pickle.load(file)
print(stud)
except EOFError:
pass
file.close()
def search():
file = open('D:\\stud2.dat', 'rb')
r = int(input('Enter the roll number to search:
'))
found = 0
try:
while True:
data = pickle.load(file)
if data['roll'] == r:
print('The Roll No = ', r, 'record is
found')
print(data)
found = 1
break
except EOFError:
pass
if found == 0:
print('The Roll No =', r, 'record is not
found')
file.close()
while True:
print('Menue \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()
#Program 11
#Program to fetch all records from STUDENT table of
SCHOOL database
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="SCHOOL")
cur=con.cursor()
cur.execute('select * from STUDENT')
cur.fetchall()
#Program 12
#Program to fetch all records where Grade = 'A' from
STUDENT table of SCHOOL database
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="SCHOOL")
cur=con.cursor()
cur.execute('select * from STUDENT where Grade =
"A"')
cur.fetchall()
#Program 13
#Program to insert a new tuple in STUDENT table of
SCHOOL database
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="SCHOOL")
cur=con.cursor()
cur.execute('insert into STUDENT values(1129,
"NAVAL", "XI", "B")')
cur.commit()
#Program 14
#Program to update particular student record from
STUDENT table of SCHOOL database
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="SCHOOL")
cur=con.cursor()
m = input('Enter Marks: ')
r = int(input('Enter Roll no: '))
cur.execute('update STUDENT set marks = "{}" where
Roll_No = "{}"'.format(m, r))
cur.commit()
#Program 15
#Program to display particular student record from
STUDENT table of SCHOOL database
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="SCHOOL")
cur=con.cursor()
r = int(input('Enter Roll no: '))
cur.execute('select * from STUDENT'.format(r))
cur.commit()
#Program 16
#Progrogram to read a text file and count number of
lines starting with the letter 'A'
def countlines():
file = open['readlines.txt','r']
lines = file.readlines()
count = 0
for i in lines:
if i[1]=='A':
count += count
print('Number of lines starting with "A" is:',
count)
file.close()
#Program 17
#Program to delete record from table alpha
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="alpha")
cur=con.cursor()
r = int(input('Enter Roll no: '))
cur.execute('delete from alpha where
Roll_No"{}"'.format(r))
cur.commit()
#Program 18
#Program to create a graph
#Program 19
#Program to find the sum
def sum(a,*b):
c = a
for i in b:
c = c + i
print(c)
sum(5,6,34,78)
#Program 20
#Program to find Simple Interest
#Program 21
#Program to fetch many functions at a time
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="alpha")
cur=con.cursor()
cur.execute('select * from alpha')
data=cur.fetchmany(2)
for i in data:
print(i)
print('Total number of rows retrieved=',
cur.rowcount)
#Program 22
#Program to fetch one function at a time
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="alpha")
cur=con.cursor()
cur.execute('select * from alpha')
data=cur.fetchone()
for i in data:
print(i)
print('Total number of rows retrieved=',
cur.rowcount)
#Program 23
#Program to fetch all functions at a time
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="alpha")
cur=con.cursor()
cur.execute('select * from alpha')
data=cur.fetchall()
for i in data:
print(i)
print('Total number of rows retrieved=',
cur.rowcount)
#Program 24
#Program to find Sum, Difference, Product and
Division of values
def op (a,b):
return (a+b, a-b, a*b, a/b)
x = float(input('Enter 1st no : '))
y = float(input('Enter 2nd no : '))
s,d,p,dv = op (x,y)
print('Sum = ', s)
print('Difference = ', d)
print('Product = ', p)
print('Division = ', dv)
print = ()
#Program 25
#Program to convert octa into hexadecimal
#Program 27
#Program to create database from python
import mysql.connector
connection=mysql.connector.connect(host="localhost",u
ser="root",password="1234")
curser=connection.cursor()
curser.execute('Create database product1')
print('Query executed successfully...')
#Program 28
#Program to get Sum and Difference of the values3
#Program 30
#Program to count total number of rows retrieved
import mysql.connector
con=mysql.connector.connect(host="localhost",user="ro
ot",password="1234",database="alpha")
cur=con.cursor()
cur.execute('select * from alpha')
data=cur.fetchall()
for i in data:
print(i)
print('Total number of rows retrieved=',
cur.rowcount)
#Program 31
#Program to capitalize first letter of the string
#Program 32
#Program to find the index of any value in the list
L1 = [16,18,11,25,18,34,14]
L1.index(18)
#Program 33
#Program to add a new value in the list
#Program 34
#Program to merge two lists
#Program 36
#Program to find key in the dictionary
#Program 37
#Program to sort the list
alist = [15,6,13,22,3,52,2]
print('Original list is:', alist)
n = len(alist)
for i in range (n):
for j in range(0,n-i-1):
if alist[j] > alist[j+1]:
alist[j], alist[j+1] = alist[j+1],
alist[j]
print('List after sorting:', alist)
#Program 38
#Program to check whether triplet is Pythagorean or
not
#Program 39
#Program to find the sum of power and square of the
value
#Program 40
#Program to find the power of the value
def power(a,b):
r = a**b
return r
def cpower(x):
x = x+2
x = power(x,0.5)
return x
n = 5
result = cpower(n)
print(result)
#Program 41
#Program to show the use of global function
c = 10
def add():
global c
c = c+2
print('Inside add():',c)
add()
c = 15
print('In main:',c)
#Program 42
#Program to use the Pascal's Triangle
#Program 43
#Program to that takes a positive integer and returns
the one's position digit of the integer
def getOnes(num):
onesDigit = num%10
return onesDigit
#Program 44
#Program to count the number of digits in an integer
without using a loop
def um_len(n):
num = str(n)
return len(num)
n1 = int(input('Enter number 1:'))
n2 = int(input('Enter number 2:'))
n3 = int(input('Enter number 3:'))
print(n1,'s length is', num_len(n1), 'digits.')
print(n2,'s length is', num_len(n2), 'digits.')
print(n3,'s length is', num_len(n3), 'digits.')