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

Class 12 Practical Programs

The document contains 12 Python programs for performing various tasks like arithmetic calculations, checking if a number is prime or Armstrong, generating Fibonacci series, counting words in a string, reading and processing a text file, generating random passwords, creating and manipulating binary and CSV files to store and retrieve student records. The last program calculates consolidated exam results from a CSV file containing student marks.
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)
20 views

Class 12 Practical Programs

The document contains 12 Python programs for performing various tasks like arithmetic calculations, checking if a number is prime or Armstrong, generating Fibonacci series, counting words in a string, reading and processing a text file, generating random passwords, creating and manipulating binary and CSV files to store and retrieve student records. The last program calculates consolidated exam results from a CSV file containing student marks.
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/ 10

#1.

Program for Arithmetic Calculation

val1 = float(input("Enter the first value:"))


val2 = float(input("Enter the second value:"))
op = input("Enter any one of the operator (+, -, *, /, //, %, **): ")
if op == '+':
result = val1 + val2
elif op == '-':
result = val1 - val2
elif op == '*':
result = val1 * val2
elif op == '/':
result = val1 / val2
elif op == '//':
result = val1 // val2
elif op == '%':
result = val1 % val2
elif op == '**':
result = val1 ** val2
else:
print("Invalid Operator")

print("The result is:", result)

#2. check if the entered number is an Armstrong or not

n = int(input("Enter a number:"))
temp = n
s=0

while n > 0:
r = n%10
n = n//10
s = s + r**3

if temp == s:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
#3. Check if the given number is Prime or Composite

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

