Practical_File_XII_CS
Practical_File_XII_CS
Output:
2. Write a program to input a character and to print whether a
given character is an alphabet, digit or any other character.
Python Code:
ch=input("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")
Output:
3. Write a program to read a list of n integers (positive as well as
negative). Create two new lists, one having all positive numbers
and the other having all negative numbers from the given list.
Print all three lists.
Python Code:
L = list()
n=int(input('Enter number of elements to be appended in the
list:'))
for i in range(0,n):
ele = int(input('Elemnet: '))
L.append(ele)
pos_L=[]
neg_L=[]
for i in L:
1/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
if i>=0:
pos_L.append(i)
else:
neg_L.append(i)
print('List with positive numbers:\n',pos_L)
print('List with negative numbers:\n',neg_L)
Output:
4. Write a function INDEX_LIST(L), where L is the list of elements
passed as argument to the function. The function returns
another list named ‘indexList’ that stores the indices of all Non-
Zero Elements of L.
For example: If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
Python Code:
def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList
L= [12,4,0,11,0,56]
L1 = INDEX_LIST(L)
print('Returned list... \n',L1)
Output:
5. Write a function that takes a sentence as an input parameter
where each word in the sentence is separated by a space. The
function should replace each blank with a hyphen and then
return the modified sentence.
Python Code:
def textReplace(text):
new_str = text.replace(' ', '-')
return new_str
print('Text replacement...')
text=input('Enter a sentence: ')
new_Text= textReplace(text)
print('Modified string after text replacement...')
print(new_Text)
Output:
6. Write a program to check whether a number is palindrome or
not using function.
Python Code:
#Program to chek whether a number is pallindrome or not.
def isPallindrome(num):
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
return res
Output:
7. Write a function StuDetails( ) in python which accept a list of
marks of students and return the minimum mark, maximum
mark and the average marks.
Python Code:
def StuDetails(lst):
min_marks = min(lst)
max_marks = max(lst)
avg_marks = sum(lst)/len(lst)
return min_marks, max_marks, avg_marks
m_lst = []
print('Enter marks of 05 subject:')
for i in range(0, 5):
ele = int(input())
m_lst.append(ele)
min_marks, max_marks, avg_marks = StuDetails(m_lst)
print('Minimum marks: ',min_marks)
print('Maximum marks: ',max_marks)
print('Average marks: ',avg_marks)
Output:
8. Create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have
marks above 75.
Python Code:
n = int(input('Enter no. of records to be stored in the dictionary:
'))
d1 = {}
rec = 0
while n>0:
rec += 1
print('Record number',rec)
name = input('Enter student name: ')
marks = int(input('Enter student marks: '))
d1[name]=marks
n-=1
Output:
9. Write a function countNow(PLACES) in Python, that takes the
dictionary, PLACES as an argument and displays the count of
the names of the places whose names are longer than 5
characters.
For example, Consider the following dictionary
3/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
PLACES={1:"Delhi",2:"London",3:"Paris",4:"Doha"}
The output should be:
Count of the places whose names are longer than 5 characters:
1
Python Code:
def countNOW(PLACES):
count = 0
for k,v in PLACES.items():
if len(v)>5:
count+=1
return count
PLACES={1:"Delhi",2:"London",3:"Paris",4:"Doha"}
count = countNOW(PLACES)
print("Count of the places whose names are longer than 5
characters:", count)
Output:
10. Write a Python program to create a text file and write your
name, class, roll, Father’s name, mother’s name and address in
it. (Using functions)
Python Code:
Output:
11. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file. (Using functions)
Python Code:
Output:
12. Write a program to write those lines which have the character
'p' from one text file to another text file. (Using functions)
fin=open("Book.txt","r")
fout=open("Story.txt","a")
s=fin.readlines()
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
print('Data Copied from Book.txt to Story.txt')
13. Write a program to accept a filename from the user and display
all the lines from the file which contain python comment
character '#'. (Using functions)
Python Code:
Output:
14. Write a function in Python that counts the number of “Me” or
Output:
15. Write a program to write, read and display employee records in
a binary file. (Using functions)
Python Code:
# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
def writeRecords():
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
writeRecords()
print("Now reading the employee records from the file")
5/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
print()
readRecords()
Output:
16. Write a Python program to create a binary file with roll number,
name and marks. Input a roll number and update the marks.
(Using functions)
Python Code:
import pickle
def bfileCreate():
#Creating the dictionary
sd = {}
fout=open(r'Student16.dat','ab')
choice= input('Do you want to enter student details- Y/N?')
while choice in 'Yy' :
rollno = int(input('Enter roll number: '))
name = input('Enter Name: ')
marks = int(input('Enter Marks: '))
sd['Rollno'] = rollno
sd['Name']=name
sd['Marks']=marks
pickle.dump(sd,fout)
choice = input("Want to enter more data- Y / N: ")
if choice.upper() != 'Y':
break
fout.close()
def bfileDisplay():
fin= open(r'Student16.dat','rb')
try :
print('Students details............ ')
while True:
sd = pickle.load(fin)
print(sd)
except EOFError:
pass
fin.close()
bfileCreate()
bfileDisplay()
print('Update student marks.......')
roll = int(input('Enter student roll number: '))
nw_marks = int(input('Enter marks for updation: '))
updateMarks(roll, nw_marks)
Output:
17. 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. (Using functions)
Python Code:
import pickle
def bfileCreate():
sd = {}
fout=open(r'Student17.dat','ab')
choice= input('Do you want to enter student details- Y/N?')
while choice in 'Yy' :
rollno = int(input('Enter roll number: '))
name = input('Enter Name: ')
sd['Rollno'] = rollno
sd['Name']=name
pickle.dump(sd,fout)
choice = input("Want to enter more data- Y / N: ")
if choice.upper() != 'Y':
break
fout.close()
def searchRoll(roll):
fin= open(r'Student17.dat','rb')
try :
ch = 0
while True:
sd = pickle.load(fin)
if sd['Rollno']==roll:
ch=1
print('Student details: \n',sd)
except EOFError:
if ch !=1:
print('Student roll number not found!')
fin.close()
bfileCreate()
print('Search Student Record....')
roll = int(input('Enter student roll number: '))
searchRoll(roll)
Output:
18. Write a program to perform read and write operation with a csv
file. (Using functions)
Python Code:
import csv
def readcsv():
7/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
with open('data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a
reader object
for row in data:
print(row)
def writecsv( ):
with open('data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"')
#write new record in file
while True:
roll = input('Enter student roll: ')
name = input('Enter student name: ')
cls = input('Enter student class: ')
stream = input('Enter student stream: ')
writer.writerow([roll, name, cls, stream])
ans=input("Do you wish to enter more records (y/n)? ")
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
print('Records in CSV file.....\n')
readcsv()
Output:
19. Create a CSV file by entering user-id and password, read and
search the password for given userid. (Using functions)
Python Code:
Output:
20. Write a menu based program to perform the operation on stack
in python using lists. (Using functions)
Python Code:
s=[]
def PUSH(a):
s.append(a)
def POP():
if (s==[]):
print( "Stack is empty.")
else:
print( "Deleted element is :", s.pop())
def DISP():
l=len(s)
8/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
# To display elements from last element to first
if l!=0:
for i in range(l-1,-1,-1):
print(s[i])
else:
print('Stack is empty.')
ch="y"
while True:
print('Stack operations.....')
print( "1. PUSH" )
print( "2. POP" )
print( "3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Push operation - Enter any number :")
PUSH(a)
elif (choice==2):
POP()
elif (choice==3):
DISP()
ch=input("Do you want to continue (y/n)?, N to exit ")
if ch in 'nN':
break
Output:
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in R:
if R[k]>=75:
9/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
Output:
TOM ANU BOB OM
22. Alam 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 even numbers
into a stack.
● Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N= [12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
Sample Output of the code should be:
38 22 98 56 34 12
Python 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:
el = POP(ST)
if el!= None:
print(el, end =' ')
Output:
38 22 98 56 34 12
23. Basic SQL Queries to Create Table
A. Write SQL query to create a database Organization
Quer CREATE DATABASE ORGANIZATION;
y
B. Write SQL query to show the lists of all databases.
Quer SHOW DATABASES;
y
C Write SQL query to select the Organization database.
Quer USE ORGANIZATION;
y
D Write SQL query to create Employee table with following
structure:
10/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
ECODE INT PRIMARY KEY
ENAME VARCHAR(30) NOT NULL
DEPT VARCHAR(25)
SALARY INT
CITY VARCHAR(25)
Table: Department
12/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
DEPTID DEPTNAME FLOORNO
D001 Personal 4 4
D002 Admin 10 10
D003 Production 1
D004 Sales 3 3
Output:
Output:
Output:
Output:
Output:
Output: