0% found this document useful (0 votes)
40 views

Python Programs Class-12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Python Programs Class-12

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Delhi Public School NTPC,

Korba

AISSCE 2020-21
COMPUTER SCIENCE
PRACTICALS

Made by – Ashutosh Singh


Board Roll NO. - 12672830
#Program 1
#Program to read a text file and count number of
lines and words present

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')

vowels = set('A, E, I, O, U, a, e, i, o, u')


cons = set('B, C, D, F, G, H, J, K, L, M, N, P, Q, R,
S, T, V, W, X, Y, Z, b, c, d, f, g, h, j, k, l, m, n,
p, q, r, s, t, v, w, x, y, z')

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

from random import randint


def ran(x, y):
return randint(x, y)
print('Three random numbers are:', ran(1, 50),
ran(51, 100), ran(101,200))

#Program 6
#Program to implement stack operation

class Stack:
def _init_(self):
self.items = []
def is_empty(self):
return self.items == []

def push(self, data):


self.item.append(data)

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: '))

for i in range (no):


print('Enter details of student', i+1)

dict['Roll_No'] = int(input('Enter the roll


number: '))

dict['Name'] = input('Enter the name: ')

dict['Class'] = input('Enter the class: ')

dict['Marks'] = int(input('Enter the marks:


'))

dict['Grade'] = input('Enter the grade: ')


pickle.dump(dict,file)
file.close()

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: '))

for i in range (no):


print('Enter details of student', i+1)

dict['Roll_No'] = int(input('Enter the roll


number: '))

dict['Name'] = input('Enter the name: ')

dict['Class'] = input('Enter the class: ')

dict['Marks'] = int(input('Enter the marks:


'))

dict['Grade'] = input('Enter the grade: ')


pickle.dump(dict,file)
file.close()

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: '))

for i in range (no):


print('Enter details of student', i+1)
dict['Roll_No'] = int(input('Enter the roll
number: '))

dict['Name'] = input('Enter the name: ')

dict['Class'] = input('Enter the class: ')

dict['Marks'] = int(input('Enter the marks:


'))

dict['Grade'] = input('Enter the grade: ')


pickle.dump(dict,file)
file.close()

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

import matplotlib.pyplot as plt


x=[1,4,7,9]
y=[2,45,12,48]
plt.plot(x,y)
plt.show()

#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

def interest(principal, time = 2,rate = 0.10):


return principal * rate * time
prin = float(input('Enter principal amount : '))
print('Simple interest with default ROI and time
value is : ')
si1 = interest(prin)
print('Rs.', si1)
roi = float(input('Enter rate of interest (ROI) : '))
time = int(input('Enter time in years : '))
print('Simple interest with your provided ROI and
time value is : ')
si2 = interest(prin, time, roi/100)
print('Rs.', si2)

#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

num = int(input('Enter a number : '))


print('Number entered = ', num)
Onum = oct(num)
Hnum = hex(num)
print('octal conversion yields', Onum)
print('hexadecimal conversion yields', Hnum)
#Program 26
#Program to use array

from array import *


vals = array('i', [5,9,-8,4,2])
newArr = array(vals.typecode,(a*a for a in vals))
for e in newArr:
print(e)

#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

def add (a,b):


return a+b
def diff (a,b):
return a-b
x = float(input('Enter 1st no : '))
y = float(input('Enter 2nd no : '))
print ('Sum = ', add (x,y), ',', 'Difference = ',
diff (x,y))
print = ()
#Program 29
#program to enter the Roll No., Name and Marks of the
students

count = int(input('How many students are there in the


class?'))
fileout = open('Marks.det','w')
for i in range(count):
print('Enter details for student',(i+1),'below:')
rollno = int(input('Rollno:'))
name = input('Name:')
marks = float(input('Marks:'))
rec = str(rollno)+','+name+','+str(marks)+'\n'
fileout.write(rec)
fileout.close()

#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

string = input('Enter a string:')


length = len(string)
a = 0
end = length
string2 = ''
while a < length :
if a == 0:
string2 += string[0].upper()
a += 1
elif (string [a] == '' and string[a+1] != ''):
string2 += string[a]
string2 += string[a+1].upper()
a += 2
else:
string2 += string[a]
a += 1
print ('Original string:', string)
print ('Capitalized words string:', string2)

#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

Colours = ['red', 'green', 'blue', 'yellow',


'violet', 'orange']
Colours.append('indigo')

#Program 34
#Program to merge two lists

t1 = ['alpha', 'beta', 'gamma']


t2 = ['theta', 'delta']
t1.extend(t2)
#Program 35
#Program to find the length of the dictionary

Emp = {'name':'John', 'salary':1000000, 'age':35,


'company': 'Apple'}
len(Emp)

#Program 36
#Program to find key in the dictionary

Emp = {'name':'John', 'salary':1000000, 'age':35,


'company': 'Apple'}
Emp.keys()

#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

A=int(input("Enter the first no.: "))


B=int(input("Enter the second no.: "))
C=int(input("Enter the third no.: "))
if A*A==(B*B)+(C*C):
print("Triplet is a Pythagorean")
elif B*B==(A*A)+(C*C):
print("Triplet is a Pythagorean")
elif C*C==(A*A)+(B*B):
print("Triplet is a Pythagorean")
else:
print("Triplet is not a Pythagorean triplet")
input()

#Program 39
#Program to find the sum of power and square of the
value

def power (b,p):


y = b**p
return y
def calcSquare(x):
a = power(x,2)
return a
n = 5
result = calcSquare(n) + power(3,3)
print(result)

#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

n=int(input("Enter number of rows : "))


s=(n-1)
for i in range(1,n+1):
print(" "*s, (str(i)+" ")*i)
s-=1
input()

#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.')

You might also like