Class 12_CS_Practicals_Python Programming

You might also like

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

TABLE OF CONTENTS

Sr No Assignment Page No Submission Teacher’s


Date Sign
Python Programming
1 Write a program to print volume of a sphere. 5/4/2024

2 Write a program to calculate and display the 5/4/2024


area of a triangle having three sides a, b and
c using Heron's Formula.
3 Write a program to calculate and print roots 5/4/2024
of a quadratic equation
4 Write a program to find greatest number 12/4/2024
among three numbers.

5 Write a program to check whether the given 12/4/2024


year is leap year or not.
6 Write a program to print odd numbers from 12/4/2024
1 to 100.
7 Write a program to print factorial of a 19/4/2024
number.
8 Write a program to print prime no. from 1 – 19/4/2024
100.
9 Write a program to check whether the given 19/4/2024
string is palindrome or not.

10 Write a program to count number of 26/4/2024


uppercase letters, lowercase letters and
digits separately from a string.
11 Write a program to create a list of five 26/4/2024
numbers and calculate and print the total
and average of the list of numbers.
12 Write a Python program to count the 26/4/2024
number of characters (character frequency)
in a string by Using Dictionary.
13 Define a function to calculate and print area 26/4/2024
of a rectangle.
14 Write a program to calculate Simple Interest 3/5/2024
to show all three types of
Arguments/Parameters.
15 Define a function named prime() to check 3/5/2024
whether the number is prime or not.
16 Define a function named sort() to sort a list 3/5/2024
of number using Bubble Sort.
17 Define a function named convert() to 3/5/2024
Convert Decimal to Binary, Octal and
Hexadecimal no.
18 Define a function named text_write() in 10/5/2024
python write the records for 5 students in a
file named as Student.txt and each record
must contain roll_no, name, Marks.
19 Define a function named text_read() in 10/5/2024
python read records from Student.txt and
print only those student’s records who
scored above 450.
20 Define a function named count_a() in python 17/5/2024
to count the number of lines in a text file
‘STORY.TXT’ which is starting with an
alphabet ‘A’.
21 Define a function named charac() to read a 17/5/2024
text file and display the number of
vowels/consonants/ uppercase/ lowercase
characters from the file separately.
22 Define a function named Count() that will 17/5/2024
read the contents of text file named
“Report.txt” and count the number of lines
which starts with either “I” or “M”.
23 Define a function named ISTOUPCOUNT() in 24/5/2024
python to read contents from a text file
WRITER.TXT, to count and display the
occurrence of the word ‘‘is’’ or ‘‘to’’ or ‘‘up’’
24 Define a function named bin_write() in 24/5/2024
python write the records for 10 students in a
file named as Student.bin and each record
must contain roll no., name, marks.
25 Define a function named bin_read() in 24/5/2024
python read records from Student.bin and
print only those student’s records who’s
marks are more than 450.
26 Define A function search_bin() to search for a 21/6/2024
given roll number and display the records, if
not found display appropriate message.
27 Define a function named bin_update() in 21/6/2024
python to read records from Student.bin and
update the marks of given roll no.
28 Define a function named csv_write() in 28/6/2024
python write the records for 6 Employees in
a file named as Employee.csv and each
record must contain Emp_no, Emp_name,
Salary.
29 Define a function named csv_read() in 28/6/2024
python read records from Employee.csv and
print only those employee’s records who’s
salary is more than 20000.
30 Write a Python program to implement a 5/7/2024
stack using a list data-structure.
Practical No-1

# Write a program to print volume of a sphere.

Source Code

pi = 3.14
r = float(input('Enter the radius of the sphere : '))
V = 4.0/3.0 * pi * r**3
print('The volume of the sphere is: ', V)

Output
Practical No-2

# Write a program to calculate and display the area of a triangle having


three sides a, b and c using Heron's Formula.

Source Code

a = float(input('Enter first side: '))


b = float(input('Enter second side: '))
c = float(input('Enter third side: '))
s = (a + b + c) / 2
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)

Output
Practical No-3
# Write a program to calculate and print roots of a quadratic equation

Source Code

import cmath
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print('The solution are {0} and {1}'.format(sol1,sol2))

Output
Practical No-4

# Write a program to find greatest number among three numbers.

Source Code

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output
Practical No-5

#Write a program to check whether the given year is leap year or not.

Source Code

year = int(input('Enter the year :'))

if (year % 400 == 0) and (year % 100 == 0):


print("{0} is a leap year".format(year))
elif (year % 4 ==0) and (year % 100 != 0):
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))

Output
Practical No-6

# Write a program to print odd numbers from 1 to 100.

Source Code

for num in range(1, 101):


if num % 2 != 0:
print(num, end = " ")

Output
Practical No-7

# Write a program to print factorial of a number.


Source Code

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


factorial = 1
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
Practical No-8

# Write a program to print prime no. from 1 – 100


Source Code

lower = 1
upper = 100
print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):


if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Output
Practical No-9

# Write a program to check whether the given string is


palindrome or not.

Source Code

