0% found this document useful (0 votes)
22 views44 pages

Xii Cs Practicals Final

Gdjsm

Uploaded by

ujjwalmaurya025
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)
22 views44 pages

Xii Cs Practicals Final

Gdjsm

Uploaded by

ujjwalmaurya025
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/ 44

Program 20: Program to enter two numbers and print the arithmetic operations like +,-,*,

/, // and %.

Solution:

#Program for Arithmetic Calculator

result = 0

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 == "/":

if val2 == 0:

print("Please enter a value other than 0")

else:

result = val1 / val2

elif op == "//":

result = val1 // val2

else:

result = val1 % val2


print("The result is :",result)
Program 21: Write a program to find whether an inputted number is perfect or not.

Solution:

# To find whether a number is perfect or not

def pernum(num):

divsum=0

for i in range(1,num):

if num%i == 0:

divsum+=i

if divsum==num:

print('Perfect Number')

else:

print('Not a perfect number')

pernum(6)

pernum(15)
Program 23: Write a Program to check if the entered number is Armstrong or not.

Solution:

# Program to check if the entered number is Armstrong or not.

#An Armstrong number has sum of the cubes of its digits is equal to the number itself

no=int(input("Enter any number to check : "))

no1 = no

sum = 0

while(no>0):

ans = no % 10;

sum = sum + (ans * ans * ans)

no = int (no / 10)

if sum == no1:

print("Armstrong Number")

else:

print("Not an Armstrong Number")


Program 24: Write a Program to find factorial of the entered number.

Solution:

#Program to calculate the factorial of an inputted number (using while loop)

num = int(input("Enter the number for calculating its factorial : "))

fact = 1

i=1

while i<=num:

fact = fact*i

i=i+1

print("The factorial of ",num,"=",fact)


Program 25: Write a Program to enter the number of terms and to print the Fibonacci
Series.

Solution:

#fibonacci

i =int(input("enter the limit:"))

x=0

y=1

z=1

print("Fibonacci series \n")

print(x, y,end= " ")

while(z<= i):

print(z, end=" ")

x=y

y=z

z=x+y
Program 26: Write a Program to enter the string and to check if it’s palindrome or not using loop.

Solution:

# Program to enter the string and check if it’s palindrome or not using ‘for’ loop.

msg=input("Enter any string : ")

newlist=[]

newlist[:0]=msg

l=len(newlist)

ed=l-1

for i in range(0,l):
if newlist[i]!=newlist[ed]:

print ("Given String is not a palindrome")

break

if i>=ed:

print ("Given String is a palindrome")

break

l=l-1

ed = ed - 1
Program 28: Write a Program to show the outputs based on entered list.

Solution:

my_list = ['p','r','o','b','e']

# Output: p

print(my_list[0])

# Output: o

print(my_list[2])

# Output: e

print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0]# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a

print(n_list[0][1],n_list[0][2],n_list[0][3])

# Output: 5

print(n_list[1][3])
Program 29: Write a Program to enter the numbers in a list using split () and to use all the functions
related to list.

Solution:

#Program to enter the numbers in a list using split () and to use all the functions related to
list.

# numbers = [int(n, 10) for n in input().split(",")]

# print (len(numbers))

memo=[]

for i in range (5):


x=int(input("enter no. \n"))

memo.insert(i,x)

i+=1

print(memo)

memo.append(25)

print("Second List")

print(memo)

msg=input("Enter any string : ")

newlist=[]

newlist[:0]=msg

l=len(newlist)

print(l)
Program 30: Write a Program to enter the number and print the Floyd’s Triangle in
decreasing order.

Solution:

#Floyd's triangle

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

for i in range(5,0,-1):

for j in range(5,i-1,-1):

print (j,end=' ')

print('\n')
Program 31: Write a Program to find factorial of entered number using user-defined module
fact().

Solution:

#Using function

import factfunc

x=int(input("Enter value for factorial : "))

ans=factfunc.fact(x)

print (ans)
Program 32: Write a Program to enter the numbers and find Linear Search, Binary Search,
Lowest Number and Selection Sort using list/array code.

Solution:

arr=[]

def array_operation():

ch=1

while ch!=10:

print('Various Array operation\n')

print('1 Create and Enter value\n')

print('2 Print Array\n')

print('3 Reverse Array\n')

print('4 Linear Search\n')

print('5 Binary Search\n')

print('6 Lowest Number \n')

print('7 Selection Sort\n')

print('10 Exit\n')

ch=int(input('Enter Choice '))

if ch==1 :

appendarray()

elif ch==2 :

print_array()

elif ch==3 :

reverse_array()

elif ch==4 :

linear_search()

elif ch==5 :

binary_search()

elif ch==6 :
min_number()

elif ch==7 :

selection_sort()

def appendarray():

for i in range(0,10):

x=int(input('Enter Number : '))

arr.insert(i,x)

def print_array():

for i in range(0,10):

print(arr[i]),

def reverse_array():

for i in range(1,11):

print(arr[-i]),

def lsearch():

try:

x=int(input('Enter the Number You want to search : '))

n=arr.index(x)

print ('Number Found at %d location'% (i+1))

except:

print('Number Not Exist in list')

def linear_search():
x=int(input('Enter the Number you want to search : '))

fl=0

for i in range(0,10):

if arr[i]==x :

fl=1
print ('Number Found at %d location'% (i+1))

break

if fl==0 :

print ('Number Not Found')

def binary_search():

x=int(input('Enter the Number you want to search : '))

fl=0

low=0

heigh=len(arr)

while low<=heigh :

mid=int((low+heigh)/2)

if arr[mid]==x :

fl=1

print ('Number Found at %d location'% (mid+1))

break

elif arr[mid]>x :

low=mid+1

else :

heigh=mid-1

if fl==0 :

print ('Number Not Found')


#

def min_number():
n=arr[0]

k=0

for i in range(0,10):

if arr[i]<n :

n=arr[i]

k=i

print('The Lowest number is %d '%(n))

def selection_sort():

for i in range(0,10):

n=arr[i]

k=i

for j in range(i+1,10):

if arr[j]<n :

n=arr[j]

k=j

arr[k]=arr[i]

arr[i]=n

array_operation()
Program 34: Write a Program to read data from data file and show Data File Handling
related functions utility in python.

Solution:

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

print(f.name)

f_contents=f.read()

print(f_contents)

f_contents=f.readlines()

print(f_contents)

f_contents=f.readline()

print(f_contents)

for line in f:

print(line, end='')

f_contents=f.read(50)

print(f_contents)

size_to_read=10

f_contents=f.read(size_to_read)

while len(f_contents)>0:

print(f_contents)

print(f.tell())

f_contents=f.read(size_to_read)
Program 35: Write a Program to read data from data file in append mode and use
writeLines function utility in python.

Solution:

#Program to read data from data file in append mode

af=open("test.txt",'a')

lines_of_text = ("One line of text here”,\

“and another line here”,\

“and yet another here”, “and so on and so forth")

af.writelines('\n' + lines_of_text)

af.close()

Program 36: Write a Program to read data from data file in read mode and count the
particular word occurrences in given string, number of times in python.

Solution:

#Program to read data from data file in read mode and

#count the particular word occurrences in given string,

#number of times in python.

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

read=f.readlines()

f.close()

times=0 #the variable has been created to show the number of times the loop runs

times2=0 #the variable has been created to show the number of times the loop runs

chk=input("Enter String to search : ")

count=0

for sentence in read:

line=sentence.split()

times+=1

for each in line:

line2=each

times2+=1

if chk==line2:

count+=1

print("The search String ", chk, "is present : ", count, "times")

print(times)

print(times2)
Program 38: Write a Program to read data from data file in read mode and append the
words starting with letter ‘T’ in a given file in python.

Solution:
#Program to read data from data file in read mode and

#append the words starting with letter ‘T’

#in a given file in python

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

read=f.readlines()

f.close()

id=[]

for ln in read:

if ln.startswith("T"):

id.append(ln)

print(id)
Program 39: Write a Program to show MySQL database connectivity in python.

Solution:

import mysql.connector

con=mysql.connector.connect(host='localhost',user='root',password='',db='school')

stmt=con.cursor()

query='select * from student;'

stmt.execute(query)

data=stmt.fetchone()

print(data)
Program 40: 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) using lists.

Solution:

#Implementation of List as stack

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 :")

s.append(a)

elif (choice==2):

if (s==[]):

print ("Stack Empty")

else:

print ("Deleted element is : ",s.pop())

elif (choice==3):

l=len(s)

for i in range(l-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? ")


Program 41: Write a program to display unique vowels present in the given word using
Stack.

Solution:

#Program to display unique vowels present in the given word

#using Stack

vowels =['a','e','i','o','u']

word = input("Enter the word to search for vowels :")

Stack = []

for letter in word:

if letter in vowels:

if letter not in Stack:

Stack.append(letter)

print(Stack)

print("The number of different vowels present in",word,"is",len(Stack))


Program 42: Write a program in Python to add, delete and display elements from a queue
using list.

Solution:

#Implementing List as a Queue - using function append() and pop()

a=[]

c='y'

while (c=='y'):

print ("1. INSERT")

print ("2. DELETE ")

print ("3. Display")

choice=int(input("Enter your choice: "))

if (choice==1):

b=int(input("Enter new number: "))

a.append(b)

elif (choice==2):

if (a==[]):

print("Queue Empty")

else:

print ("Deleted element is:",a[0])

a.pop(0)

elif (choice==3):

l=len(a)

for i in range(0,l):

print (a[i])

else:

print("wrong input")
c=input("Do you want to continue or not: ")
Program 43: Write a Program to show whether entered numbers are prime or not in the
given range.

Solution:

lower=int(input("Enter lowest number as lower bound to check : "))


upper=int(input("Enter highest number as upper bound to check: "))
c=0
for i in range(lower, upper+1):
if (i == 1):
continue

# flag variable to tell if i is prime or not


flag = 1

for j in range(2, i // 2 + 1):


if (i % j == 0):
flag = 0
break

# flag = 1 means i is prime


# and flag = 0 means i is not prime
if (flag == 1):
print(i, end = " ")
Program 44: Write a program to input any two tuples and swap their values

Solution:

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 45: Write a program with a user-defined function with string as a parameter
which replaces all vowels in the string with ‘*’

Solution:

def strep(str):
# convert string into list
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
# Each Character Check with Vowels
if str_lst[i] in 'aeiouAEIOU':
# Replace ith position vowel with'*'
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("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
Program 46: Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters and other than character and digit in the file.

Solution:

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()
Program 47: Write a Python code to find the size of the file in bytes, the number of lines,
number of words and no. of character.

Solution:

import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")

# A flag that signals the location outside the word.


pos = 'out'
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:", letters)
Program 48: 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.

Solution:

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 49: Create a binary file with roll number, name and marks. Input a roll number
and update details.

Solution:

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()
Program 50: Write a program to create a library in python and import it in a program.

Solution:

import math
def rectangle(s1,s2):
area = s1*s2
return area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
def triangle(s1,s2):
area=0.5*s1*s2
return area

# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2):
r = n1 - n2
return r
def mult(n1,n2):
m = n1*n1
return m
def div(n1,n2):
d=n1/n2
return d

# main() function
from Mypackage import Area
from Mypackage import Calculator
def main():

r = float(input("Enter Radius: "))


area =Area.circle(r)
print("The Area of Circle is:",area)
s1 = float(input("Enter side1 of rectangle: "))
s2 = float(input("Enter side2 of rectangle: "))
area = Area.rectangle(s1,s2)
print("The Area of Rectangle is:",area)
s1 = float(input("Enter side1 of triangle: "))
s2 = float(input("Enter side2 of triangle: "))
area = Area.triangle(s1,s2)
print("The Area of TriRectangle is:",area)
s = float(input("Enter side of square: "))
area =Area.square(s)
print("The Area of square is:",area)
num1 = float(input("\nEnter First number :"))
num2 = float(input("\nEnter second number :"))
print("\nThe Sum is : ",Calculator.sum(num1,num2))
print("\nThe Multiplication is : ",Calculator.mult(num1,num2))
print("\nThe sub is : ",Calculator.sub(num1,num2))
print("\nThe Division is : ",Calculator.div(num1,num2))
main()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy