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

class xii program file

Project

Uploaded by

pandeyvansh299
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

class xii program file

Project

Uploaded by

pandeyvansh299
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Front page

certificate
Acknowledgement
# Program1: WAP to accept a string and whether it is a palindrome or not.

str_1 = input ("Enter the string to check if it is a palindrome:")

str_1 = str_1.casefold ()

rev_str = reversed (str_1)

if list (str_1) == list (rev_str):

print ("The string is a palindrome.")

else:

print ("The string is not a palindrome.")

Output
#Program2: WAP to store students’ details like admission number, roll number, name and percentage in a dictionary and
display information on the basis of admission number.

record = dict ()

i=1

n= int (input ("How many records u want to enter: "))

while(i<=n):

Adm = input("Enter Admission number: ")

roll = input("Enter Roll Number: ")

name = input("Enter Name :")

perc = float(input("Enter Percentage : "))

t = (roll,name, perc)

record[Adm] = t

i=i+1

Nkey = record.keys()

for i in Nkey:

print("\nAdmno- ", i, " :")

r = record[i]

print("Roll No\t", "Name\t", "Percentage\t")

for j in r:

print(j, end = "\t")

Output:
# program 3: Write a program with a user-defined function with string as a parameter which replaces all vowels in the
string with ‘*’.
def strep(str):
str_lst =list(str)
for i in range(len(str_lst)):
if str_lst[i] in 'aeiouAEIOU':
str_lst[i]='*'

#to join the characters into a new string.

new_str = "".join(str_lst)
return new_str

def main():
line = input("Enter string: ")
print("Original String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
Program 4: '''implement reading from and writing to a text file. This program performs the following tasks:
Creates and writes to a text file.
Reads the content of the file.
Appends additional content to the file.
Reads the file line by line.'''
# Function to write content to a file
def write():
with open('example.txt', 'w') as file:
file.write("Hello, world!\n")
file.write("This is a text file in Python.\n")
file.write("We can add multiple lines of text.\n")
print("Data written to the file successfully.")

# Function to read the entire content of a file


def read():
try:
with open('example.txt', 'r') as file:
content = file.read()
print("File content read successfully:")
print(content)
except FileNotFoundError:
print("The file does not exist.")

# Function to append new content to the file


def append():
with open('example.txt', 'a') as file:
file.write("This is an additional line added later.\n")
print("Data appended to the file successfully.")

# Function to read the file line by line


def read_line():
try:
with open('example.txt', 'r') as file:
print("Reading the file line by line:")
for line in file:
print(line, end='') # 'end' is used to avoid double newlines
except FileNotFoundError:
print("The file does not exist.")

# Main function to execute all operations


def main():
# Step 1: Write to the file
write()

# Step 2: Read from the file


read()

# Step 3: Append new content to the file


append()

# Step 4: Read the file line by line


read_line()

# Execute the main function


if __name__ == '__main__':
main()
Program 5: 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()
Program 6: 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).....")

with open('Student_Details.csv','r',newline='') as fileobject:


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
Program 7 : '''Write a random number generator that generates random numbers between 1 and 6 (simulates a dice)’’’

import random

def roll_dice():
print (random.randint(1, 6))

print("""Welcome to my python random dice program!


To start press enter! Whenever you are over, type quit.""")

f = True
while f:
user = input(">")
if user.lower() == "quit":
f = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
Program 8 : Write a python program to implement sorting techniques based on user choice using a list data-structure.
(bubble/insertion)
Download
#BUBBLE SORT FUNCTION
def Bubble_Sort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp

#INSERTION SORT FUNCTION


def Insertion_Sort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue

# DRIVER CODE
def main():
print ("SORT MENU")
print ("1. BUBBLE SORT")
print ("2. INSERTION SORT")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]: "))
nlist = [14,46,43,27,57,41,45,21,70]
if choice==1:
print("Before Sorting: ",nlist)
Bubble_Sort(nlist)
print("After Bubble Sort: ",nlist)
elif choice==2:
print("Before Sorting: ",nlist)
Insertion_Sort(nlist)
print("After Insertion Sort: ",nlist)
else:
print("Quitting.....!")
main()
Program 9: Write a python program to implement a stack using a list data-structure.
def isempty(stk):
if stk==[]:
return True
else:
return False

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])
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
Program 10 : #WAP to input any two tuples and swap their values.

t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

t1,t2 = t2, t1

print("After Swapping: ")


print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
Program 11: Given a number, the task is to check if it is a Tech number or not.
import math
# Function to count the number of digits in a number
def count_digits(n):
count = 0
while n > 0:
n //= 10
count += 1
return count
# Returns true if n is a tech number, else false
def is_tech(n):
# Count the number of digits
count = count_digits(n)
# Return false if digits are odd
if count % 2 != 0:
return False
# Split the number in two equal halves and store their sum
half = count // 2
first_half = n // 10 ** half
second_half = n % (10 ** half)
sum_val = first_half + second_half
# Check if the square of the sum is equal to the original number
if sum_val ** 2 == n:
return True
else:
return False
# Driver code
if is_tech(81):
print("True")
else:
print("False")
if is_tech(2025):
print("True")
else:
print("False")
if is_tech(1521):
print("True")
else:
print("False")

Program 12: Print

*****
****
***
**
*
# Function to print inverted half pyramid pattern
def inverted_half_pyramid(n):
for i in range(n, 0, -1):
for j in range(1, i + 1):
print("* ", end="")
print("\r")

# Example: Inverted Half Pyramid with n = 5


n=5
inverted_half_pyramid(n)
Program 13 : # Python program to count positive and negative numbers in a List

# list of numbers
list1 = [10, -21, 4, -45, 66, -93, 1]

pos_count, neg_count = 0, 0

# iterating each number in list


for num in list1:

# checking condition
if num >= 0:
pos_count += 1

else:
neg_count += 1

print("Positive numbers in the list: ", pos_count)


print("Negative numbers in the list: ", neg_count)
Program 14: write a python code to insert the record in Mysql.
import mysql.connector
con=mysql.connector.connect(host='localhost',
password='12345',
user='root',
database='class12')
cur=con.cursor()
#for multiple records
rn=int(input("enter roll no"))
name=input("enter name")
dob=input("enter date of birth")
fee = int(input("enter fee"))
cur.execute("insert into student values ({},'{}','{}',{})".format(rn,name,dob,fee))
con.commit()
con.close()
print("row executed successfully")
Program 15: Traverse a Python list in reverse order.

list1 = [10, 20, 30, 40, 50]

# Print the list

print("Original list: ", list1)

# Reverse the list

newlist = list1[::-1]

# print the list

print("List in reverse order: ", newlist)

# another list with string and integer elements

list2 = ["Hello", 10, "world", 20]

# print the list

print("Original list: ", list2)

# Reverse the list

newlist = list2[::-1]

# print the list

print("List in reverse order: ", newlist)

You might also like