my_str = input('Enter the string : ')


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

Output
Practical No-10

# Write a program to count number of uppercase letters,


lowercase letters and digits separately from a string.

Source Code

str=input('Enter the string : ')


lower=0
upper=0
digit=0
for i in str:
if(i.islower()):
lower+=1
elif(i.isupper()):
upper+=1
elif(i.isdigit()):
digit+=1
print("The number of lowercase characters is:",lower)
print("The number of uppercase characters is:",upper)
print("The number of digit is:",digit)

Output
Practical No-11

# Write a program to create a list of five numbers and


calculate and print the total and average of the list of
numbers.

Source Code

L = eval(input('Enter the list : '))


count = 0
for i in L:
count += i
avg = count/len(L)
print("sum = ", count)
print("average = ", avg)

Output
Practical No-12

# Write a Python program to count the number of characters


(character frequency) in a string by Using Dictionary.
Source Code

test_str = input('Enter the string : ')


res = {}

for keys in test_str:


res[keys] = res.get(keys, 0) + 1

print("Count of all characters in the string is : \n" + str(res))


Output
Practical No-13

# Define a function to calculate and print area of a rectangle.


Source Code

def calarea(l,b):
return l*b

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


breadth = int(input("Enter the breadth : "))
area = calarea(length,breadth)
print('Area of the rectangle is : ',area)

Output
Practical No-14

# Write a program to calculate Simple Interest to show all


three types of Arguments/Parameters.

Source Code with Positional argument

def simple_interest(p,r,t):
si = (p * r * t)/100
return si

p = int(input('Enter principal : '))


r = int(input('Enter rate of interest : ') )
t = int(input('Enter time period is :'))
si = simple_interest(p,r,t)
print('The Simple Interest is', si)
Output

Source Code with Default Parameter

def simple_interest(p=8,r=6,t=5):
si = (p * r * t)/100
return si

si = simple_interest()
print('The Simple Interest is', si)

Output
Source Code with Keyword argument

def simple_interest(p,r,t):
si = (p * r * t)/100
return si

si = simple_interest(p=8,r=6,t=5)
print('The Simple Interest is', si)

Output
Practical No-15
# Define a function named prime() to check whether the
number is prime or not.

Source Code

def isPrime(num):
flag = False
if num == 1:
print(num, "is not a prime number")
elif num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break

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

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


isPrime(num)

Output
Practical No-16

# Define a function named sort() to sort a list of number using


Bubble Sort.

Source Code

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr

arr = [64, 34, 25, 12, 22, 11, 90]


print("Before sorting: ", arr)
arr = bubble_sort(arr)
print("After sorting: ", arr)

Output
Practical No-17

# Define a function named convert() to Convert Decimal to


Binary, Octal and Hexadecimal no.

Source Code

