12 Cs Practical File
12 Cs Practical File
Output -
Enter a number: 6556
Number is palindrome
Practical No-2
# Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a character of a
value\n"))
if choice==1:
ch=input("Enter a character:")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: ")) print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False
Output
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
1
Enter a character : a
97
Do you want to continue? Y/N Y
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
2
Enter an integer value: 65
A
Do you want to continue? Y/N
N
Practical 3
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter choice(1/2/3/4): ")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
next_calculation = input("Let's do next calculation? (yes/no): ")
if next_calculation == "no":
break
else:
print("Invalid Input")
Output -
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no
Practical No-4
# Example of Global and Local variables in function
x = "global "
def display():
global x
y = "local"
x=x*2
print(x)
print(y)
display()
Output -
global global local
Practical No-5
# Python program to count the number of vowels, consonants, digits and special characters in a string
str = input(“Enter the string : “)
vowels = 0
digits = 0
consonants = 0
spaces = 0
symbols = 0
str = str.lower()
for i in range(0, len(str)):
if(str[i] == ‘a’or str[i] == ‘e’ or str[i] == ‘i’ or str[i] == ‘o’ or str[i] == ‘u’):
vowels = vowels + 1
elif((str[i] >= ‘a’and str[i] <= ‘z’)):
consonants = consonants + 1
elif( str[i] >= ‘0’ and str[i] <= ‘9’):
digits = digits + 1
elif (str[i] ==’ ‘):
spaces =spaces + 1
else:
symbols = symbols + 1
print(“Vowels: “, vowels);
print(“Consonants: “, consonants);
print(“Digits: “, digits);
print(“White spaces: “, spaces);
print(“Symbols : “, symbols);
Output -
Enter the string : 123 hello world $%&45
Volwels: 3
Consontants: 7
Digits: 5
White spaces: 3
Symbols: 3
Practical No-6
# Python Program to add marks and calculate the grade of a student
total=int(input("Enter the maximum mark of a subject: "))
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
average=(sub1+sub2+sub3+sub4+sub5)/5
print("Average is ",average)
percentage=(average/total)*100
print("According to the percentage, ")
if percentage >= 90:
print("Grade: A")
elif percentage >= 80 and percentage < 90:
print("Grade: B")
elif percentage >= 70 and percentage < 80:
print("Grade: C")
elif percentage >= 60 and percentage < 70:
print("Grade: D")
else:
print("Grade: E")
Output -
Enter the maximum mark of a subject: 10
Enter marks of the first subject: 8
Enter marks of the second subject: 7
Enter marks of the third subject: 9
Enter marks of the fourth subject: 6
Enter marks of the fifth subject: 8
Average is 7.6
According to the percentage, Grade: C
Practical No-7
# Generating a List of numbers Using For Loop
import random
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
Output -
[10, 5, 21, 1, 17]
Practical No-8
# Write a program to read a text file line by line and display each word separated by '#'.
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
OR
fin=open("D:\\python programs\\Book.txt",'r')
L1=fin.readlines( )
s=' '
for i in range(len(L1)):
L=L1[i].split( )
for j in L:
s=s+j
s=s+'#'
print(s)
fin.close()
Output –
Text in file:
hello how are you?
python is case-sensitive language.
Output in python shell:
hello#how#are#you?#python#is#case-sensitive#language.#
Practical No-9
# Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters and
other than character and digit in the file.
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit) print("Vowels:",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
Practical No-9
# Remove all the lines that contain the character `a' in a file and write it to another file
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w") for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
Practical No-10
# Write a Python code to find the size of the file in bytes, the number of lines, number of words and
no. of character.
import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
filesize = os.path.getsize("Mydoc.txt")
for letter in line:
if letter != ' ' and pos == 'out': words += 1
pos = 'in'
elif letter == ' ': pos =
'out'
print("Size of File is",filesize,'bytes')
print("Lines:", lines) print("Words:", words)
print("Letters:", letter)
Practical No-11
# Create a binary file with the 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'])
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()
Practical No-12
# Create a binary file with roll number, name and marks. Input a roll number and update details.
Create a binary file with roll number, name and marks.
Input a roll number and update details.
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:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile: for j in
newRecord:
pickle.dump(j,Myfile) 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()
Practical No-13
# Write a program to perform read and write operation onto a student.csv file having fields as roll
number, name, stream and percentage.
import csv
with open('Student_Details.csv','w',newline='') as csvf: writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y': rl=int(input("Enter Roll
No.: ")) n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n)..............................")
def circle(r):
area= math.pi*r*r return
area
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])
#Driver Code