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

CS Practical File

The document contains 10 questions related to Python programming. Each question provides sample code to perform a task using functions. The code takes inputs, performs operations like searching, sorting, counting etc. and provides the output. The questions cover various concepts in Python like functions, lists, tuples, strings, file handling etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

CS Practical File

The document contains 10 questions related to Python programming. Each question provides sample code to perform a task using functions. The code takes inputs, performs operations like searching, sorting, counting etc. and provides the output. The questions cover various concepts in Python like functions, lists, tuples, strings, file handling etc.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 36

1

NAME : PIYUSH CHAUHAN

CLASS : 12-A

ROLL NO. : 14258528

SUBJECT : CS PRATICAL FILE

SESSION : 2022-2023

SUBMIT TED TO : MR. ARUN KUMAR

Q1. WAP to search an element in a list and display the frequency of element
present in list and

their location using Linear search by using user defined function.

PROGRAM:

def function():

l1 = list(map(str, input("Enter the elements: ").split()))

choice = int(input("\nChoose from the following:- \n\t1. Count the no.


of occurrence of element in given list

\n\t2. Find position of given element \nChoice: "))


if choice == 1:

dictionary = {}

b = dictionary.keys()

for word in l1:

if word in dictionary:

dictionary[word]+=1

else:

dictionary[word] = 1

print(dictionary)

elif choice == 2:

a = input("Enter the element : ")

for i in range(len(l1)):

if l1[i] == a:

print("Position of element = ", i+1)

function()

OUTPUT:

Enter the elements: today is wednesday.

Choose from the following:-

1. Count the no. of occurrence of element in given list

2. Find position of given element

Choice: 1

{'today': 1, 'is': 1, 'wednesday.': 1}

Q2. WAP to take input for 3 numbers, check and print the largest number using
function.

PROGRAM:
def maximum_value(b,c,d):

print(max(b,c,d))

maximum_value(6,7,8)

OUTPUT:

8
4

Q3.WAP to pass list to a function and double the odd values and half even
values

of a list and display list element after changing using function.

PROGRAM:

def change(A):

for i in range(len(A)):

if A[i]%2 == 0:

A[i] =
int(A[i]/2)

else:

A[i] = A[i]*2

Print()

change([1,6,8,5])

OUTPUT:

[2, 3, 4, 10]
5

Q4. WAP input n numbers in tuple and pass it to function to count

how many even and odd numbers are entered.

PROGRAM:

def count(P):

even = 0

odd = 0

for i in range(len(P)):

if P[i]%2 == 0:

even+=1

else:

odd +=1

print("No. of odd elements: ", odd, "\nNo. of even elements: ",


even)

count((2,4,5,7,10))

OUTPUT:

No. of odd elements: 2

No. of even elements: 3


6

Q5.Write a python program to take input for 2 numbers,


calculate and

print their sum, product and difference using function.

PROGRAM:

def algebra(B,C):

FA= int(input("Choose the operation: \n\t1. Sum \n\t2.


Product \n\t3. Difference\nChoice: "))

if FA== 1:

print("Sum = ",B+C)

elif FA== 2:

print("Product = ",B*c)

elif FA== 3:

print("Product = ",B-C)

algebra(7,4)

OUTPUT:

Choose the operation:

1. Sum

2. Product

3. Difference

Choice: 1

Sum = 11
7

Q6. WAP to pass a string to a function and count how many vowels

present in the string using function.

PROGRAM:

def count_vowels(str):

count = 0

for i in str:

if i in ['a','e','i','o','u','A','E','I','O','U']:

count+=1

print(count)

count_vowels('I live in INDIA and I love its TRADITIONS')


OUTPUT:

16

Q7. WAP to generator that generates random numbers between 1

and 6 using user defined function.

PROGRAM:

def generator():

import random

print("Randomly generated no.between 1-6 is:


",random.randint(1,6))

generator()

OUTPUT:

Randomly generated no.between 1-6 is: 5


9

Q8.WAP that counts the number of digits, uppercase letters,


lowercase letter, spaces

and other characters in the string entered.

PROGRAM:

def analytics(str):

D=int(input("Choose the operation: \n\t1. No. of digits \n\t2. No.


of uppercase characters \n\t3. No. of lowercase

characters \n\t4. No. of spaces \n\t5. No. of Special character \n\


t6. Calculate everything \nChoice: "))

if D== 1:

count = 0

for i in range(len(str)):

if str[i].isdigit():

count+=1

print("No. of digits: ", count)


elif D== 2:

count = 0

for i in range(len(str)):

if str[i].isupper():

count+=1

print("No. of uppercase letter: ", count)

elif D== 3:

count= 0

for i in range(len(str)):

if str[i].islower():

count+=1

print("No. of lowercase letter: ", count)

elif D== 4:

count= 0

for i in range(len(str)):

if str[i].isspace():

count+=1

print("No. of spaces: ", count)

elif D== 5:

count= 0

for i in range(len(str)):

if str[i].isalpha():

continue

elif str[i].isdigit():

10

continue

elif str[i].isspace():

continue

else:
count+=1

print("No. of special characters: ", count)

elif D== 6:

count_uc= 0

count_lc= 0

count_digit= 0

count_space= 0

count_sp= 0

for i in range(len(str)):

if str[i].isupper():

count_uc+=1

elif str[i].islower():

count_lc+=1

elif str[i].isdigit():

count_digi+=1

elif str[i].isspace():

count_space+=1

else:

count_sp+=1

print("No. of digits: ", count_digit)

print("No. of uppercase letters: ", count_uc)

print("No. of lowercase letters: ", count_lc)

print("No. of spaces: ", count_space)

print("No. of special characters: ", count_sp)

analytics("piyush@ $ MJK @1245/ OP/,. BOLte")

OUTPUT:

Choose the operation:

1. No. of digits
2. No. of uppercase characters

3. No. of lowercase characters

4. No. of spaces

5. No. of Special character

6. Calculate everything

Choice: 2

No. of uppercase letter: 8

11

Q9. WAP to accept a string (a sentence) and returns a string having


first

letter of each word in capital letter using function.

PROGRAM:

def function(str):

fo_str = ' '

M = str.split()

for i in range(len(M)):

M[i] = M[i].capitalize()

for i in M:

fo_str+=i

print(' '.join(M))

function('i am a good boy and i love to play cricket')

OUTPUT:

I Am A Good Boy And I Love To Play Cricket


12

Q10. Write a python program to read a file named “story.txt”, count


and print

total words starting with “a” or “A” in the file?

PROGRAM:

fw=open("story.txt",'w')

fw.write("I AM a big FAN of RONALDO


and i like FOOTBALL also")

fw.close()

fr=open("story.txt", 'r')

count= 0

str= ' '

while str!='':

str = fr.readline()

P= str.split()

for i in P:

if i[0] in ['a', 'A']:

count+=1

print(i)

print("Number of words starting with a


or A:",count)

OUTPUT:
AM

and

also

Number of words starting with a or A: 4

13

Q11. WAP to count no of words “this” and “ those” in a text

file using function.

PROGRAM:

fw=open("killer.txt",'w')

fw.write("this boy is good and those boys disturbs the


class ")

fw.close()

fr= open("killer.txt", 'r')

str= fr.read()

print("Occurance of this: ", str.count('this'))

print("Occurance of that: ", str.count('those'))

OUTPUT:

Occurance of this: 1

Occurance of that: 1
14

Q12. Write a python program to read a file named “story.txt”, count

and print total lines starting with vowels in the file?

PROGRAM:

fo= open("story.txt", 'r')

count= 0

str= fo.readlines()

for i in str:

if i[0] in ['a','e','i','o','u','A','E','I','O','U']:

print(i)

count+=1

print(count)

OUTPUT:

I AM a big FAN of RONALDO and i like FOOTBALL also

15

Q13. WAP to read characters from keyboard one by one, all lower case
letters
gets stored inside a file “LOWER”, all uppercase letters gets stored
inside a

file “UPPER” ,and all other characters get stored inside “OTHERS”.

PROGRAM:

A= open("upper.txt", 'w')

B= open("lower.txt", 'w')

C= open("other.txt", 'w')

while True:

K= input("Enter a character to write


or quit to terminate the program :")

if K=="quit" or K=="Quit":

break

elif K.isupper():

A.write(K + " ")

elif K.islower():

B.write(K + " ")

else:

C.write(K+ " ")

A.close()

B.close()

C.close()

print("I AM A Good Boy and I won 2 medals.")

OUTPUT:

Enter a character to write or quit to terminate the program :2

Enter a character to write or quit to terminate the program :6

Enter a character to write or quit to terminate the program :quit

I AM A Good Boy and I won 2 medals.


16

Q14. WAP to create a binary file with name and roll number. Search for
a given

roll number and display name, if not found display appropriate


message.

PROGRAM:

import pickle

student=[]

f=open("student.dat",'wb')

P='Y'

while P.lower()=='y':

roll=int(input("Enter Roll Number:"))

name=input("Enter Name:")

student.append([roll,name])

P=input("Add More?(Y):")

pickle.dump(student,f)

f.close()

fo=open("student.dat",'rb')

student=[]

while True:

try:

student=pickle.load(fo)

except EOFError:

break

p='Y'

while p.lower()=='y':

found=False

r=int(input("Enter Roll number to search:"))

for s in student:

if s[0]==r:
print("Name is:",s[1])

found=True

break

17

if not found:

print("sorry! Roll number not


found")

P=input("Search more?(Y):")

break

fo.close()

OUTPUT:

Enter Roll Number:1

Enter Name:KK

Add More?(Y):Y

Enter Roll Number:2

Enter Name:MM

Add More?(Y):N

Enter Roll number to search:1

Name is: KK

Search more?(Y):N

18

Q15. WAP to create a binary file with roll number, name and marks,
input

a roll number and update the marks.

PROGRAM:

import pickle

student=[]

fa=open("student.dat",'wb')

D='Y'

while D.lower()=='y':

roll=int(input("Enter Roll Number:"))

name=input("Enter Name:")

marks=int(input("Enter Marks:"))

student.append([roll,name,marks])

D=input("Add More?(Y):")

pickle.dump(student,fa)

fa.close()

fm=open("student.dat",'rb+')

student=[]

while True:

try:

student=pickle.load(fm)

except EOFError:

break

D='Y'

while D.lower()=='y':

found=False

o=int(input("Enter Roll number to update:"))

for s in student:

if s[0]==o:

print("Name is:",s[1])
print("current marks is:",s[2])

g=int(input("Enter New Marks:"))

s[2]=g

19

print("Record Upadated")

found=True

break

if not found:

print("sorry! Roll number not found")

D=input("Update more?(Y):")

break

fm.close()

OUTPUT:

Enter Roll Number:1

Enter Name:AA

Enter Marks:90

Add More?(Y):Y

Enter Roll Number:2

Enter Name:QQ

Enter Marks:99

Add More?(Y):N

Enter Roll number to update:2

Name is: QQ

current marks is: 99

Enter New Marks:95

Record Upadated

Update more?(Y):N
20

Q16.WAP to create a CSV file with empid, name and mobile


no. and search

empid, update the record and display the records.

PROGRAM:

import csv

def write():

f=open("file.csv",'w',newline='')

wo=csv.writer(f)

wo.writerow(['empid','name','mobileno.'])

while true:

eid=int(input("enter empid:"))

name=input("enter name of emp:")

mobno=int(input("enter mobileno.:"))

data=[eid,name,mobno]

wo.writerow(data)

ch=input("do you want to add more records(y/n)")

if ch in 'Nn':

break

f.close()

def read():

f=open("file.csv",'r')
ro=csv.reder(fr)

for i in ro:

print(i)

def search():

f=open("file.csv",'r',newline='')

eid=input("enter empid to search")

found=0

for rec in r:

if rec[0]==eid:

print(".....Record found......")

print(rec)

found=1

break

if found==0:

print(".......Record not
found......")

f.close()

def update():

f=open("file.csv",'r',newline='')

eid=input("enter empid to search")

21

found=0

r=csv.reader(f)

nrec=[]

for rec in r:

if rec[0]==eid:

print("....current record....")

rec[1]=input("enter name to update")

print(".....updated record.....",rec)

found=1
nrec.append(rec)

if found==0:

print("....record not found....")

f.close()

else:

f=open('file.csv','w',newline=='')

w=csv.writer(f)

w.writerows(nrec)

f.close()

write()

read()

search()

update()

OUTPUT:

enter empid:AABB@SDV

enter name of emp:KK

enter mobileno.:9911754784

do you want to add more records(y/n)y

enter empid:BBAA@SDV

enter name of emp:MM

enter mobileno.:9814754581

do you want to add more records(y/n)n

['empid','name','mobileno.']

[' AABB@SDV ',' KK ', '9911754784']

[' BBAA@SDV ',' MM ', '9814754581']

enter empid to searchMMBB@SDV

....record not found....

enter empid to searchBBAA@SDV

....current record....
enter name to updateDD

.....updated record..... [' BBAA@SDV


','DD ', '9814754581']

22

Q17. Python program to implement all basic operations of a stack, such as


adding element (PUSH

operation), removing element (POP operation) and displaying the stack elements
(Traversal operation)

using lists.

PROGRAM:

s = []

top = None

def s_push(stk):

while True:

item = int(input("\nEnter the element:


"))

stk.append(item)

top = len(stk)-1

redo = input("Do you want to add more


elements: ")

if redo in 'nN':

break

def s_pop(stk):

if len(stk) == 0:

print("Underflow")

else:

i = stk.pop()

if len(stk) == 0:

top = None

else:

top = len(stk)
top = top-1

print(i)

def display(stk):

if len(stk) == 0:

print('Stack is empty')

else:

top = len(stk) - 1

print(stk[top], '#Top Element')

for i in range(top-1, -1, -1):

print(stk[i])

while True:

choices = int(input("\n\t1. Push \n\t2. Pop \n\t3.


Display the stack \n\t4. Exit \nChoice: "))

if choices == 1:

s_push(s)

elif choices == 2:

23

s_pop(s)

elif choices == 3:

display(s)

elif choices == 4:

input("Thanks for using!!")

break

else:

print("Invalid Input!!")

OUTPUT:

1. Push
2. Pop

3. Display the stack

4. Exit

Choice: 1

Enter the element: 2

Do you want to add more elements: N

1. Push

2. Pop

3. Display the stack

4. Exit

Choice: 3

2 #Top Element

1. Push

2. Pop

3. Display the stack

4. Exit

Choice: 4

Thanks for using!!

24

Q18. Write a python program to maintain book details


like book code, book

title and price using stacks data structures.

PROGRAM:

data = []
top = None

def s_push(stk):

while True:

bookcode = int(input("\nEnter the book code:


"))

booktitle = input("Enter the book title: ")

price = int(input("Enter the price of book: "))

stk.append([bookcode, booktitle,price])

top = len(stk)-1

redo = input("Do you want to add more books: ")

if redo in 'nN':

break

def display(stk):

if len(stk) == 0:

print('Stack is empty')

else:

top = len(stk) - 1

print(stk[top])

for i in range(top-1, -1, -1):

print(stk[i])

def search(stk):

code = int(input("Enter the book code: "))

for i in range(len(stk)):

if stk[i][0] == code:

print("Details of asked book = \n", stk[i])

def update(stk):
code = int(input("Enter the book code: "))

a = int(input("Which portion you want to update: \n\t1.


Book Code \n\t2. Book Name \n\t3. Price \nChoice: "))

if a == 1:

code_new = int(input("Enter the new code: "))

for i in range(len(stk)):

25

if stk[i][0] == code:

stk[i][0] = code_new

print("Code Updated!!")

elif a == 2:

name_new = input("Enter the new name: ")

for i in range(len(stk)):

if stk[i][0] == code:

stk[i][1] = name_new

print("Name Updated!!")

elif a == 3:

price_new = int(input("Enter the new price: "))

for i in range(len(stk)):

if stk[i][0] == code:

stk[i][2] = price_new

print("Price Updated!!")

while True:

choices = int(input("\n\t\t\t***Welcome to Library


Management System*** \n\t1. Add books to library \n\t2. Search

\n\t3. Update data \n\t4. View the library \n\t5. Exit\nChoice: "))

if choices == 1:

s_push(data)

elif choices == 2:

search(data)
elif choices == 3:

update(data)

elif choices == 4:

display(data)

elif choices == 5:

input("Thanks for using!!")

break

else:

print("Invalid Input!!")

OUTPUT:

***Welcome to Library Management


System***

1. Add books to library

2. Search

3. Update data

4. View the library

5. Exit

26

Choice: 1

Enter the book code: 1100

Enter the book title: MBA

Enter the price of book: 40

Do you want to add more books: Y

Enter the book code: 1101

Enter the book title: LLB

Enter the price of book: 120

Do you want to add more books: N


***Welcome to Library Management System***

1. Add books to library

2. Search

3. Update data

4. View the library

5. Exit

Choice: 2

Enter the book code: 1100

Details of asked book =

[1100, 'MBA', 40]

***Welcome to Library Management System***

1. Add books to library

2. Search

3. Update data

4. View the library

5. Exit

Choice: 5

Thanks for using!!

27

Q19. Write a python code to create table emp using python-mysql


connectivity.Create

database and table as below:

Name of database =school

Name of table = emp (empno,ename,salary)

PROGRAM:
import mysql.connector

mydb=mysql.connector.connect(host="localhost",user="root",passwd="web

@1234",database="school")

mycursor=mydb.cursor()

mycursor.execute(""create table emp(empno int(5),ename


char(6),salary

int(8));"")

for x in mycursor:

print(x)

OUTPUT:

('food',)

('information_schema',)

('mysql',)

('order1',)

('performance_schema',)

('piyush14',)

('sakila',)

('school',)

('sys',)

28

('world',)

Q20. Write a python code to insert data into table emp using python-mysql

connectivity

Create database and table as below:

Name of database =school

Name of table = emp (empno,ename,salary)

PROGRAM:

import mysql.connector

mycon = mysql.connector.connect(host = 'localhost',


user = 'root' , password =

'web@1234', database = "school")

cur = mycon.cursor()

while True:

empno = int(input("Enter the empno: "))

ename = input("Enter the ename: ")

salary = int(input("Enter the salary: "))

sql = 'Insert into emp (empno, ename,


salary) Values (%s, %s, %s)'

vals = (empno, ename,salary)

cur.execute(sql, vals)

mycon.commit()

print('Data added!!')

c = input("\nDo you want to add more data:


")

if c in 'nN':

break

OUTPUT:

Enter the empno: 1101

Enter the ename: CC

Enter the salary: 70000

29

Data added!!

Do you want to add more data: Y

Enter the empno: 1102

Enter the ename: DD

Enter the salary: 80000

Data added!!

Do you want to add more data: N


30

Q21. Write a code to fetch record from table emp using python-mysql

connectivity.

Create database and table as below:

Name of database =school

Name of table = emp (empno,ename,salary)

PROGRAM:

import mysql.connector

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

= 'root', password = 'web@1234', database = 'school')

cur = mycon.cursor()

r1 = 'select * from emp'

cur.execute(r1)

d = cur.fetchall()
for k in d:

print(k)

OUTPUT:

(1101, 'CC', 70000)

(1102, 'DD', 80000)

31

Q22. Write the SQL query commands based on following table .

Write SQL query for (a) to (e)

(a) To show book name, Author name and price of books of First Pub. Publisher .

= select Book_id,Author_name,price from book where publisher='first publi';

(b) To list the names from books of text type .

= select Book_name from book where type='text';

(c) To Display the names and price from books in ascending order of their prices.

= select Book_name,price from book order by price;

(d) To increase the price of all books of EPB publishers by 50.


= update book set price=price+50 where publisher='EPB';

(e) To display the Book_Id, Book_name and quantity issued for all books which have
been issued.

= Select a.book_id ,a.book_name ,b.quantity_issued from books a, issued b where


a.book_id=b.book_id;

32

Q23. Write the SQL query commands based on following table .

Write the SQL commands for the following :


(i) To show firstname, lastname, address and city of all employees
living in paris.

= select Firstname,lastname,Address,city from Employees where city='paris';

(ii) To display the content of Employees table in descending order of


Firstname.

= select*from Employees Order by Firstname DESC;

(iii) To display the firstname,lastname and total salary of all managers


from the tables Employee
and empsalary , where total salary is calculated as
salary+benefits.

= select Firstname,Lastname,(salary+benefits)'Total salary' From Employees


natural join
Emp salary;

(iv) To display the maximum salary among managers and clerks from the
table Empsalary.

= select Max(Salary) from Empsalary where designation IN('Manager','clerk');

You might also like