Professional Documents
Culture Documents
Class XII 083 - Computer Science Record
Class XII 083 - Computer Science Record
Program Code:
inp = input( )
print(inp)
Output:
Hi, Welcome to 083 - Computer Science Lab
Hi, Welcome to 083 - Computer Science Lab
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Smallest of two numbers
02
Program Code:
Output:
Enter First Number:25
Enter Second Number:15
15 is smallest
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Biggest of three numbers
03
Program Code:
Output:
Enter First Number:10
Enter Second Number:20
Enter Third Number:30
30 is Biggest
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Half pyramid pattern with stars(*)
04(a)
Program Code:
rows = 5
for i in range(rows):
for j in range(i+1):
print("*", end=' ')
print("\n")
Output:
*
* *
* * *
* * * *
* * * * *
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Inverted half pyramid using numbers
04(b)
Program Code:
rows = 5
for i in range(rows, 0, -1):
for j in range(1, i+1):
print(j, end=" ")
print("\n")
Output:
1 2 3 4 5
1 2 3 4
1 2 3
1 2
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Alphabetic Pattern
04(c)
Program Code:
# Alphabetic Pattern
Output:
A
AB
ABC
ABCD
ABCDE
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Sum of Series of 1 + x^2 + x^3 + ....+ x^n
05(a)
Program Code:
Output:
Enter Which Series:2
Enter the Terms:5
1 2.0 4.0 8.0 16.0
31.0
Result:
The above program was successfully executed and displays
the result
Pr No: Check Perfect number, an Amstrong Date:
06 number or a Palindrome number
Program Code:
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Check the number is a prime or composite number
07
Program Code:
Output:
Enter any number:19
19 number is prime but not composite number
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Display the terms of a Fibonacci series
08
Program Code:
firstterm = 0
secondterm = 1
counter = 0
totalterms = int(input("Please enter how many terms: "))
if totalterms <= 0:
print("Please enter only positive integers")
elif totalterms==1:
print(firstterm)
else:
print("Fibonacci Series: ")
while counter<totalterms:
print(firstterm)
sum = firstterm+secondterm
firstterm = secondterm
secondterm = sum
counter=counter+1
Output:
Please enter how many terms: 8
Fibonacci Series:
0
1
1
2
3
5
8
13
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Display the terms of a Fibonacci series
09
Program Code:
Output:
Enter First number :57
Enter Second number :18
GCD of 57 and 18 = 3
LCM of 57 and 18 = 342.0
Result:
The above program was successfully executed and displays
the result
Pr No: Count and display the number of vowels, consonants, Date:
10 uppercase, lowercase characters in string
Program Code:
Output:
Enter any string :083 Computer Science
Total number of vowel: 6
Total number of consonent: 14
Total number of uppercase letter: 2
Total number of lowercase letter: 13
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Palindrome String
11
Program Code:
#Palindrome String
string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")
Output:
Enter a letter:malayalam
The letter is a palindrome
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Largest or Smallest number in a list
12
Program Code:
Output:
List Size: 6
Enter number 50
Enter number 12
Enter number 75
Enter number 24
Enter number 25
Enter number 36
Largest element in the list is 75
Smallest element in the list is 12
Result:
The above program was successfully executed and displays
the result
Pr No: Swapping elements at the even location with the Date:
13 elements at the odd location
Program Code:
# Swapping elements at the even location with the elements at the odd location
mylist = []
n = int(input("Enter elements for the list: "))
for i in range(n):
value = int(input("Enter the Values:"))
mylist.append(value)
print("The original list : " + str(mylist))
odd_i = []
even_i = []
for i in range(0, len(mylist)):
if i % 2:
even_i.append(mylist[i])
else :
odd_i.append(mylist[i])
result = odd_i + even_i
print("Separated odd and even index list: " + str(result))
Output:
Enter elements for the list: 6
Enter the Values:12
Enter the Values:24
Enter the Values:36
Enter the Values:48
Enter the Values:60
Enter the Values:72
The original list : [12, 24, 36, 48, 60, 72]
Separated odd and even index list: [12, 36, 60, 24, 48, 72]
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Search an Element in a List
14
Program Code:
Output:
Enter the elements for the list: 6
Enter the Value:25
Enter the Value:50
Enter the Value:75
Enter the Value:100
Enter the Value:125
Enter the Value:150
Enter an element to be search:
125
Element found at Index: 4
Element found at Position: 5
Result:
The above program was successfully executed and displays
the result
Pr No: Create a dictionary with the roll number, name and Date:
15 marks of n students in a class and display the names
of students who have marks above 75
Program Code:
Output:
Enter number of students: 5
Enter Details of student No. 1
Roll No: 499
Student Name: Bharath
Marks: 85
Enter Details of student No. 2
Roll No: 599
Student Name: Babu
Marks: 74
Enter Details of student No. 3
Roll No: 699
Student Name: Barani
Marks: 89
Enter Details of student No. 4
Roll No: 799
Student Name: Baskar
Marks: 70
Enter Details of student No. 5
Roll No: 899
Student Name: Bala
Marks: 76
{499: ['Bharath', 85], 599: ['Babu', 74], 699: ['Barani', 89], 799: ['Baskar',
70], 899: ['Bala', 76]}
Student's name who get more than 75 marks is/are Bharath
Student's name who get more than 75 marks is/are Barani
Student's name who get more than 75 marks is/are Bala
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Simple Calculator using user defined function
16
Program Code:
num1 = int(input())
op = input()
num2 = int(input())
simcal(num1,op,num2)
Output:
25
*
8
200
Result:
The above program was successfully executed and displays
the result
Pr No: Read a text file line by line and Date:
17 display each word separated by # symbol
smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)
Program Code:
#Read a text file line by line and display each word separated by # symbol
file = open("smartwatch.txt","r")
lines = file.readlines()
for line in lines:
words = line.split()
for word in words:
print(word + "#",end = "")
print(" ")
Output:
A#smartwatch#is#a#wearable#computer#in#the#form#of#a#watch;#
modern#smartwatches#provide#a#local#touchscreen#interface#for#daily#use,#
while#an#associated#smartphone#app#provides#for#management#and#
telemetry#(such#as#long-term#biomonitoring)#
Result:
The above program was successfully executed and displays
the result
Pr No: Read a text file and display the number of vowels/ Date:
18 consonants/uppercase/lowercase characters in the file
smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)
Program Code:
#Read a text file and display the number of vowels / consonants / uppercase
#/lowercase characters in the file
myfile = open("smartwatch.txt","r")
vowel = consonent = uppercase = lowercase= 0
s = myfile.read()
for i in s:
if i.isalpha():
if(i in ('AEIOUaeiou')):
vowel = vowel +1
else:
consonent = consonent + 1
if i.isupper() :
uppercase = uppercase + 1
if i.islower():
lowercase = lowercase + 1
print("Total number of vowel:",vowel)
print("Total number of consonent:",consonent)
print("Total number of uppercase letter:",uppercase)
print("Total number of lowercase letter:",lowercase)
Output:
Total number of vowel: 76
Total number of consonent: 123
Total number of uppercase letter: 1
Total number of lowercase letter: 198
Result:
The above program was successfully executed and displays
the result
Pr No: Remove all the lines that contain the character `a' Date:
19 in a file and write it to another file
smartwatch.txt
A smartwatch is a wearable computer in the form of a watch;
modern smartwatches provide a local touchscreen interface for daily use,
while an associated smartphone app provides for management and
telemetry (such as long-term biomonitoring)
hello
computer
modern
biomonitoring
telemetry
Program Code:
#Remove all the lines that contain the character `a' in a file and write it
#to another file
f1 = open("smartwatch.txt")
f2 = open("newfile.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("newfile.txt","r")
Output:
## File Copied Successfully! ##
newfile.txt
hello
computer
modern
biomonitoring
telemetry
Result:
The above program was successfully executed and displays
the result
Pr No: Create a binary file with name and roll number. Date:
20 Search for a given roll number and display the
name, if not found display appropriate message
Program Code:
#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
import pickle
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
break
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
Output:
Result:
The above program was successfully executed and displays
the result
Pr No: Create a binary file with roll number, name and Date:
21 marks.Input a roll number and update details.
Program Code:
import pickle
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()
Output:
Result:
The above program was successfully executed and displays
the result
Pr No: Write a random number generator that generates Date:
22 random numbers between 1 and 6 (simulates a dice)
Program Code:
#Write a random number generator that generates random numbers between 1 and
#6 (simulates a dice)
import random
def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
Output:
Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.
>1
Rolling dice...
Your number is:
5
>2
Rolling dice...
Your number is:
6
>3
Rolling dice...
Your number is:
2
>4
Rolling dice...
Your number is:
3
>5
Rolling dice...
Your number is:
6
>6
Rolling dice...
Your number is:
1
>7
Rolling dice...
Your number is:
2
>quit
>>>
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
To implement a stack using list
23
Program Code:
#To implement a stack using list
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
Output:
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
stack is empty
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:225
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:1
enter item:325
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
325 <-top
225
125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:2
poped
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:4
225 <-top
125
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:3
top most item is: 225
stack operation
1.push
2.pop
3.peek
4.display
5.exit
enter choice:5
>>>
Result:
The above program was successfully executed and displays
the result
Pr No: Create a CSV file by entering user-id and password, Date:
24 read and search the password for given user-id.
Program Code:
#Create a CSV file by entering user-id and password,
#read and search the password for given user-id.
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)
if i[0] == given:
print(i[1])
break
Output:
enter id: class12
enter password: class12B2023
press Y/y to continue and N/n to terminate the program
y
enter id: class11
enter password: class11B2024
press Y/y to continue and N/n to terminate the program
y
enter id: class10
enter password: class10B2025
press Y/y to continue and N/n to terminate the program
n
enter the user id to be searched
class11
class11B2024
Result:
The above program was successfully executed and displays
the result
Pr No: Date:
Database Table Creation
25
desc student;
Altering Table:
desc student;
desc student;
# Field Type Null Key Default Extra
1 admn_no varchar(5) NO PRI NULL
2 stud_name varchar(25) YES NULL
3 gender varchar(6) YES NULL
4 class varchar(3) YES NULL
5 section varchar(2) YES NULL
Updating Table:
SQL Joins:
select
issue_book_details.Stud_Name,issue_book_details.Class,add_book_detail.Boo
k_Title,add_book_detail.Price,issue_book_details.Issue_Date,issue_book_de
tails.Return_Date from add_book_detail inner join issue_book_details on
add_book_detail.Book_Issue_No = issue_book_details.Book_Issue_No;
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base = "school")
print(mydb)
Output
<mysql.connector.connection_cext.CMySQLConnection object at
0x0000023EDCC672B0>
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234")
mycursor=mydb.cursor()
#mycursor.execute("create database if not exists school")
mycursor.execute("show databases")
for x in mycursor:
print(x)
Output
('12class',)
('information_schema',)
('mysql',)
('performance_schema',)
('sakila',)
('school',)
('sys',)
('testdb',)
('world',)
Create Table
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("create table stud(rollno int(3) primary key,name
varchar(20),age int(2))")
print("Successfully Table Created")
Output
Successfully Table Created
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
while 1==1:
ch=int(input("enter 100 to exit any other no to insert record into student
table"))
if ch==100:
break
rollno=int(input("Enter rollno"))
name=input("Enter name")
age=int(input("Enter Age"))
mycursor.execute("insert into student
values('"+str(rollno)+"','"+name+"','"+str(age)+"')")
mydb.commit()
Output
enter 100 to exit any other no to insert record into student table10
Enter rollno565
Enter nameTharun
Enter Age18
enter 100 to exit any other no to insert record into student table100
Search Records
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
rollno=int(input("enter rollno"))
mycursor.execute("select * from student where rollno='"+str(rollno)+"'")
for x in mycursor:
print(x)
Output
enter rollno565
(565, 'Tharun', 18)
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myrecords=mycursor.fetchall()
for x in myrecords:
print (x)
Output
(565, 'Tharun', 18)
update
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("update student set marks=99 where rollno=2")
mydb.commit()
delete
import mysql.connector
mydb=mysql.connector.connect(host="127.0.0.1",user="root",passwd="1234",data
base="school")
mycursor=mydb.cursor()
mycursor.execute("delete from student where rollno=1")
mydb.commit()