0% found this document useful (0 votes)
27 views17 pages

Python Programs for Class XII Computer Science

The document contains a student's computer science assignment submitted to their teacher Ms. Monika Arora. It includes the student's name, class, roll number, and 12 programs written by the student on various Python programming tasks like calculating square roots, factorials, counting vowels in strings, and performing operations on dictionaries, tuples, and binary files.

Uploaded by

Astral Gamer
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)
27 views17 pages

Python Programs for Class XII Computer Science

The document contains a student's computer science assignment submitted to their teacher Ms. Monika Arora. It includes the student's name, class, roll number, and 12 programs written by the student on various Python programming tasks like calculating square roots, factorials, counting vowels in strings, and performing operations on dictionaries, tuples, and binary files.

Uploaded by

Astral Gamer
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

Name: Dhruve Garg

Class: Xll-‘B’

Roll no.: 11

Subject: Computer Science

Submitted to: Ms. Monika Arora


INDEX
[Link]. PROGRAM NAME
1. Program to display square root of a number using math
module.
2. Write a function to find factorial of a given number. The
function should return the calculated factorial using return
statement.
3. Write a function to accept string as an input and to count
and display the total number of vowels present in it.
4. Input elements in a tuple and to count and display number
of even and odd number present in it using function.

5. Compute the area of rectangle on the basis of length and


breadth inputed by the user as the arguments to this
function.
6. Write a program to write dictionary to the binary file.
7. Write a program to read dictionary items from the binary
file.
8. Store and display multiple integers in and from a binary file.
9. Program for inserting/appending a record in a binary file
“[Link]”.
10. Program to read a record from the binary file “[Link]”.
11. Write a menu-driven program to perfrom all the basics
operations using dictionary on student binary file such as
inserting, reading, updating, searching and deleting a
record.
12. Write a 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) sing lists.
1. Program to display square root of a number
using math module.

import math
def cal_sqrt():
number=float(input("Enter a number: "))
sq_root=[Link](number)
#Display the square root
print("The square root of",number,"is",sq_root)

cal_sqrt()

Output:
Enter a number: 36
The square root of 36.0 is 6.0
2. Write a function to find factorial of a given number.
The function should return the calculated factorial
using return statement.

def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)

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

if num < 0:
print("Sorry, factorial for a negative number does not
exist")
elif num == 0:
print("The factorial of 0 is 1")

else:
print("The factorial of",num,"is",factorial(num))

Output:
Enter a number :8
The factorial of 8 is 40320
3. Write a function to accept string as an input and to count
and display the total number of vowels present in it.

def countVowels(str1):
count=0
for ch in str1:
if ch in "aeiouAEIOU":
count+=1
return count

# Main code
# function calls
str_input=input("Enter any String :")
count =countVowels(str_input)
print("Total no. of vowels present in the string are :",count)

Output:
Enter any String :Hello i am using function
Total no. of vowels present in the string are : 9
4. Input elements in a tuple and to count and display number
of even and odd number present in it using function.

def countEvenOdd(tup):
counteven=0
countodd=0
for i in tup:
if i % 2 ==0:
counteven += 1
else:
countodd += 1
return counteven,countodd

tup1=()
n=int(input("Enter the total elements in a tuple: "))
for i in range(n):
num=int(input("Enter the number :"))
tup1=tup1 + (num,)
count_stats=countEvenOdd(tup1)
print("Even numbers are:",count_stats[0])
print("Odd numbers are:",count_stats[1])

Output:
Enter the total elements in a tuple: 4
Enter the number :1
Enter the number :2
Enter the number :3
Enter the number :4
Even numbers are: 2
Odd numbers are: 2
5. Compute the area of rectangle on the basis of length and
breadth inputed by the user as the arguments to this
function.

def areaRectengle(length, breadth=1):


'''
Objective: To compute the area of rectangle
Input Parameters: length, breath - numeric value
Return Value: area - numeric value
'''
area = length * breadth
return area
def main():
'''
Objectives: To compute the area of rectangle based on user input
Input Parameters: None
Return Value: None
'''
print('Enter the following values for rectangle:')
lengthRect = int(input('Length : integer value: '))
breadthRect = int(input('Breadth : integer value: '))
areaRect = areaRectangle(lengthRect, breadthRect)
print('Area of rectangle is', areaRect)

if __name__ == ' __main__':


main()

Output:
Enter the following values for rectangle:
Length : integer value: 10
Breadth : integer value: 20
Area of rectangle is 200
[Link] a program to write dictionary to the
binary file.

import pickle
dict1 = {'Python':90, 'Java': 95, 'C++': 85}
f = open('bin_file.dat','wb')
[Link](dict1,f)
[Link]()

Output:
[Link] a program to read dictionary items
from the binary file.

import pickle
f = open('bin_file.dat','rb')
dict1 = [Link](f)
[Link]()
print(dict1)

Output:
{'Python': 90, 'Java': 95, 'C++': 85}
[Link] and display multiple integers in and
from a binary file.

def binfile():
import pickle # line1
file = open('[Link]','wb') # line 2
while True:
x = int(input("Enter the integer: ")) # line 3
[Link](x,file) # line 4
ans = input('Do yo want to enter more data Y / N :')
if [Link]()== 'N' : break
[Link]() # line 5
file = open('[Link]','rb') # line 6
try : # line 7
while True : # line 8
y = [Link](file) # line 9
print(y) # line 10
except EOFError : # line 11
pass
[Link]() # line 12

binfile()

Output:
Enter the integer: 7
Do yo want to enter more data Y / N :Y
Enter the integer: 5
Do yo want to enter more data Y / N :N
7
5
9. Program for inserting/appending a record in a binary
file “[Link]”.

import pickle
record=[ ]
while True:
roll_no = int(input("Enter student roll no:"))
name = input("Enter the student name:")
marks=int(input("Enter the marks obatined:"))
data=[roll_no,name,marks]
[Link](data)
choice=input("wish to enter more records (Y/N)?:")
if [Link]()=='N':
break
f=open("student","wb")
[Link](record,f)
print("Record Added")
[Link]()

Output:
Enter student roll no :6
Enter the student name: Rohit
Enter the marks obtained :499
wish to enter more records (Y/N)?: Y
Enter student roll no :5
Enter the student name :Karan
Enter the marks obtained :490
wish to enter more records (Y/N)?: N
Record Added
10. Program to read a record from the
binary file “[Link]”.

import pickle
f = open("student","rb")
stud_rec = [Link](f) # To read the object from the opened file
print("Contents of students file are:")
# reading the fields from the file
for R in stud_rec:
roll_no = R[0]
name = R[1]
marks = R[2]
print(roll_no,name, marks)
[Link]()

Output:
Contents of students file are:
6 Rohit 499
5 Karan 490
11. Write a menu-driven program to perfrom all the basics operations using
dictionary on student binary file such as inserting, reading, updating,
searching and deleting a record.

import os
import pickle

# Accepting data for Dictionary


def insertRec():
rollno=int(input("Enter roll number:"))
name = input("Enter Name:")
marks = int(input("Enter Marks:"))
# Creating the dictionary
rec = {"Rollno": rollno, "Name": name, "Marks": marks}
# Writing the dictionary
f = open("[Link]","ab")
[Link](rec, f)
[Link]()

# Reading the records


def readRec():
f = open("[Link]", "rb")
while True:
try:
rec = [Link](f)
print("Roll Num:", rec['Rollno'])
print("Name:", rec["Name"])
print("Marks:", rec["Marks"])
except EOFError:
break
[Link]()
# Searching a record based on Rollno
def searchRollNo(r) :
f = open("[Link]", "rb")
flag = False
while True:
try:
rec = [Link](f)
if rec['Roll Num'] == r:
print("Roll Num:", rec['Rollno'])
print("Name:", rec["Name"])
print("Marks:", rec["Marks"])
flag = True
except EOFError:
break
if flag == False:
print("No Record Found")
[Link]()

# Marks Modification for a RollNo


def updateMarks(r, m):
f = open("[Link]", "rb")
reclst = [ ]
while True:
try:
rec = [Link](f)
[Link](rec)
except EOFERROR:
break
[Link]()
for i in range(len(reclst)) :
if reclst[i]['Rollno'] == r :
reclst[i]['Marks'] = m
f = open("[Link]",'wb')
for x in reclst:
[Link](x, f)
[Link]()
# Deleting a record based on RollNo
def deleteRec(r):
f = open("[Link]", "rb")
recslt = [ ]
while True:
try:
rec = [Link](f)
[Link](rec)
except EOFERROR:
break
[Link]()
f = open("[Link]", 'wb')
for x in recslt:
if x['Rollno'] == r:
continue
[Link](x, f)
[Link]()

while True:
print('Type 1 to insert rec. ')
print('Type 2 to display rec. ')
print('Type 3 to search rec. ')
print('Type 4 to update rec. ')
print('Type 5 to delete rec. ')
print('Enter your choice 0 to exit')
choice = int(input("Enter your choice:"))
if choice == 0:
break
elif choice == 1:
insertRec ()
elif choice == 2:
readRec ()
elif choice == 3:
r = int(input("Enter a rollno to search:"))
searchRollNo(r)
elif choice == 4:
r = int(input("Enter a rollno:"))
m = int(input("Enter new Marks:"))
updateMarks(r, m)
elif choice == 5:
r = int(input("Enter a rollno:"))
deleteRec(r)

Output:
Type 1 to insert rec.
Type 2 to display rec.
Type 3 to search rec.
Type 4 to update rec.
Type 5 to delete rec.
Enter your choice 0 to exit
Enter your choice:1
Enter roll number:5
Enter Name:Kiran
Enter Marks:456
Type 1 to insert rec.
Type 2 to display rec.
Type 3 to search rec.
Type 4 to update rec.
Type 5 to delete rec.
Enter your choice 0 to exit
Enter your choice: 2
Roll Num: 5
Name: Kiran
Marks: 456
Type 1 to insert rec.
Type 2 to display rec.
Type 3 to search rec.
Type 4 to update rec.
Type 5 to delete rec.
Enter your choice 0 to exit
Enter your choice:0
12. Write a 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) sing lists.

s=[ ]
c="y"
while (c=="y"):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
[Link](a)
elif (choice==2):
if (s==[ ]):
print ("Stack Empty")
else:
print ("Deleted element is : ",[Link]())
elif (choice==3):
l=len(s)
for i in range(1-1,-1,-1): #To display elements from last element to first
print (s[i])
else:
print("Wrong Input")
c=input("Do you want to continue or not? ")

Output:
1. PUSH
2. POP
3. Display
Enter your choice: 2
Stack Empty
Do you want to continue or not? n

Common questions

Powered by AI

The 'pickle' module in Python simplifies file operations by allowing complex data structures to be serialized and stored in binary files. This module can convert Python objects, such as dictionaries and lists, into a byte stream, making them easier to store in files. When retrieving data, 'pickle' can deserialise the byte stream back into Python objects. This functionality is crucial in this context because it allows for the complex data manipulations described, such as storing dictionaries in a binary file and appending or reading records from it, which would be cumbersome with plain text file operations .

The document addresses the initialization of tuple elements by focusing on user input for constructing the tuple dynamically. The user is prompted to input the total number of elements, followed by entering each number, which is appended to an initially empty tuple. This dynamic construction allows for flexibility in the size and specific values of the tuple. Subsequently, the program iterates over the tuple to count even and odd numbers, demonstrating tuple usage for data analysis while emphasizing immutability and the necessity to recreate tuples for changes .

User input validation is critical in binary file operations as described, to ensure that valid and expected data types are stored and processed. Validation helps prevent errors that arise from incorrect user inputs that could lead to exceptions or corrupt data storage in the file. In the programs, prompts for inputs such as integers or specific responses like 'Y' or 'N' ensure that operations like appending or searching are performed accurately. Despite validation, there remains room for improving these programs by further refining user inputs to avoid boundary issues or unexpected data formats .

Implementing a stack using a Python list enhances understanding of basic data structure operations by demonstrating how elements can be added and removed from one end using the stack concept of LIFO (Last In, First Out). Lists in Python naturally allow operations like 'append()' for adding elements and 'pop()' for removing the last element, which corresponds directly to PUSH and POP operations in stack terminology. This implementation clarifies how stacks operate in practice and provides a practical framework for understanding how data structures can be managed in software development .

Implementing basic dictionary operations in a binary file contributes to effective data management by allowing complex objects to be stored efficiently and retrieved without loss. The menu-driven program in the document allows for inserting, reading, updating, searching, and deleting records seamlessly. Using dictionaries as a structure means data is managed in a key-value format, allowing for quick access and modification. It supports consistent data handling practices, enhancing modularity and systematic management of records, crucial for larger scale applications requiring structured and maintainable data systems .

A menu-driven program simplifies user interaction by providing a structured interface for performing various operations without manually executing different functions. It allows users to insert, read, update, search, and delete records from a binary file by selecting options from a menu. This structure improves usability by streamlining the execution flow and ensuring all operations can be performed within a single program. Additionally, it reduces the risk of errors by guiding the user through pre-defined options and processing the input data accordingly .

The recursive approach to finding the factorial of a number works by defining a base case for n = 1, where the function returns 1, and the recursive case where the function calls itself with 'n-1'. This design exemplifies the power and simplicity of recursion for mathematical functions like factorial, as it naturally aligns with how factorial is defined mathematically. However, recursion can be less efficient for large numbers due to increased memory usage from call stack growth and potential for stack overflow, unlike iterative solutions which use a simple loop .

When reading data from a binary file, the program uses a try-except block to manage errors. Specifically, it uses 'try' around the loop that reads objects from the file, and 'except EOFError' to catch the End of File error, which naturally occurs when the file's end is reached. This avoids accidental crashes from attempting to read past the last object stored in the file, ensuring the program handles file exhaustion gracefully and maintains robustness during operations .

Parameter defaulting in the function for calculating the area of a rectangle is significant because it offers flexibility in usage. By setting a default value for the breadth parameter, the function allows for scenarios where only the length is provided by the user, assuming the rectangle is a line when the breadth is 1. This enhances the function's usability and caters to diverse input scenarios without necessitating changes in the function call or extensive error handling for missing arguments .

The program for reading dictionary items from a binary file uses the 'pickle' module in Python. It opens the binary file in read-binary ('rb') mode. The 'pickle.load()' function is used to retrieve the dictionary object stored in the file. It loads the dictionary into memory, which is then printed to the console. The file is closed after loading the dictionary to free up system resources. The output would display the contents of the dictionary as stored in the binary file .

You might also like