if n == 0 or n ==1:
print("Neither Prime not Composite")
elif n == 2:
print("Prime")
elif n%2 == 1:
for i in range(3, n//2+1, 2):
if n%i == 0:
print("Composite")
break
else:
print("Prime")

#4. Fibonacci Series

def fibonacci(n):
a=0
b=1

if n == 1:
print(a)
else:
print(a)
print(b)
for i in range(n-2):
c=a+b
print(c)
a=b
b=c

n = int(input("Enter no of terms upto which Fibonacci series is to be


printed:"))

if n <= 0:
print("Incorrect input")
else:
print("The Fibonacci series is:")
fibonacci(n)
#5. count a word from a string

def countword(str1, word):


s = str1.split()
count = 0

for w in s:
if w.lower() == word:
count +=1
return count

str1 = input("Enter any line of text:")

word = input("Enter the word to be counted:")

c = countword(str1, word)

if c == 0:
print("Sorry, the word '", word, "' is not present in the given string")
else:
print("The word '", word, "' has appeared", c, "times in the given string")

#6. print words separated by #

f = open("sample.txt", 'r')

for line in f:
words = line.split()
for w in words:
print(w, end = '#')

print()

f.close()
#7. Program to read a text file and display no of vowels, consonants,

f = open("Sample.txt", 'r')

vowels = 0
consonants = 0
upper = 0
lower = 0

content = f.read()

for ch in content:
if ch.isalpha():
if ch in "AEIOUaeiou":
vowels += 1
else:
consonants += 1

if ch.isupper():
upper += 1
else:
lower += 1

print("No of vowels:", vowels)


print("No of consonants:", consonants)
print("No of upper case letters:", upper)
print("No of lower case letters:", lower)

f.close()

#8. remove the lines containing the character ‘a’ from the file

f = open("sampleold.txt", 'r')
content = f.readlines()
f.close()

f1 = open("sampleold.txt", 'w')
f2 = open("samplenew.txt", 'w')

for line in content:


if 'a' in line:
f2.write(line)
else:
f1.write(line)

f1.close()
f2.close()
#9. random password generator

import random

#generating a 4 digit number


number = str(random.randint(1000,9999))

#generating 2 alphabetic upper case character


ucase = ''
ucase += chr(random.randint(65,90))
ucase += chr(random.randint(65,90))

#generating 2 alphabetic lower case character


lcase = ''
lcase += chr(random.randint(97,122))
lcase += chr(random.randint(97,122))

#generating 2 special charater

spch = ''
for i in range(2):
index = random.randrange(len(special))
spch += special[index]

password = ucase + lcase + spch + number

print(password)
#10 create a binary file for student data and then perform search

import pickle

def write():
f = open("Student.dat", 'wb')

n = int(input("Enter no of students:"))

for i in range(n):
st_id = int(input("Enter Student ID:"))
st_name = input("Enter Student Name:"))
l = [st_id, st_name]

pickle.dump(l,f)

f.close()

def search():
f = open("Student.dat", 'rb')
st_id = int(input("Enter the student id to be searched:"))
try:
while True:
data = pickle.load(f)
if data[0] == st_id:
print("Name:", data[1])
break

except EOFError:
print("Record with the entered student ID not found")

f.close()

write()
search()
#11 program to update student data in a binary file and display it

import pickle

def update():
import os
f1 = open("Student.dat", 'rb')
f2 = open("temp.dat", 'wb')
st_id = int(input("Enter the student id whose mark is to updated:"))
name = input("Enter new Name:")
found = False
try:
while True:
data = pickle.load(f1)
if data[0] == st_id:
data[1] = name
found = True
pickle.dump(data,f2)

except EOFError:
if found == True:
print("Record Updated Successfully")
else:
print("Record with entered Student ID not found")

f1.close()
f2.close()
os.remove("Student.dat")
os.rename('temp.dat','Student.dat')

def display():
f = open("Student.dat", 'rb')

try:
while True:
data = pickle.load(f)
print(data)
except EOFError:
print("End of File.")

f.close()

display()
update()
display()
#12 program to delete student data from a binary file and display it

import pickle

def delete():
import os
f1 = open("Student.dat", 'rb')
f2 = open("temp.dat", 'wb')
st_id = int(input("Enter the student id whose record is to be deleted:"))
found = False

try:
while True:
data = pickle.load(f1)
if data[0] != st_id:
pickle.dump(data,f2)
else:
found = True
except EOFError:
if found == True:
print("Record Deleted Successfully")
else:
print("Record with entered Student ID not found")

f1.close()
f2.close()
os.remove("Student.dat")
os.rename('temp.dat','Student.dat')

def display():
f = open("Student.dat", 'rb')

try:
while True:
data = pickle.load(f)
print(data)
except EOFError:
print("End of File.")

f.close()

display()
delete()
display()
#13 create a csv file to store user_id and password

import csv

def write():
f = open("details.csv", 'w', newline = '')
writer = csv.writer(f)

while True:
u_id = input("Enter User_ID:")
pssd = input("Enter Password:")
data = [u_id, pssd]
writer.writerow(data)

ch = input("Do you want to insert another record (Y/N):")

if ch in "Nn":
break
f.close()

def read():
f = open("details.csv", 'r')
reader = csv.reader(f)

for rec in reader:


print(rec)

f.close()

def search():
f = open("details.csv", 'r')
reader = csv.reader(f)

user_id = input("Enter the user_id to be searched:")

for rec in reader:


if rec[0] == user_id:
print("User_id:", rec[0])
print("Password:", rec[1])
break
else:
print("No record found with the given User_id")
f.close()

write()
read()
search()
14: To create consolidated result from Student Exam Marks stored in a CSV file

import csv
import math

f = open('Student.csv', 'r')

total_mark = 0
strength = 0
centum = 0
distinction = 0
first = 0
second = 0
ra = 0

reader = csv.reader(f)
next(reader)
for rec in reader:
mark = int(rec[2])
total_mark += mark
strength += 1
if mark == 100:
centum += 1
elif mark >= 80:
distinction += 1
elif mark >= 60:
first += 1
elif mark >= 40:
second += 1
else:
ra += 1

f.close()

print("------Class Result------")
print("Class Average:", math.ceil(total_mark/strength – 0.50))
print("No of Centums:", centum)
print("No of Distinction:", distinction)
print("No of First Class:", first)
print("No of Second Class:", second)
print("No of Re-appear:", ra)
print("------------------------")

You might also like