0% found this document useful (0 votes)
42 views31 pages

2023 24 - Practicalprograms (1 25)

Uploaded by

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

2023 24 - Practicalprograms (1 25)

Uploaded by

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

COMPUTER SCIENCE

PRACTICAL PROGRAM SOLUTIONS (2023-2024)

PROGRAM 1:

# Write a Python Program to find largest number in a list.

SOURCE CODE:
list1 = [10, 20, 4, 45, 99]
list1.sort()
print("Largest element is:", list1[-1])

OUTPUT:
Largest element is: 99
PROGRAM 2:
# Write a Python Program to create a dictionary containing names of competition winner
students as keys and number of their wins as values.

SOURCE CODE:
n=int(input("How many students ?"))
CompWinners={}
for a in range(n):
key=input("Name of the Student:")
value=int(input("Number of competitions won:"))
CompWinners[key]=value
print("The dictionary now is:")
print(CompWinners)

OUTPUT:
How many students ?
5
Name of the Student:Navel
Number of competitions won:5
Name of the Student:Zainab
Number of competitions won:3
Name of the Student:Nita
Number of competitions won:3
Name of the Student:Rosy
Number of competitions won:1
Name of the Student:Jamshed
Number of competitions won:4
The dictionary now is:
{'Navel': 5, 'Zainab': 3, 'Nita': 3, 'Rosy': 1, 'Jamshed': 4}
PROGRAM 3:
# Write a Python Program to accept 5 items into a list and reverse the list. Also swap the
first and last items in the list.

SOURCE CODE:
L=[]
for i in range(0,5):
L.append(input("Enter an item : "))
print("The original list is: ",L)
print("The reversed list is: ",L[::-1])
L[0],L[-1] = L[-1],L[0]
print ("The swapped list is: ", L)

OUTPUT:
Enter an item : 10
Enter an item : 40
Enter an item : 5
Enter an item : 23
Enter an item : 34
The original list is: ['10', '40', '5', '23', '34']
The reversed list is: ['34', '23', '5', '40', '10']
The swapped list is: ['34', '40', '5', '23', '10']
PROGRAM 4:
# Write a Python Program to check if a string is palindrome or not.

SOURCE CODE:
def isPalindrome(s):
return s == s[::-1]
getVal = input("Enter a string:")
ans = isPalindrome(getVal)
if ans:
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome ")

OUTPUT:
Enter a string:amma
Yes, it is a palindrome
Enter a string:student
No, it is not a palindrome
PROGRAM 5:
# Write a Python Program to check whether a value exists in dictionary.

SOURCE CODE:
D={101: "Peter",102:"Richard",103: "Firoza",104:"Parvathi"}
val = input('Enter Name : ')
found = 0
for k in D:
if val.lower() ==D[k].lower():
print("value found at key : ",k)
found = 1
if found == 0:
print("Value not found")

OUTPUT:
Enter Name : Peter
value found at key : 101
Enter Name : Sasi
Value not found
PROGRAM 6:
# Write a Python Program to calculate a factorial value by given number.

SOURCE CODE:
def factorial_num(number):
factorial = 1
for n in range(1, number + 1):
factorial = factorial * n
return factorial
print("FACTORIAL CALCULATION")
num=int(input("Enter the number:"))
print("Factorial of given number is:",factorial_num(num))

OUTPUT:
FACTORIAL CALCULATION
Enter the number:5
Factorial of given number is: 120
FACTORIAL CALCULATION
Enter the number:7
Factorial of given number is: 5040
PROGRAM 7:
# Write a Python Program to receives two numbers in a function and returns the results of
all arithmetic operations(+,-,*,/,%) on these numbers.

SOURCE CODE:
def arCalc(x,y):
return x+y,x-y,x*y,x/y,x%y
print("ARITHMETIC OPERATIONS")
num1=int(input("Enter number 1:"))
num2=int(input("Enter number 2:"))
add,sub,mul,div,mod=arCalc(num1,num2)
print("Sum of given numbers:",add)
print("Subtraction of given numbers:",sub)
print("Product of given numbers:",mul)
print("Division of given numbers:",div)
print("Modulo of given numbers:",mod)