def convertBinary(num):
if num >= 1:
convertBinary(num // 2)
print(num % 2,end='')

def convertOctal(num):
if num >= 1:
convertOctal(num // 8)
print(num % 8,end='')

def convertHexaDecimal(num):
if num >= 1:
convertHexaDecimal(num // 16)
print(num % 16,end='')

num = int(input('Enter the number : '))


print('The Binary no is -> ')
convertBinary(num)
print('\n')
print('The Octal no is -> ')
convertOctal(num)
print('\n')
print('The HexaDecimal no is -> ')
convertHexaDecimal(num)

Output
Practical No-18

# Define a function named text_write() in python write the records for


5 students in a file named as Student.txt and each record must contain
roll_no, name, Marks

Source Code

def text_write():
f=open('Student.txt','w')
for i in range(5):
roll=input('Enter the roll no : ')
name=input('Enter the name of the student : ')
marks=input('Enter the marks : ')
student=[roll,'\t',name,'\t',marks]
student.append('\n')
f.writelines(student)
print("Records are inserted successfully")
f.close()

text_write()

Output
Practical No-19

# Define a function named text_read() in python read records from


Student.txt and print only those student’s records who scored above
450

Source Code

def text_read():
f = open("Student.txt",'r')
data = f.readlines()
for i in data:
lst=i.split()
if(int(lst[2])>450):
print(i,end='')
f.close()

text_read()

Output
Practical No-20

# Define a function named count_a() in python to count the number of


lines in a text file ‘STORY.TXT’ which is starting with an alphabet ‘A’

Source Code

def count_a():
count=0
f = open('STORY.TXT','r')
lines=f.readlines()
for line in lines:
if(line[0] == 'A'):
count+=1
f.close()
return (count)

a_count = count_a()
print("Lines starts with A = ",a_count )

Source File

Output
Practical No-21

# Define a function named charac() to read a text file and display the
number of vowels/consonants/ uppercase/ lowercase characters from
the file separately

Source Code

def charac():
vowel,cons,upper, lower = 0, 0, 0, 0
f = open('STORY.TXT','r')
data=f.read()
for ch in data:
if ch.isalpha():
if ch in 'aeiouAEIOU':
vowel+=1
if ch not in 'aeiouAEIOU':
cons+=1
if ch.isupper():
upper+= 1
if ch.islower():
lower+= 1
f.close()
return (vowel, cons, upper, lower)

vowel,cons,upper, lower = charac()


print("No of Vowels = ",vowel)
print("No of Consonant = ",cons)
print("No of Upper case = ",upper )
print("No of Lower case = ",lower )

Source File
Output
Practical No-22

# Define a function named Count() that will read the contents of text
file named “Report.txt” and count the number of lines which starts
with either “I” or “M”

Source Code

def count():
count=0
f = open('Report.txt','r')
lines=f.readlines()
for line in lines:
if(line[0] in 'IM'):
count+=1
f.close()
return (count)

IorM_count = count()
print("Lines starts with I or M = ",IorM_count)

Source File

Output
Practical No-23

# Define a function named ISTOUPCOUNT() in python to read contents


from a text file WRITER.TXT, to count and display the occurrence of the
word ‘‘is’’ or ‘‘to’’ or ‘‘up’’

Source Code

def ISTOUPCOUNT():
count = 0
f= open('WRITER.TXT', "r")
data=f.read()
words = data.split()
for word in words:
if word in ["is","to","up"] :
count += 1
f.close()
return count

print(ISTOUPCOUNT())

Source File

Output
Practical No-24

# Define a function named bin_write() in python write the records for


10 students in a file named as Student.bin and each record must
contain roll no., name, mark

Source Code

import pickle

def bin_write():
f = open('Student.bin','wb')
for i in range(5):
roll = int(input('Enter roll no : '))
name = input('Enter name : ')
marks = int(input('Enter marks : '))
record=[roll,name,marks]
pickle.dump(record,f)
print("Records are inserted succcessfully")
f.close()

bin_write()

Output
Practical No-25

# Define a function named bin_read() in python read records from


Student.bin and print only those student’s records who’s marks are
more than 450.

Source Code

import pickle

def bin_read():
f = open('Student.bin','rb')
try:
while True:
data=pickle.load(f)
if(data[2] > 450):
print(data)
except:
f.close()

bin_read(

Output
Practical No-26

# Define A function search_bin() to search for a given roll number and


display the records, if not found display appropriate message

Source Code

import pickle

def search_bin():
f = open('Student.bin','rb')
roll=int(input('Enter roll to search :'))
found=False
try:
while True:
data=pickle.load(f)
if(int(data[0]) == roll):
print(data)
found=True
break
except:
f.close()
if(found == False):
print('Roll no not found')

search_bin()

Output
Practical No-27

# Define a function named bin_update() in python to read records from


Student.bin and update the marks of given roll no

Source Code

import pickle
import os

def bin_update():
f1 = open('Student.bin','rb')
f2=open('temp.bin','wb')
roll=int(input('Enter roll to search :'))
try:
while True:
data = pickle.load(f1)
if data[0]==roll:
data[1] = input('Enter name to be updated : ')
data[2] = int(input('Enter marks to be updated : '))
pickle.dump(data,f2)
else:
pickle.dump(data,f2)
except:
f1.close()
f2.close()
os.remove('Student.bin')
os.rename('temp.bin','Student.bin')
print('Data is updated successfully.')

bin_update()

Output
Practical No-28

# Define a function named csv_write() in python write the records for 6


Employees in a file named as Employee.csv and each record must
contain Emp_no, Emp_name, Salary

Source Code

import csv

def csv_write():
f = open('Employee.csv','w',newline='')
data=csv.writer(f)
data.writerow(['Emp_no','Emp_name','Salary'])
nested=[]
for i in range(6):
emp_no=input('Enter the emp no : ')
emp_name=input('Enter the emp name : ')
salary=input('Enter the salary : ')
emp=[emp_no,emp_name,salary]
nested.append(emp)
data.writerows(nested)
print('Records are inserted successfully')
f.close()

csv_write()

Output
Practical No-29

# Define a function named csv_read() in python read records from


Employee.csv and print only those employee’s records who’s salary is
more than 20000.

Source Code

import csv

def csv_read():
f = open('Employee.csv','r',)
csvreader=csv.reader(f)
header = next(csvreader)
rows = []
for row in csvreader:
if(int(row[2])>20000):
rows.append(row)
print(header)
print(rows)
f.close()

csv_read()

Output
Practical No-30

# Write a Python program to implement a stack using a list data-


structure

Source Code

# Python program to implement stack


# using list

# Declare a list named as "stack"


stack = [10, 20, 30]
print("Stack elements: ")
print(stack)

# PUSH operation
stack.append(40)
stack.append(50)
print("Stack elements after push opration...")
print(stack)

# POP operation
print(stack.pop(), " is removed/popped...")
print(stack.pop(), " is removed/popped...")
print(stack.pop(), " is removed/popped...")
print("Stack elements after pop operation...")
print(stack)

# TOP operation i.e., to get topmost element


print("Stack TOP:", stack[-1])

# To check whether stack is empty or not


if stack == []:
print("Stack is empty")
else:
print("Stack is not empty")
Output

You might also like