Practical Qns+2 CS2022

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

PROGRAM NO:1

Write a program to check whether a number is prime or not.

Aim: To check whether the given number is prime or not.

Source code

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


if num > 1:
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")

else:
print(num,"is not a prime number")

OUTPUT:
Enter a number: 21
21 is not a prime number

Enter a number: 113


113 is a prime number
PROGRAM NO:2

Write a program using function to find fibanocci numbers

Aim : Define a function to to find fibanocci numbers

Source code:

def fibanocci(n):
if n<=1:
return n
else:
return(fibanocci(n-1)+fibanocci(n-2))

num=int(input("how many fibanocci numbers you want to display:"))


for i in range(num):
print(fibanocci(i),"",end="")

OUTPUT:

how many fibanocci numbers you want to display:10


0 1 1 2 3 5 8 13 21 34
PROGRAM NO:3

Write a Python program to find the factorial of a number provided by the user.

Aim: To find the factorial of a number provided by the user

Source code:
# To take input from the user
num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


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)

OUTPUT:

Enter a number: 0
The factorial of 0 is 1
Enter a number: 5
The factorial of 5 is 12
PROGRAM NO:4

Write a program to check whether the entered string is palindrome or not.

Aim: Input a string and check whether the entered string is palindrome or not

Source code:

my_str=input("Enter a string: ")


# make it suitable for caseless comparison
my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

OUTPUT:
Enter a string: English
The string is not a palindrome.
Enter a string: Malayalam
The string is a palindrome.
PROGRAM NO:5

Write a program to pass a list and double the odd values and half even values of a list
and display list element after changing

Aim: To pass a list and double the odd values and half even values of a list and
display list element after changing

Source code:

def oddeven(L):
L2=[]
for i in range(0,len(L)):
if L[i]%2==0:
e=L[i]/2
L2.append(e)
else:
e=L[i]*2
L2.append(e)
print(L2)
a= eval(input("Enter a list:"))
oddeven (a)

OUTPUT:

Enter a list:25,43,11,12,78,46,55,84,71
[50, 86, 22, 6.0, 39.0, 23.0, 110, 42.0, 142]
PROGRAM NO:6
Write a Python Program to pass n number in a tuple and Count Even and Odd Numbers in
Tuple .

Aim: To pass n number in a tuple and Count Even and Odd Numbers in Tuple .

Source code:
# Count of Tuple Even and Odd Numbers

#evodTuple = (2, 33, 45, 88, 77, 98, 54, 0, 17)


evodTuple=eval(input("Enter values to the Tuple: "))
print("Even and Odd Tuple Items = ", evodTuple)

tEvenCount = tOddCount = 0

for i in range(len(evodTuple)):
if(evodTuple[i] % 2 == 0):
tEvenCount = tEvenCount + 1
else:
tOddCount = tOddCount + 1

print("The Count of Even Numbers in evodTuple = ", tEvenCount)


print("The Count of Odd Numbers in evodTuple = ", tOddCount)
OUTPUT:
Enter values to the Tuple: 45,34,67,87,66,54,21,12,2,80,63
Even and Odd Tuple Items = (45, 34, 67, 87, 66, 54, 21, 12, 2, 80, 63)
The Count of Even Numbers in evodTuple = 6
The Count of Odd Numbers in evodTuple = 5

PROGRAM NO:7

Write a python program to count how many vowels present in the string.
Aim: To count how many vowels present in the string.

Source code:

OUTPUT:

Enter a string : Umbrella


Number of vowels : 3

PROGRAM NO:8
Write a program to generate random number between 1-6 by using user defined function.
AIM: To generate random number between 1-6 by using user defined function.
SOURCE CODE:
OUTPUT:

PROGRAM NO: 9
Write a program to read and display file content line by line with each word separated by #.

Aim : to read and display file content line by line with each word separated by #.

Source code:

OUTPUT:

PROGRAM NO: 10
Write a program to remove all the lines that contain the character ‘a’ in a file and
write it to another file.
Aim: To remove all the lines that contain the character ‘a’ in a file and write it to
another file.

Source code:

OUTPUT:

PROGRAM NO: 11
Write a program to read a file book.txt print the contents of file along with numbers of
words and frequency of word computer in it

Aim: To read a file book.txt print the contents of file along with numbers of
words and frequency of word computer in it

Source code:

f=open("book.txt","r")
L=f.readlines()
c1=0
print("Contents of file :",L)
for i in L:
j=i.split()
for k in j:
if k.lower() in "computer,Computer":
c1+=1
print("*****FILE END*****")
print()
print("Number of times 'computer' in the file =",c1)
f.close()

OUTPUT:
contents of file : ['Computer is an interesting subject. I like to study computer science.
Python is an interpreted, high-level computer programming language. Created by Guido
van Rossum . ']
*****FILE END*****

Number of times 'computer' in the file =


3

Program No: 12
Write a program read content of file and display total number of vowels, consonants,
lowercase and uppercase characters
AIM: Program to read the content of file and display the total number of consonants,
uppercase, vowels , lower case characters and special characters

SOURCE CODE:
f = open("file1.txt")
v=c=u=l= othr =0
data = f.read() content of file is:
vowels=['a','e','i','o','u'] India is my country I love python
for ch in data: Python learning is fun 123@
if ch.isalpha():
if ch.lower() in vowels: OUTPUT
v+=1
Total Vowels in file: 16
else:
Total Consonants in file: 30
c+=1
Total Capital letters in file: 3
if ch.isupper():
Total Small letters in file: 43
u+=1
elif ch.islower(): Total other characters : 4

l+=1
elif ch!=' ' and ch!='\n':
othr +=1
print("Total Vowels in file:",v)
print("Total Consonants in file:",c)
print("Total Capital letters in file:",u)
print("Total Small letters in file:",l)
print("Total other characters :", othr)
f.close()
Date
:
Program No: 13
Write a program to create binary file to store Rollno ,Name and Percentage of marks
Search any Rollno and display the details if Rollno found otherwise “Rollno not found”

AIM: program to create binary file to store Rollno ,Name and Percentage of marks Search
any Rollno and display the details if Rollno found otherwise “Rollno not found”
SOURCE CODE:
import pickle
def write():
with open("binary.dat",'wb') as f:
while True:
roll=int(input("Enter roll no:"))
name=input("Enter name")
per=int(input("Enter Percentage of marks :"))
Rec=[roll,name,per]
pickle.dump(Rec,f)
ch=input(" Do you want to enter more records(y/n) :")
if ch=='n' or ch=='N':
break
def read():
with open("binary.dat",'rb') as f:
try:
while True:
Rec=pickle.load(f)
print(Rec)
except EOFError:
print("The End of file reached")
def search():
with open("binary.dat",'rb') as f:
a=int(input("Enter roll number to be searched"))
found=0
OUTPUT:
try:
while True and found==0:
Enter roll no:12
Rec=pickle.load(f) Enter name Asha
if Rec[0]==a: Enter Percentage of marks :90
print("found") Do you want to enter more records(y/n): y

print(Rec) Enter roll no:13

found =1 Enter name jyothi

Enter Percentage of marks :87


except EOFError:
Do you want to enter more records(y/n) : y
print("Record not found")
Enter roll no:14
f.close()
Enter name vipin
Enter Percentage of marks :79

Do you want to enter more records(y/n): N


write() [12, 'Asha', 90]
read() [13, 'jyothi', 87]

search() [14, 'vipin', 79]


The End of file reached

Enter roll number to be searched 12


found
[12, 'Asha', 90]
Program No: 14
Write a program to create a binary file with roll number, name and marks, input a roll
number and update the marks.
Aim : To create a binary file with roll number, name and marks, input a roll number and
update the marks.
Source Code:
OUTPUT:
Program No: 15
Write a program to create a CSV file with empid, name and mobile no.
and search empid, update the record and display the records.

AIM: To create a CSV file with empid, name and mobile no. and search
empid, update the record and display the records

SOURCE CODE:

import csv
with open(r'C:\Users\Sid\AppData\Local\Programs\Python\Python38\employee.txt','a') as cf:
mywriter=csv.writer(cf,delimiter=',')
ans='y'
while ans.lower()=='y':
found=False
eno=int(input("Enter Employee Id : "))
name=input("Enter Name : ")
mobno=int(input("Enter Mobile No : "))
mywriter.writerow([eno,name,mobno])
ans=input("Want to enter more data?(y/n) :")
ans='y'
with open(r'C:\Users\Sid\AppData\Local\Programs\Python\Python38\employee.txt','r') as cf:
myreader=csv.reader(cf,delimiter=',')
ans='y'
while ans.lower()=='y':
f=False
e=int(input("Enter Employee Id to be searched: "))
for r in myreader:
if len(r)!=0:
if int(r[0])==e:
print("Name :",r[1])
print("Mobile No:",r[2])
found=True
break
if not found:
print("==========================")
print("Sorry Employee Id not found")
print("==========================")
ans= input("Want to search more ?(y/n) : ")
ans='y'
with open(r'C:\Users\Sid\AppData\Local\Programs\Python\Python38\employee.txt','a') as cf:
x=csv.writer(cf)
x.writerow([eno,name,mobno])
OUTPUT:
Enter Employee Id : 24
Enter Name : Varun
Enter Mobile No : 545
Want to enter more data?(y/n) :y
Enter Employee Id : 25
Enter Name : Geetha
Enter Mobile No : 23132
Want to enter more data?(y/n) :n
Enter Employee Id to be searched: 25
Name : Geetha
Mobile No: 23132
Want to search more ?(y/n) : y
Enter Employee Id to be searched: 24
Name : Varun
Mobile No: 545
Want to search more ?(y/n) : y
Enter Employee Id to be searched: 30
Sorry Employee Id not found
Want to search more ?(y/n) : n
Program No: 16
Write a program for linear search.

AIM: program for linear search

SOURCE CODE:

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

OUTPUT:
Enter the elements: 23,67,44,99,65,33,78,12
Enter the element that you want to search : 78
Element found at the position : 7
Program No: 17
Write a menu based program to perform the operations on stack in python using list.
AIM: Program to implement Stack in Python using List
SOURCE CODE:

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 display(stk):
if isempty(stk):
print("....Stack empty....")
else:
top=len(stk)-1
print(stk[top],"--top")
for a in range(top-1,-1,-1):
print(stk[a])
stack=[]
top=None
while True:
print("--Stack Operation...")
print("1.Push")
print("2.Pop")
print("3.Display stack")
print("4.exit ")
ch=int(input("Enter your choice"))
if ch==1:
item=int(input("Enter item"))
push(stack,item)
elif ch==2:
item=pop(stack)
if item=="underflow":
print("underflow Stack is empty")
else:
print("Popped item is:",item)
elif ch==3:
display(stack)
elif ch==5:
break
else:
print("Invalid choice")
OUTPUT:
--Stack Operation...
1.Push
2.Pop
3.Display stack
4.exit
Enter your choice1
Enter item45
--Stack Operation...
1.Push
2.Pop
3.Display stack
4.exit
Enter your choice 1
Enter item7
--Stack Operation...
1.Push
2.Pop
3.Display stack
4.exit
Enter your choice 1
Enter item12
--Stack Operation...
1.Push
2.Pop
3.Display stack
4.exit
Enter your choice 3
12 --top
7
45
--Stack Operation...
1.Push
2.Pop
3.Display stack
4.exit
Enter your choice2
Popped item is: 12
--Stack Operation...
1.Push
2.Pop
3.Peek
4.Display stack
5.exit
Enter your choice5
>>>
Program No: 18
Write a program Create a student table in SQL with attributes - sid, sname, section, gender
& mark. Integrate SQL with Python by importing the MySQL module. Display the details of
students from student table in descending order of marks from the Python script.

Aim: Create a student table in SQL with attributes - sid,sname,section,gender & mark.
Integrate SQL with Python by importing the MySQL module. Display the details ofstudents
from student table in descending order of marks from the Python script
SOURCE CODE:

import mysql.connector
mycon=mysql.connector.connect(host='localhost',user='root',password='root',database='school')
if mycon.is_connected() :
print("connection Successful")
cursor = mycon.cursor()
cursor.execute("select * from student order by marks desc")
data = cursor.fetchall()
c= cursor.rowcount
print("\n --------------OUTPUT----------------\n")
print("Total no. of rows retrieved in result set:",c)
print("\nDisplaying student records in descending order ofmarks:\n")
for row in data:
print(row)
mycon.close()
OUTPUT:

connection Successful

--------------OUTPUT----------------

Total no. of rows retrieved in result set: 5

Displaying student records in descending order ofmarks:

(12, 'Shruthi', 'B', 'f', 91.0)


(10, 'Abdul', 'A', 'm', 80.0)
(13, 'Karthik', 'A', 'm', 78.0)
(11, 'Sinan', 'B', 'm', 73.0)
(14, 'Lincy', 'A', 'f', 65.0)
Date
:
Program No: 19
Write a program Create a student table in SQL with attributes - sid, sname, section, gender
& mark. Integrate SQL with Python by importing the MySQL module. Display the details of
students from student table whose name starts with ‘S’ from the Python script.

Aim: Create a student table in SQL with attributes - sid, sname, section, gender & mark.
Integrate SQL with Python by importing the MySQL module. Display the details of students
from student table whose name starts with ‘S’ from the Python script.

SOURCE CODE:

import mysql.connector
mycon=mysql.connector .connect(host='localhost',user='root',password='root',database='school')
if mycon.is_connected() :
print("connection Successful")
cursor = mycon.cursor()
cursor.execute("select * from student where sname like 'S%'")
data = cursor.fetchall()
c= cursor.rowcount
print("\n OUTPUT \n")
print("Total no. of rows retrieved in result set:",c)
print("\nDisplaying student records whose name stars with 'S':\n")
for row in data:
print(row)
mycon.close()

OUTPUT:
connection Successful

OUTPUT

Total no. of rows retrieved in result set: 2

Displaying student records whose name stars with 'S':


(12, 'Shruthi', 'B', 'f', Decimal('91.00'))
(11, 'Sinan', 'B', 'm', Decimal('73.00'))
Date
:
Program No: 20

Write a program to create a student table in SQL with attributes - sid, sname, section,
gender & mark. Integrate SQL with Python by importing the MySQL module. Display
the details of all students from student table. Also, display lowest, highest, total marks
& average marks of students gender wise from within the Python script.

Aim: create a student table in SQL with attributes - sid, sname, section, gender & mark.
Integrate SQL with Python by importing the MySQL module. Display the details of all
students from student table. Also, display lowest, highest, total marks
& average marks of students gender wise from within the Python script.

SOURCE CODE:

import mysql.connector

mycon=mysql.connector.connect(host='localhost',user='root',password='root',

database='school')

if mycon.is_connected():

print("Connection Successful")

cursor = mycon.cursor()

cursor.execute("select * from student")

data = cursor.fetchall()

count = cursor.rowcount

print("\n OUTPUT \n")

print("Total no. of rows retrieved in result set:",count)

print("\nDisplaying student records:\n")


for row in data :
print(row)
cursor.execute("select gender,min(marks),max(marks),sum(marks),avg(marks) from
student group by gender")
data = cursor.fetchall()
print("\nDisplaying query result :\n")
print("GENDER\tMIN(MARK)\tMAX(MARK)\tSUM(MARK)\tAVG(MARK)")
print(" ")
for row in data:
print(row)
mycon.close()

OUTPUT:
Connection Successful

OUTPUT

Total no. of rows retrieved in result set: 5

Displaying student records:

(12, 'Shruthi', 'B', 'f', Decimal('91.00'))


(10, 'Abdul', 'A', 'm', Decimal('80.00'))
(13, 'Karthik', 'A', 'm', Decimal('78.00'))
(11, 'Sinan', 'B', 'm', Decimal('73.00'))
(14, 'Lincy', 'A', 'f', Decimal('65.00'))

Displaying query result :

GENDER MIN(MARK) MAX(MARK) SUM(MARK) AVG(MARK)


..................................................................................................................................................
('f', Decimal('65.00'), Decimal('91.00'), Decimal('156.00'), Decimal('78.000000'))
('m', Decimal('73.00'), Decimal('80.00'), Decimal('231.00'), Decimal('77.000000'))
>>>

Date
:
Program No: 21
Write a program to Create a student table in SQL with attributes - sid, sname, section
,gender & mark. Integrate SQL with Python by importing the MySQL module. Display the
details of all students from student table. Update 2 marks for all students of section A.
Display the contents of the table after updation using a Python script.

Aim: Create a student table in SQL with attributes - sid, sname, section ,gender & mark.
Integrate SQL with Python by importing the MySQL module. Display the details of all
students from student table. Update 2 marks for all students of section A. Display the
contents of the table after updation using a Python script.

SOURCE CODE:
import mysql.connector
mycon=mysql.connector .connect(host='localhost',user='root',password='root',database='school')
if mycon.is_connected() :
print("Successful Connection")
cursor = mycon.cursor()
cursor.execute("select * from student")
data = cursor.fetchall()
count = cursor.rowcount
print("\n OUTPUT \n")
print("Total no. of rows retrieved in result set :",count)
print("\nDisplaying student records before updation:\n")
for row in data:
print(row)
cursor.execute("update student set marks = marks+2 where sec = 'A'")
mycon.commit()
cursor.execute("select * from student")
data = cursor.fetchall()
print("\nDisplaying query result after updation:\n")
for row in data:
print(row)
mycon.close()

OUTPUT:

Successful Connection

OUTPUT

Total no. of rows retrieved in result set : 5

Displaying student records before updation:

(12, 'Shruthi', 'B', 'f', Decimal('91.00'))


(10, 'Abdul', 'A', 'm', Decimal('82.00'))
(13, 'Karthik', 'A', 'm', Decimal('80.00'))
(11, 'Sinan', 'B', 'm', Decimal('73.00'))
(14, 'Lincy', 'A', 'f', Decimal('67.00'))

Displaying query result after updation:

(12, 'Shruthi', 'B', 'f', Decimal('91.00'))


(10, 'Abdul', 'A', 'm', Decimal('84.00'))
(13, 'Karthik', 'A', 'm', Decimal('82.00'))
(11, 'Sinan', 'B', 'm', Decimal('73.00'))
(14, 'Lincy', 'A', 'f', Decimal('69.00'))
>>>
SQL
Consider the tables given below and answer the questions that follow:

Table: Employee
No Name Salary Zone Age Grade Dept
1 Mukul 30000 West 28 A 10
2 Kritika 35000 Centre 30 A 10
3 Naveen 32000 West 40 NULL 20
4 Uday 38000 North 38 C 30
5 Nupur 32000 East 26 NULL 20
6 Moksh 37000 South 28 B 10
7 Shelly 36000 North 26 A 30

Table: Department
Dept DName MinSal MaxSal HOD
10 Sales 25000 32000 1
20 Finance 30000 50000 5
30 Admin 25000 40000 7

WRITE SQL COMMANDS TO:

Create Table
1.Create the table Employee.
2.Create the table Department.
Insert data in a table
3.Insert data in the table Employee
4.Insert data in the table Department.
Simple Select
5.Display the Salary, Zone, and Grade of all the employees.
6.Display the name of all the employees along with their annual salaries.
The new column should be given the name “Annual Salary”.
Conditional Select using Where Clause
7.Display the details of all the employees who are below 30 years of age.
Using DISTINCT Clause
8.Display the names of various zones from the table Employee. A zone name should appear only
once.
Using Logical Operators (NOT, AND, OR)
9.Display the details of all the employees who are getting a salary of more than 35000 in the
department 30.
10.Display the names and salaries of all the employees who are not working in department 20.
11.Display the details of all the employees whose salary is between 32000 and 38000.

Using IN Operator
12.Display the names of all the employees who are working in department 20 or 30.
(Using IN operator)
Using BETWEEN Operator
13.Display the details of all the employees whose salary is between 32000 and 38000.
14.Display the details of all the employees whose grade is between ‘A’ and ‘C’.
Using LIKE Operator
15.Display the name, salary, and age of all the employees whose names start with ‘M’.
16.Display the name, salary, and age of all the employees whose names contain ‘a’ in the
descending order of their names.
17.Display the details of all the employees whose names contain ‘a’ as the second character.
Using Aggregate functions
18.Display the highest and the lowest salaries being paid in department 10.
19.Display the number of employees working in department 10.
Using ORDER BY clause
20.Display the name and salary of all the employees in the ascending order of their salaries.
Using GROUP BY clause
21.Display the total number of employees in each department.
22.Display the highest salary, lowest salary, and average salary of each zone.
Using UPDATE, DELETE, ALTER TABLE
23.Put the grade B for all those whose grade is NULL.
24.Increase the salary of all the employees above 30 years of age by 10%.
25.Delete the records of all the employees whose grade is C and salary is below 30000.
26.Add another column HireDate of type Date in the Employee table.
JOIN of two tables
27.Display the name, salary of all the employees who work in Sales department.
28.Display the Name and Department Name of all the employees.
29.Display the names of all the employees whose salary is out of the specified range for the
corresponding department.
30.Display the name of the department and the name of the corresponding HOD for all the
departments.

You might also like