OUTPUT:
ARITHMETIC OPERATIONS
Enter number 1:4
Enter number 2:7
Sum of given numbers: 11 Subtraction of given numbers: -3 Product of given numbers:
28
Division of given numbers: 0.5714285714285714 Modulo of given numbers: 4
PROGRAM 8:
# Write a Python Program to calculate simple interest using a function interest() that can
receive principal amount, time and rate and returns calculated simple interest. Do specify
default values for rate and time as 10% and 2 years respectively.

SOURCE CODE:
def interest(principal,time=2,rate=0.10):
return principal*rate*time
print("SIMPLE INTEREST CALCULATION")
prin=float(input("Enter principal amount:"))
print("Simple interest with default ROI and time values 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 values is:")
si2=interest(prin,time,roi/100)
print("Rs.",si2)

OUTPUT:
SIMPLE INTEREST CALCULATION
Enter principal amount:20000
Simple interest with default ROI and time values is: Rs. 4000.0
Enter rate of interest(ROI):5
Enter time in years:5
Simple interest with your provided ROI and time values is: Rs. 5000.0
PROGRAM 9:
# Write a Python Program to generates random numbers between 1 and 6 (simulates a
dice).

SOURCE CODE:
def fun():
import random
r=random.randint(1,6)
print("Random number generated between 1 to 6 :",r)
fun()

OUTPUT:
Random number generated between 1 to 6 : 5
Random number generated between 1 to 6 : 1
Random number generated between 1 to 6 : 3
PROGRAM 10:
# Write a Python Program to read a text file line by line and display each word separated
by '#'.

SOURCE CODE:
fileobj=open("text10.txt","r")
lines=fileobj.readlines()
for line in lines:
x=line.split()
for y in x:
print(y+" # ",end=" ")
print(" ")

OUTPUT:
Welcome # to #
Python #
World!!!!!! #
PROGRAM 11:

# Write a Python Program to display the size of a file after removing EOL characters,
leading and trailing white space and blank lines.

SOURCE CODE:
myfile=open("text10.txt","r")
str1=" "
size=0
tsize=0
while str1:
str1=myfile.readline()
tsize=tsize+len(str1)
size=size+len(str1.strip())
print("Size of file after removing all EOL characters & blank lines:",size)
print("the Total size of the file is:",tsize)
myfile.close()

OUTPUT:
The Content in text file is:
Welcome to Python World!!!
Size of file after removing all EOL characters & blank lines: 24
the Total size of the file is: 27
PROGRAM 12:
# Write a Python Program to get student data(rollno,name,marks) from user and write
onto a binary file.The program should be able to get data from the user and write onto the
file as long as the user wants.

SOURCE CODE:
import pickle
stud={}
stufile=open("stud.dat","wb")
ans='y'
while ans=='y':
rno=int(input("Enter the Roll number:"))
name=input("Enter the Name of the Student:")
marks=float(input("Enter marks:"))
stud['Rollno']=rno
stud['Name']=name
stud['marks']=marks
pickle.dump(stud,stufile)
ans=input("Want to enter more records? (Y/N)-")
stufile.close()

OUTPUT:
Enter the Roll number:11
Enter the Name of the Student:Gokul
Enter marks:83.5
Want to enter more records? (Y/N)-y
Enter the Roll number:12
Enter the Name of the Student:Mano
Enter marks:81.5
Want to enter more records? (Y/N)-y
Enter the Roll number:13
Enter the Name of the Student:James
Enter marks:80
Want to enter more records? (Y/N)-N
PROGRAM 13:
# Write a Python Program to create a binary file with roll number, name & marks, input a
roll number & update the marks.

SOURCE CODE:
import pickle
sdata={}
totals=int(input("Enter number of students :"))
fileobj=open("student.dat","wb")
for i in range(totals):
sdata["Roll no"]=int(input("Enter roll no. :"))
sdata["Name"]=input("Enter name :")
sdata["Marks"]=float(input("Enter marks :"))
pickle.dump(sdata,fileobj)
sdata={}
fileobj.close()
found=False
rollno=int(input("Enter roll number to update mark :"))
fileobj=open("student.dat","rb+")
try:
while True:
pos=fileobj.tell()
sdata=pickle.load(fileobj)
if (sdata["Roll no"]==rollno):
sdata["Marks"]=float(input("Enter new marks :"))
fileobj.seek(pos)
pickle.dump(sdata,fileobj)
found=True
except EOFError:
if found==False:
print("Roll number not found.")
else:
print("Student’s marks updated successfully.")
fileobj.close()
OUTPUT:
Enter number of students :2
Enter roll no. :01
Enter name :Priya
Enter marks :89.5
Enter roll no. :02
Enter name :Sheela
Enter marks :67
Enter roll number to update mark :02
Enter new marks :90
Student’s marks updated successfully.
PROGRAM 14:
# Write a Python Program to read a text file and display the number of vowels/
consonants/ uppercase/lowercase characters in the file.

SOURCE CODE:
fileobj=open("vowels.txt","r")
vowel=0
consonants=0
upper=0
lower=0
L=fileobj.read()
vowels=['a','e','i','o','u','A','E','I','O','U']
for i in L:
if i.isalpha():
if i.islower():
lower+=1
if i.isupper():
upper+=1
if i in vowels:
vowel+=1
else:
consonants+=1
print("Number of upper:",upper)
print("Number of lowercase:",lower)
print("Number of vowels:",vowel)
print("Number of consonants:",consonants)

OUTPUT:
The Content in vowels file is:
The Program will create the file name in your program's folder..

Number of upper: 2
Number of lowercase: 49
Number of vowels: 19
Number of consonants: 32
PROGRAM 15:
# Write a Python Program to create a CSV file by entering user id and password, read and
search the password for given user id.

SOURCE CODE:
import csv
with open("emp.txt","a") as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
userid=int(input("Enter user id:"))
password=int(input("Enter password:"))
ans=input("Do you wanna enter more data? (y/n)")
x=csv.writer(csvfile)
x.writerow([userid,password])
ans='y'
with open("emp.txt","r") as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
found=False
e=int(input("Enter the userid to search:"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("Password: ",row[1])
found=True
break \
if not found:
print("UserID is not found")
ans=input("Do you wat to search more?(y/n)")
ans='y'

OUTPUT:
Enter user id:1005 Enter password:34567
Do you wanna enter more data? (y/n)y
Enter user id:1003
Enter password:78267
Do you wanna enter more data? (y/n)n
Enter the userid to search:1005
Password: 34567
Do you wat to search more?(y/n)n
PROGRAM 16:
# Write a Python Program to create a function push(student) and pop(student) to add a
new student name and remove a student name from a list student, considering them to act
as PUSH and POP operations of stackData Structure in Python.

SOURCE CODE:
st=[ ]
def push(st):
sn=input("Enter name of student:")
st.append(sn)
def pop(st):
if(st==[]):
print("Stack is empty")
else:
print("Deleted student name is :",st.pop())
push(st)
print('After push :',st)
pop(st)
print('After pop: ',st)

OUTPUT:
Enter name of student:Mala
After push : ['Mala']
Deleted student name is : Mala
After pop: []
PROGRAM 17:
# Write a Python Program that has a list containing 10 integers. You need to help him
create a program with separate user defined functions to perform the following operations
based on this list.
Traverse the content of the list and push the ODD numbers into a stack.
Pop and display the content of the stack.

SOURCE CODE:
N=[12, 13, 34, 56, 21, 79, 98, 22,35, 38]
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in N:
if k%2!=0:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

OUTPUT:
35 79 21 13
PROGRAM 18:

# Write a Python Program that has created a dictionary containing top players and their
runs as key value pairs of cricket team. Write a program, with separate user defined
functions to perform the following operations:
Push the keys (name of the players) of the dictionary into a stack, where the
corresponding value (runs) is greater than 49.
Pop and display the content of the stack

SOURCE CODE:
SCORE={"KAPIL":40,"SACHIN":55 , "SAURAV":80,"RAHUL":35, "YUVRAJ":110 }
def PUSH(S,R):
S.append(R)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[ ]
for k in SCORE:
if SCORE[k]>49:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

OUTPUT:
YUVRAJ SAURAV SACHIN
PROGRAM 19:

Consider the following table ‘Doctor’. Write SQL commands for the following:

No Name Age Department Dateofadmin Charge Sex


1 Arpit 62 Surgery 21/01/06 300 M
2 Zayana 18 ENT 12/12/05 250 F
3 Kareem 68 Orthopedic 19/02/06 450 M
4 Abhilash 26 Surgery 24/11/06 300 M
5 Dhanya 24 ENT 20/10/06 350 F

QUESTION 1:
Create database HOSPITAL.
QUERY:
CREATE DATABASE HOSPITAL;
QUESTION 2:
Create the above table DOCTOR and insert the values mentioned.
QUERY:
CREATE TABLE DOCTOR (NO INT, NAME VARCHAR (20), AGE INT,
DEPARTMENT VARCHAR (20), DOJ DATE, CHARGE INT, SEX CHAR (1));
QUESTION 3:
Group & Display all the details of doctor according to their gender.
QUERY:
SELECT * FROM DOCTOR GROUP BY SEX;
QUESTION 4:
Remove the doctor, Kareem from the table.
QUERY:
DELETE FROM DOCTOR WHERE NO = 3;
QUESTION 5:
Display the total no of departments available in the doctor table.
QUERY:
SELECT ‘DEPARTMENT’, COUNT (DISTINCT (DEPARTMENT)) FROM
DOCTOR;
QUESTION 6:
Display the name, age and department who’s names ends with ‘A’
QUERY:
SELECT NAME, AGE, DEPARTMENT FROM DOCTOR WHERENAME LIKE
‘%A’;
QUESTION 3:

QUESTION:5

QUESTION:6
PROGRAM 20:
Consider the table ‘EMPLOYEES’
NO NAME DEPARTMENT DATE OFJOINING SALARY SEX
1 RAJA COMPUTER 21/05/1998 8000 M
2 SANGILA HISTORY 21/05/1997 9000 F
3 RITU SOCIOLOGY 29/08/1998 8000 F
4 KUMAR LINGUISTICS 13/06/1996 10000 M
5 VENKATRAMAN HISTORY 31/10/1999 8000 M
6 SIDHU COMPUTER 21/05/1986 14000 M
7 AISWARYA SOCIOLOGY 11/01/1988 12000 F

QUESTION 1:
Write a query to display the lowest salary of teacher in all the departments.
QUERY:
SELECT MIN (SALARY) AS 'LOWEST SALARY' FROM EMPLOYEES;
QUESTION 2:
Write a query to display the highest salary of male teachers.
QUERY:
SELECT MAX (SALARY) AS 'HIGHEST SALARY' FROM EMPLOYEES
WHERE SEX = 'M';
QUESTION 3:
Write a query to display the total salary of teachers in history department.
QUERY:
SELECT SUM (SALARY) AS 'TOTAL SALARY' FROM EMPLOYEES
WHERE DEPARTMENT = 'HISTORY';
QUESTION 4:
Write a query to display the average salary of teachers who has joined before
1/1/1998.
QUERY:
SELECT AVG (SALARY) AS 'AVERAGE SALARY' FROM
EMPLOYEESWHERE DOJ < '1998/01/01';
QUESTION 5:
Write a query to update the salary of all employees working in computer
department with 10% of their existing salary
QUERY:
UPDATE EMPLOYEES SET SALARY = SALARY + (SALARY *0.10)
WHERE DEPARTMENT = 'COMPUTER';
QUESTION 1:

QUESTION 2:

QUESTION 3:

QUESTION 4:
PROGRAM 21:
Consider the following table ‘ACTIVITY’

ACODE ACTIVITY STADIUM PARTICIPANTS PRIZE SCHEDULE


NAME NUM MONEY DATE
1001 RELAY 100x4 STAR 16 10000 23-JAN-04
ANNEX
1002 HIGH JUMP STAR 10 12000 12-DEC-03
ANNEX
1003 SHOT PUT SUPER 12 8000 14-FEB-04
POWER
1005 LONG JUMP STAR 12 9000 01-JAN-04
ANNEX
1008 DISCUSS SUPER 10 15000 19-MAR-04
THROW POWER

QUESTION 1:
Write a query to display the names of all the activities with their Acode in
descending order.
QUERY:
SELECT ACTIVITYNAME FROM ACTIVITY ORDER BY ACODE
DESC;
QUESTION 2:
Write a query to display the activity names, Acode in ascending order of
prize money who is in ‘Star Annex’ stadium.
QUERY:
SELECT ACTIVITYNAME, ACODE FROM ACTIVITY WHERE
STADUIM = ‘STAR ANNEX' ORDER BY PRIZE_MONEY;
QUESTION 3:
Write a query to display the details of all the activities for which schedule
date is earlier than ‘01/01/2004’ in ascending order of participants num.
QUERY:
SELECT * FROM ACTIVITY WHERE SCHEDULE_DATE < '2004/01/01'
ORDER BY PARTICIPANT_NUM;
QUESTION 4:
Write a query to display the total number of participants who have prize
money is more than 9000.
QUERY:
SELECT SUM (PARTICIPANT_NUM) AS 'TOTAL' FROM ACTIVITY
WHERE PRIZE_MONEY > 9000;
QUESTION 5:
Write a query to add a new column city.
QUERY:
ALTER TABLE ACTIVITY ADD CITY VARCHAR(20);
QUESTION 1:

QUESTION 2:

QUESTION 3:

QUESTION 4:
PROGRAM 22:
Write a program to connect Python with MySQL using database connectivity and
perform the Fetch operation on data in database:

SOURCE CODE:
import mysql.connector as m
c = m.connect(host = 'localhost', user= 'root', passwd = 'sqlpass', database='cs_db')
def select( ):
cur = c.cursor( )
cur.execute('select * from employee;')
data = cur.fetchall( )
for i in data:
for j in i:
print(j, end = "\t")
print( )
#______MAIN_____
select ()

OUTPUT:

E01 SIYA 54000


E02 JOY Null
E03 ALLEN 32000
E04 NEEN 42000
E05 BONIYA 25000
PROGRAM 23:
Write a program to connect Python with MySQL using database connectivity
andperform the insert operation on data in database:

SOURCE CODE:
import mysql.connector as m
c = m.connect (host = 'localhost', user= 'root', passwd = 'sqlpass', database='cs_db')
def inst( ):
cur = c.cursor ( )
Empid = input("Enter your Employee ID :")
name = input("Enter your Name :")
salary = input ("Enter your salary :")
cur.execute ('insert into employee values ("{0}","{1}", {2})'.format (Empid,
name, salary))
c.commit ( )
#_____MAIN___
inst ()

OUTPUT:

Enter your Employee ID: E07 Enter your Name: SMITH Enter your salary: 45000
PROGRAM 24:
Write a program to connect Python with MySQL using database connectivity
andperform the delete operation on data in database:

SOURCE CODE:
import mysql.connector as m
c = m.connect (host = 'localhost', user= 'root', passwd = 'sqlpass', database='cs_db')
def delEmp( ):
cur = c.cursor ( )
Empid = input("Enter your Employee ID :")
cur.execute ('delete from employee where EmpId = "{0}" '.format (Empid))
c.commit ( )
print(“Employee {0}, removed from the table”.format(Empid))
#____MAIN ___
delEmp ( )

OUTPUT

Enter your Employee ID: E05 Employee E05, removed from the table
PROGRAM 25:
Write a program to connect Python with MySQL using database connectivity and
update the salary of the employee ‘E02’ to 45,000 in the database table.

SOURCE CODE:
import mysql.connector as m
c = m.connect (host = 'localhost', user= 'root', passwd = 'sqlpass', database='cs_db')
def updEmp( ):
cur = c.cursor ( )
Empid = input("Enter your Employee ID :") salary = input ("Enter your
updated salary:")
cur.execute (‘update employee set salary = "{0}" where empid = “{1}”
'.format(Empid,salary))
c.commit ( )
print(“Employee {0}, salary have been updated to {1}”.
format(Empid,salary))
#_____MAIN_____
updEmp ( )

OUTPUT

Enter your Employee ID: E02


Enter your updated salary: 45000
Employee E02, salary have been updated to 45000

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy