ClassXII-Practical File

You might also like

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

INDEX

Sr. Practical Name Date Signature


No.
1. Input any number from user and calculate factorial of a
number.
2. Input any number from user and check it is Prime no. or not.
3. Write a program to create simple functions in Python.

4. Write a program to find sum of elements of List recursively.

5. Write a program to calculate the nth term of Fibonacci series.

6. Python program for implementation of Insertion Sort.

7. Write a Python Program to implement Binary Search


Algorithm.

8. Write a Python program to find out number of occurrence of


any word in given string.

9. Read a text file line by line and display each word separated
by a #.

10. Program to Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in the
file.

11. Write a Program to remove all the lines that contain the
character 'a' in a file and write it to another file.

12. Write a program to create a binary file with name and roll
number. Search for a given roll number and display the name,
if not found display appropriate message.

13. Create a binary file with roll number, name and marks. Input a
roll number and update the marks.

14. Write a random number generator that generates random


numbers between 1 and 6 (simulates a dice).

15. Create a CSV file by entering user-id and password, read and
search the password for given userid.

16. Write a Python program to implement a stack using list.

1
PRACTICAL FILE

Experiment 1: Date :

Program : Input any number from user and calculate factorial of a number.

# Program to calculate factorial of entered number


num = int(input("Enter any number :"))
fact = 1
n = num # storing num in n for printing
while num>1: # loop to iterate from n to 2
fact = fact * num
num-=1

print("Factorial of ", n , " is :",fact)

Output :

Enter any number :5

Factorial of 5 is : 120

Enter any number :10

Factorial of 10 is : 3628800

2
Experiment 2: Date :

Program : Input any number from user and check it is Prime no. or not.

---------------------------------------------------------------------------------------------------------------------------------------

import math

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

isPrime=True

for i in range(2,int(math.sqrt(num))+1):

if num % i == 0:

isPrime=False

if isPrime:

print("## Number is Prime ##")

else:

print("## Number is not Prime ##")

Output :

Enter any number :2

## Number is Prime ##

Enter any number :5

## Number is Prime ##

3
Experiment 3: Date :

Program: Write a program to create simple functions in Python.


------------------------------------------------------------------------------------------------------------------------------------

# Function definition is here


def changeme( mylist ):
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)

Output :
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

ii) Changing the values inside the function.

def changeme( mylist ):


mylist = [1,2,3,4]; # This would assig new reference in mylist
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

Output :

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

4
Experiment 4: Date :

Program : Write a program to find sum of elements of List recursively.

------------------------------------------------------------------------------------------------------------------------------------

#Program to find sum of elements of list recursively

def findSum(lst, num):

if num == 0:

return 0

else:
return lst[num-1] + findSum(lst, num-1)

mylist = [] # Empty List

# Loop to input in list

num = int (input("Enter how many number:"))

for i in range(num):
n = int(input("Enter Element " +str(i+1) + ":"))

mylist.append(n) #Adding number to the list

sum = findSum(mylist, len(mylist))


print("Sum of List items", mylist, "is:", sum)

Output :

Enter how many number:5


Enter Element 1:10
Enter Element 2:20
Enter Element 3:30
Enter Element 4:40
Enter Element 5:50
Sum of List items [10, 20, 30, 40, 50] is: 150

5
Experiment 5: Date :

Program : Write a program to calculate the nth term of Fibonacci series.


------------------------------------------------------------------------------------------------------------------------------------

#Program to find 'n'th term of fibonacci series

#Fibonacci series : 0,1,1,2,3,5,8,13,21,34,55,89,...

#nth term will be counted from 1 not 0

def nthfiboterm(n):

if n<=1:

return n

else:

return (nthfiboterm(n-1)+nthfiboterm(n-2))

num = int(input("Enter the 'n' term to find in fibonacci :"))

term =nthfiboterm(num)

print(num,"th term of fibonacci series is :",term)

Output :

Enter the 'n' term to find in fibonacci :5

5 th term of fibonacci series is : 5

6
Experiment 6: Date :

Python program for implementation of Insertion Sort.

------------------------------------------------------------------------------------------------------------------------------------
# Function to do insertion sort

def insertionSort(arr):

# Traverse through 1 to len(arr)

for i in range(1, len(arr)):

key = arr[i]

j = i-1

while j >=0 and key < arr[j] :

arr[j+1] = arr[j]

j -= 1

arr[j+1] = key

arr = [12, 11, 13, 5, 6]

insertionSort(arr)

print ("Sorted array is:")

for i in range(len(arr)):

print ("%d" %arr[i])

Output:

Sorted array is:


5

11
12

13

7
Experiment 7: Date :

Write a Python Program to implement Binary Search Algorithm.

-------------------------------------------------------------------------------------------------------------------------------------
def binary_search(arr, low, high, x):

# Check base case


if high >= low:

mid = (high + low) // 2

if arr[mid] == x:

return mid

elif arr[mid] > x:


return binary_search(arr, low, mid - 1, x)

# Else the element can only be present in right subarray


else:

return binary_search(arr, mid + 1, high, x)

else:
# Element is not present in the array

return -1
# Test array

arr = [ 2, 3, 4, 10, 40 ]
x = 10

result = binary_search(arr, 0, len(arr)-1, x)

if result != -1:
print("Element is present at index", str(result))

else:
print("Element is not present in array")

Output :

Element is present at index 3

8
Experiment 8: Date :

Write a Python program to find out number of occurrence of any word in given string.

------------------------------------------------------------------------------------------------------------------------------------

#Program to find the occurrence of any word in a string.

def countWord(str1, word):

s = str1.split()

count = 0

for w in s:

if w == word:

count+=1

return count

str1 = input("Enter any Sentence:")

word = input("Enter word to search in a sentence:")

count = countWord(str1, word)

if count == 0:

print("## Sorry! ", word, "not present")

else:

print("##", word,"occurs ", count, "times##")

Output :
Enter any Sentence:Welcome to Python Programming.
Enter word to search in a sentence:Python
## Python occurs 1 times##

Enter any Sentence:User defined function in Python.

Enter word to search in a sentence:Programming


## Sorry! Programming not present

9
Experiment 9:

Read a text file line by line and display each word separated by a #.

--------------------------------------------------------------------------------------------------------------------------------------

#program to read content of file line by line and display each word seperated by '#'

f = open("file1.txt")

for line in f:

words = line.split()

for w in words:

print(w + '#', end = "")

print()

f.close()

10
Experiment no. 10 Date :

Program to Read a text file and display the number of vowels/consonants/uppercase/lowercase


characters in the file.

-----------------------------------------------------------------------------------------------------------------------------------

f = open("file2.txt")

v=0

c=0

u=0

l=0

o=0

data = f.read()

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

for ch in data:

if ch.isalpha():

if ch.lower() in vowels:

v+=1

else:

c+=1

if ch.isupper():

u+=1

elif ch.islower():

l+=1

elif ch!=' ' and ch!='\n':

o += 1

print ("Total Vowels in File :", v)

print ("Total Consonants in File :", c)

print ("Total Capital letters in File :", u)


11
print ("Total Small letters in File :", l)

print ("Total other than letters in File :", o)

f.close()

12
Experiment no. 11 Date:

Write a Program to remove all the lines that contain the character 'a' in a file and write it to
another file.

#Program to read line from file and write it to another line


#Except for those line which contains letter 'a'

f1 = open("file2.txt")
f2 = open("file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully! ##”)
f1.close() f2.close()

NOTE: Content of file2.txt


a quick brown fox one two
three four five six seven
India is my country eight nine ten
bye!

OUTPUT

## File Copied Successfully! ##

NOTE: After copy content of file2copy.txt


one two three four five six
seven eight nine ten bye!

13
Experiment No. 12 Date:

Write a program to create a binary file with name and roll number. Search for a given roll number
and display the name, if not found display appropriate message.

#Program to create a binary file to store Rollno and name


#Search for Rollno and display record if found
#otherwise "Roll no. not found"

import pickle student=[]


f=open('student.dat','wb') ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :")) name =
input("Enter Name :") student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f) f.close()
f=open('student.dat','rb') student=[]
while True:
try:
student = pickle.load(f) except
EOFError:
break
ans='y'

while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :")) for s in
student:
if s[0]==r:
print("## Name is :",s[1], " ##") found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()

14
OUTPUT

Enter Roll Number :1 Enter


Name :Amit Add More ?(Y)y

Enter Roll Number :2 Enter


Name :Jasbir Add More ?(Y)y

Enter Roll Number :3 Enter


Name :Vikral Add More ?(Y)n

Enter Roll number to search :2


## Name is : Jasbir ## Search more
?(Y) :y

Enter Roll number to search :1


## Name is : Amit ## Search more
?(Y) :y

Enter Roll number to search :4


####Sorry! Roll number not found #### Search more
?(Y) :n

15
Experiment No. 13 Date:

Create a binary file with roll number, name and marks. Input a roll number and update the marks.

#Program to create a binary file to store Rollno and name


#Search for Rollno and display record if found
#otherwise "Roll no. not found"

import pickle student=[]


f=open('student.dat','wb') ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :")) name =
input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f) f.close()
f=open('student.dat','rb+') student=[]
while True:
try:
student = pickle.load(f) except
EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :")) for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##") m =
int(input("Enter new marks :")) s[2]=m
print("## Record Updated ##") found=True
break
if not found:
print("####Sorry! Roll number not found ####") ans=input("Update more ?(Y) :")
f.close()
Page : 10

16
OUTPUT

Enter Roll Number :1 Enter


Name :Amit Enter Marks :99
Add More ?(Y)y

Enter Roll Number :2 Enter


Name :Vikrant Enter Marks :88
Add More ?(Y)y

Enter Roll Number :3 Enter Name


:Nitin Enter Marks :66
Add More ?(Y)n

Enter Roll number to update :2


## Name is : Vikrant ##
## Current Marks is : 88 ## Enter new
marks :90
## Record Updated ## Update
more ?(Y) :y

Enter Roll number to update :2


## Name is : Vikrant ##
## Current Marks is : 90 ## Enter new
marks :95
## Record Updated ## Update
more ?(Y) :n

17
Experiment No. 14 Date:

Write a random number generator that generates random numbers between 1 and 6 (simulates a
dice).

---------------------------------------------------------------------------------------------------------------------------------------

import random
x = "y"

while x == "y":
# Generates a random number between 1 and 6 (including both 1 and 6)

no = random.randint(1,6)

if no == 1:

print("[-----]")

print("[ ]")

print("[ 0 ]")
print("[ ]")

print("[-----]")
if no == 2:

print("[-----]")
print("[ 0 ]")

print("[ ]")

print("[ 0 ]")
print("[-----]")

if no == 3:
print("[-----]")

print("[ ]")
print("[0 0 0]")

print("[ ]")

print("[-----]")

18
if no == 4:

print("[-----]")

print("[0 0]")
print("[ ]")

print("[0 0]")
print("[-----]")

if no == 5:

print("[-----]")

print("[0 0]")

print("[ 0 ]")
print("[0 0]")

print("[-----]")
if no == 6:

print("[-----]")

print("[0 0 0]")

print("[ ]")

print("[0 0 0]")
print("[-----]")

x=input("press y to roll again and n to exit:")

print("\n")

19
Output :

[-----]
[ ]
[0 0 0]
[ ]
[-----]

press y to roll again and n to exit:y

[-----]
[0]
[ ]
[0]
[-----]

press y to roll again and n to exit:y

[-----]
[0 0]
[ ]
[0 0]
[-----]

press y to roll again and n to exit:y

[-----]
[0 0 0]
[ ]
[0 0 0]
[-----]

press y to roll again and n to exit:n

20
Experiment No. 15 Date:

Create a CSV file by entering user-id and password, read and search the password for given userid.

import csv
with open("user_info.csv", "w") as obj:

fileobj = csv.writer(obj)

fileobj.writerow(["User Id", "password"])


while(True):

user_id = input("enter id: ")


password = input("enter password: ")

record = [user_id, password]


fileobj.writerow(record)

x = input("press Y/y to continue and N/n to terminate the program\n")

if x in "Nn":
break

elif x in "Yy":
continue

with open("user_info.csv", "r") as obj2:


fileobj2 = csv.reader(obj2)

given = input("enter the user id to be searched\n")

for i in fileobj2:
next(fileobj2)

# print(i,given)
if i[0] == given:

print(i[1])
break

21
Output:

enter id: cbse

enter password: 123

press Y/y to continue and N/n to terminate the program


y

enter id: computer_science


enter password: python

press Y/y to continue and N/n to terminate the program

enter id: class12

enter password: cs083


press Y/y to continue and N/n to terminate the program

n
enter the user id to be searched

cbse

123

22
Experiment No. 16 Date:

Write a Python program to implement a stack using list.

---------------------------------------------------------------------------------------------------------------------------------------

def isEmpty(stk):
if stk == []:

return True
else:

return False

def add(stk,item):

stk.append(item)
top = len(stk)-1

def remove(stk):

if(stk==[]):

print("Stack empty;UNderflow")

else:

print("Deleted student is :",stk.pop())

def display(stk):

if isEmpty(stk):

print("Stack empty ")

else :

top = len(stk)-1

print(stk[top],"<-top")
for a in range(top-1,-1,-1):

print(stk[a])

stack=[]
23
top = None

while True:

print("STACK OPERATION:")

print("1.ADD student")
print("2.Display stack")

print("3.Remove student")
print("4.Exit")

ch = int(input("Enter your choice(1-4):"))

if ch==1:

rno = int(input("Enter Roll no to be inserted :"))

sname = input("Enter Student name to be inserted :")


item = [rno,sname]

add(stack,item)
input()

elif ch==2:

display(stack)

input()

elif ch==3:
remove(stack)

input()

elif ch==4:

break

else:

print("Invalid choice ")

input()

24
Output :
STACK OPERATION:
1.ADD student
2.Display stack
3.Remove student
4.Exit
Enter your choice(1-4):1
Enter Roll no to be inserted :11
Enter Student name to be inserted :ATHANG

STACK OPERATION:
1.ADD student
2.Display stack
3.Remove student
4.Exit
Enter your choice(1-4):1
Enter Roll no to be inserted :12
Enter Student name to be inserted :SUJATA

STACK OPERATION:
1.ADD student
2.Display stack
3.Remove student
4.Exit
Enter your choice(1-4):1
Enter Roll no to be inserted :13
Enter Student name to be inserted :MEENA

STACK OPERATION:
1.ADD student
2.Display stack
3.Remove student
4.Exit
Enter your choice(1-4):1
Enter Roll no to be inserted :14
Enter Student name to be inserted :SUSHIL

STACK OPERATION:
1.ADD student
2.Display stack
3.Remove student
4.Exit
Enter your choice(1-4):4

25

You might also like